2011-09-05 27 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']