我用 mocha、chai 和 supertest 编写了一个简单的单元测试。
describe('controller.CWEManagementAPI', function () {
it('should be able to say hello', function() {
var request = require('supertest')
, express = require('express');
var app = express();
app.get('/user', function(req, res){
res.send(201, { name: 'tobi' });
});
request(app)
.get('/user')
.set('Accept', 'application/json')
.expect(200)
.end(function(err, res){
if (err) return done(err);
console.log('test');
assert.equal( res.body.name, 'tobi');
done()
});
});
});
但问题是:console.log('test')
没有执行。
所以我认为 assert.equal( res.body.name, 'tobi');
也没有执行。
所以我在没有单元测试的情况下编写代码,例如:
var request = require('supertest')
, express = require('express');
var app = express();
app.get('/user', function(req, res){
res.send(201, { name: 'tobi' });
});
request(app)
.get('/user')
.expect('Content-Type', /json/)
.expect('Content-Length', '20')
.expect(201)
.end(function(err, res){
if (err) throw err;
console.log(res.body.name);
console.log('done');
process.exit();
});
console.log()
全部执行。所以我不知道为什么第一个代码不能显示日志信息。
最佳答案
您尝试运行的是使用 mocha 的异步测试。因此,测试用例应该收到一个回调参数,以便在完成其操作后调用。
你在最后调用了 done() 但还没有收到它作为参数。
改变
it('should be able to say hello', function() {
}
到
it('should be able to say hello', function(done) {
}
关于node.js - 使用 express、node.js 构建的 restful api 的单元测试日志记录(使用 mocha、supertest 和 chai),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14333491/