【发布时间】:2017-07-18 15:24:19
【问题描述】:
在使用 Mocha & Chai 为项目编写测试时,我注意到我可以让 true.should.be.false 失败,但是当被测变量来自承诺并且预期失败时,Mocha 会超时:Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
以下是我尝试过的事情(以及解决方案)的示例,希望将来能对某人有所帮助。
const chai = require('chai');
const should = chai.should();
const assert = chai.assert;
function getFoo() {
return new Promise((resolve, reject) => {
resolve({bar: true});
});
}
describe('Example for StackOverflow', function() {
it('will fail as expected', function() {
true.should.be.false;
});
it('will also fail as expected', function() {
var foo = {
bar: true
};
foo.bar.should.be.false;
});
it('times out instead of fails', function(done) {
getFoo().then(data => {
data.bar.should.be.false;
done();
});
});
it('times out instead of fails even without arrow notation', function(done) {
getFoo().then(function(data) {
data.bar.should.be.false;
done();
});
});
it('should throws an error when the expectation fails, but the done() in catch() doesnt seem to matter', function(done) {
getFoo().then(data => {
data.bar.should.be.false;
done();
})
.catch(error => {
console.error(error);
done();
})
.catch(error => {
console.error(error);
done();
});
});
it('still throws an error in the catch() if I try to use assert.fail() inside the catch to force a failure', function(done) {
getFoo().then(data => {
data.bar.should.be.false;
done();
})
.catch(error => {
console.error(error);
assert.fail(0, 1);
done();
})
.catch(error => {
console.error(error);
done();
});
});
});
作为参考,这里有几个版本:
- 节点:v5.12.0
- 柴:v4.1.0
- 摩卡:v3.4.2
这与node.js how to get better error messages for async tests using mocha 的不同之处在于我专门讨论了当should 检测到失败并抛出由于未返回承诺而未捕获的错误时发生的超时。他们的解决方案侧重于使用done- 我不需要它,因为它会将承诺返回给 Mocha,以便它可以捕获错误。
【问题讨论】:
-
您的问题与其他问题完全相同。您收到一个无意义的错误,因为您正在吞咽异常。未能返回被拒绝的失败是您可以吞下异常的众多方法之一。同样的问题,同样的解决方案:不要吞下异常或拒绝失败。
-
您的陈述是正确的,但另一个问题更关注
done回调而不是返回承诺。谢谢。