我有这段代码使用 supertest 和 mocha:
import request from 'supertest';
//....
var newGame;
describe('Creating game', function() {
beforeEach(function(done) {
request(app)
.post('/api/games')
.send({
owner: 'Mr. X',
})
.expect(201)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) {
return done(err);
}
newGame = res.body;
done();
});
});
describe('the created game', function() {
it('should name the specified owner', function() {
newGame.owner.should.equal('Mr. X');
});
...
})
});
当服务器代码抛出一些异常(例如访问 undefined object 的属性)时,我会得到这个堆栈跟踪
Error: expected 201 "Created", got 500 "Internal Server Error"
at Test._assertStatus (D:\Codes\theApp\node_modules\supertest\lib\test.js:232:12)
at Test._assertFunction (D:\Codes\theApp\node_modules\supertest\lib\test.js:247:11)
at Test.assert (D:\Codes\theApp\node_modules\supertest\lib\test.js:148:18)
at Server.assert (D:\Codes\theApp\node_modules\supertest\lib\test.js:127:12)
at emitCloseNT (net.js:1521:8)
而不是实际的错误,例如“访问未定义的属性”。我怎样才能得到实际的错误?
最佳答案
可能有很多方法可以解决这个问题,但我认为 mocha 或 supertest 无法访问导致 500 发生的实际错误。
你用什么来创建app
?如果是 Express,例如 error-handling middleware可以在测试期间添加,这会导致将任何 500 诱导错误记录到控制台。
例如这样:
function logErrors (err, req, res, next) {
console.error(err.stack)
next(err)
}
const request = supertest(app.use(logErrors))
关于node.js - 在 mocha 中运行 supertest 时如何获取实际的服务器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34699457/