[英]Unit testing expressjs application
我有以下模塊,我正在為其添加單元測試。 基本上,我想確保使用/和適當的處理程序this.express.static('www/html')
調用app.listen
,我還想確保使用正確的端口調用app.listen
。
function WebService(express, logger) {
this.express = express;
this.log = logger;
this.port = 3000;
}
// init routes and start the server
WebService.prototype.start = function start() {
var app = this.express();
// Setup routes
app.use('/', this.express.static('www/html'));
// Startup the server
app.listen(this.port);
this.log.info('Starting webserver on port %s', this.port);
};
module.exports = WebService;
如果刪除app.use(用簡單的app.get代替),則可以通過將其傳遞到單元測試中的構造函數中來進行偵聽測試
var express_stub = function() {
var tmpObj = {
get: function() {},
listen: listen_stub // sinonjs stub
};
return tmpObj;
};
當我切換到在路由中使用this.express.static
時,結果就落空了(可能是因為this.express沒有定義靜態),我無法完全理解正確的處理方式。 作為構造函數的this.express()
真的讓我失望。 我無法弄清楚模擬要驗證的電話的正確方法。
您可以使用Supertest
var request = require('supertest')
, express = require('express');
var app = express();
app.get('/user', function(req, res){
res.send(200, { name: 'tobi' });
});
request(app)
.get('/user')
.expect('Content-Type', /json/)
.expect('Content-Length', '20')
.expect(200)
.end(function(err, res){
if (err) throw err;
});
使用摩卡:
describe('GET /users', function(){
it('respond with json', function(done){
request(app)
.get('/user')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, done);
})
})
我建議您將應用程序分為兩個文件:包含所有應用程序代碼的app.js並通過module.exports返回它;以及需要app.js並將其傳遞到新的http服務器監聽方法的server.js文件。 這樣,您可以編寫需要執行app.js的測試。
這就是使用Express Generator創建的默認應用程序的工作方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.