Javascript 单元测试expressjs应用程序
我正在为以下模块添加单元测试。基本上,我希望确保使用/和相应的处理程序Javascript 单元测试expressjs应用程序,javascript,node.js,unit-testing,express,Javascript,Node.js,Unit Testing,Express,我正在为以下模块添加单元测试。基本上,我希望确保使用/和相应的处理程序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 serv
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没有定义static),我无法完全理解正确的处理方法。作为构造函数的this.express()
真的让我抓狂。我想不出在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);
})
})
我建议您将应用程序分为两个文件:包含所有应用程序代码并随module.exports一起返回的app.js文件,以及需要app.js并将其传递给新http server listen方法的server.js文件。
这样,您就可以编写符合app.js要求的测试
这就是使用express generator创建的默认应用程序的工作方式。Colonnello我猜单元测试与集成测试不同。。。这个例子是一个集成testP.M,你是对的。我不太清楚。这不是单元测试,但它是按路线进行测试的方法,在express开发中使用最多,但我也在express app中进行单元测试,因此我的答案不是不正确的,而是不完整的。。