使用superagent +的Mocha测试承诺超时,而不是因“期望"而失败 [英] Mocha tests using superagent + promises timeout rather than fail with 'expect'
问题描述
我正在使用mocha
对外部Web服务运行许多集成测试.我使用superagent-promise
进行请求/响应处理,并且使用expect
作为我的断言库.
I'm using mocha
to run a number of integration tests against an external web service. I use superagent-promise
for the request/response handling, and I'm using expect
as my assertion library.
对于其中的某些测试,我需要将大量请求链接在一起,因此,promise非常有用.但是,我注意到我的测试现在由于超时(并且没有错误消息)而不是错误消息本身而失败.举一个简单的例子:
For some of these tests I need to chain a large number of requests together, so the promises have been very helpful. However I'm noticing that my tests are now failing with a timeout (and no error message) rather than with the error message itself. As a simple example:
it('[MESSAGES-1] cannot be posted without an auth token', function(done) {
agent.post(config.webRoot + '/rooms/ABC/messages').send({
content: 'This is a test!'
}).end().then(function(res) {
// Not expected
}, function(err) {
expect(err.status).toBe(401)
done()
})
})
按预期工作并通过:
Messages
✓ [MESSAGES-1] cannot be posted without an auth token
但是,如果我更改断言以期望使用不同的状态代码:
However if I alter my assertion to expect a different status code:
expect(err.status).toBe(200) // This should fail
然后测试失败并超时!
1) Messages [MESSAGES-1] cannot be posted without an auth token:
Error: timeout of 1000ms exceeded. Ensure the done() callback is being called in this test.
这是常见问题吗?有什么解决方法或可以调整的地方吗?我不想失去使用诺言的能力.
Is this a common problem? Is there a workaround or tweak I can make? I don't want to lose the ability to use promises.
推荐答案
这是一个已知问题吗?
Is this a known issue?
这实际上不是问题.
问题是expect(err.status).toBe(200)
引发了一个错误,该错误被.then
内部吞没了,并导致代码永远无法到达done()
.您应该将代码重组为以下内容:
The problem is that expect(err.status).toBe(200)
throws an error that is swallowed inside the .then
and which causes the code to never reach done()
. You should restructure you code to the following:
it('[MESSAGES-1] cannot be posted without an auth token', function(done) {
agent.post(config.webRoot + '/rooms/ABC/messages').send({
content: 'This is a test!'
}).end()
.then(function(res) {
// Not expected
}, function(err) {
expect(err.status).toBe(401)
done()
})
.catch(function(err) {
done(err); //report error thrown in .then
})
})
这样,您可以捕获并报告expect(err.status).toBe(200)
引发的错误.
This way you catch and report the error thrown by expect(err.status).toBe(200)
.
这篇关于使用superagent +的Mocha测试承诺超时,而不是因“期望"而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!