2011-09-05 105 views
0

如何测试这样的函数?Node.js:如何测试函数

app.post '/incoming', (req,res) -> 
    console.log "Hello, incoming call!" 
    message = req.body.Body 
    from = req.body.From 

    sys.log "From: " + from + ", Message: " + message 
    twiml = '<?xml version="1.0" encoding="UTF-8" ?>\n<Response>\n<Say>Thanks for your text, we\'ll be in touch.</Say>\n</Response>' 
    res.send twiml, {'Content-Type':'text/xml'}, 200 

我还没有选择任何测试框架。我不明白如何测试。

谢谢!

回答

1

测试很简单。您只需创建一个启动快速服务器的单元测试,创建一个http POST并断言您的HTTP发布正常并获得正确的输出。使用vows-is。文件夹test在(对不起,没有CoffeeScript的)

var is = require("vows-is"), 
    app = require("../src/app.js"); 

is.config({ 
    "server": { 
     "factory": function _factory(cb) { cb(app); } 
    } 
}); 

is.suite("http request test").batch() 

    .context("a request to POST /incoming") 
     // make a POST request 
     .topic.is.a.request({ 
      "method": "POST", 
      "uri": "http://localhost:8080/incoming", 
      // set the request body (req.body) 
      "json": { 
       "Body": ..., 
       "From": ... 
      } 
     }) 
     .vow.it.should.have.status(200) 
     .vow.it.should.have 
      .header("content-type", "text/xml") 
     .context("contains a body that") 
      .topic.is.property('body') 
      .vow.it.should.be.ok 
      .vow.it.should.include.string('<?xml version="1.0" encoding="UTF-8" ?>\n<Response>\n<Say>Thanks for your text, we\'ll be in touch.</Say>\n</Response>') 

// run the test suite 
.suite().run({ 
    reporter: is.reporter 
}, function() { 
    is.end(); 
}); 

这些信息存储在一个文件http-test.js。然后只需运行

$ npm install vows-is 
$ node test/http-test.js 

看到example of exporting your serverSetup function

+0

改变CB(serverSetup()); 以cb(serverSetup); Express使代码工作得很好!谢谢 – donald

+0

@donald因为'cb'当前接受'undefined'作为有效参数。这是没有记录的,也不是API的一部分。这可能会或可能不会在未来版本的誓言中发生变化。它目前工作但不是面向未来(使用风险自负!) – Raynos

+0

但它不适用于“()”。我有app = module.exports = express.createServer() 在我的server.js – donald

2

我更喜欢更轻的语法nodeunit,与request联合制作的HTTP请求。你会创建一个test/test.coffee文件看起来像

request = require 'request' 

exports['Testing /incoming'] = (test) -> 
    request 'http://localhost:3000/incoming', (err, res, body) -> 
    test.ok !err 
    test.equals res.headers['content-type'], 'text/xml' 
    test.equals body, '<?xml version="1.0" encoding="UTF-8" ?>\n<Response>\n<Say>Thanks for your text, we\'ll be in touch.</Say>\n</Response>' 
    test.done() 

,并从运行另一个文件(或许你Cakefile)与

{reporters} = require 'nodeunit' 
reporters.default.run ['test']