我有以下模块,我正致力于为其添加单元测试。基本上我想确保用/和相应的处理程序this.express.static('www/html')
调用app.use,我还想确保使用正确的端口调用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()
作为构造函数真的在抛弃我。我无法弄清楚模拟我想要在快递中验证的电话的正确方法。
答案 0 :(得分:3)
您可以使用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;
});
使用Mocha:
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的server.js文件并将其传递给新的http服务器监听方法。 这样你就可以编写需要app.js的测试。
这是使用快速生成器创建的默认应用程序的工作方式。