Node.js 测试异步代码时如何检查Mocha中的断言错误
当用Mocha测试异步代码时,我的一个断言失败了,Mocha所做的就是报告一个超时错误。有没有办法改善这一点?如何知道哪些断言失败以及为什么失败Node.js 测试异步代码时如何检查Mocha中的断言错误,node.js,mocha.js,Node.js,Mocha.js,当用Mocha测试异步代码时,我的一个断言失败了,Mocha所做的就是报告一个超时错误。有没有办法改善这一点?如何知道哪些断言失败以及为什么失败 mocha Contact #getContacts() 1) should return at least 1 contact 0 passing (3s) 1 failing 1) Contact #getContacts() should return at least 1 contact:
mocha
Contact
#getContacts()
1) should return at least 1 contact
0 passing (3s)
1 failing
1) Contact #getContacts() should return at least 1 contact:
Error: timeout of 3000ms exceeded. Ensure the done() callback is being called in this test.
代码:
你应该像这样回报承诺:
it('should return at least 1 contact', function() {
return contact.getContacts().then(function(contacts) {
assert.equal(4,2);
});
});
当断言抛出一个错误时,似乎错误被吞没,并且从不显示,并且在断言抛出之后的代码也被跳过 像这样尝试(捕捉拒绝): 或者使用catch(rejectFunc)代替then(null,rejectFunc)和bluebird之类的lib
Idebehold的答案也很好。我还不知道mocha直接支持Promissions,我总是使用done参数,因为我知道如果我有一个没有堆栈跟踪的超时,那么在这个测试中有一个被吞没的错误。问题是断言失败,这会引发异常。这导致承诺被拒绝,但没有人注意到。您的代码只检查承诺是否成功。如果您退还了承诺,那么摩卡将进行检查,如果承诺被拒绝,测试将失败 所以你想要
it('should return at least 1 contact', function() {
return contact.getContacts().then(function(contacts) {
assert.equal(4,2);
});
});
尝试使用
this.setTimeout(10000)
为这个特定的测试设置一个更高的超时,以确保这不仅仅是你的getContacts()
需要多长时间才能完成的问题。它就像一个符咒。谢谢这是为了处理像“假阳性”这样的情况。是不是“Iiyan?”muneermuhammed是的,没错。
it('should return at least 1 contact', function(done) {
contact.getContacts().then(function(contacts) {
assert.equal(4,2)
done()
}).then(null, function (err) {
console.error(err);
done(err);
});
})
it('should return at least 1 contact', function() {
return contact.getContacts().then(function(contacts) {
assert.equal(4,2);
});
});