【发布时间】:2015-11-17 09:13:40
【问题描述】:
我正在尝试在 mocha 的异步承诺失败测试中断言正确的错误消息,但我的测试没有通过,我不知道为什么。
这是代码 - 承诺是
'use strict';
let getFailingPromise = function() {
return new Promise(function(resolve, reject) {
// simply fail on the next tick
setTimeout(function() {
reject(new Error('No reason.'));
});
});
}
describe('failing promise catcher', function() {
it('should fail and I should catch it', function(done) {
let promise = getFailingPromise();
promise.catch(function(err) {
console.log('Error message:', err.message); // => Error message: No reason.
console.log(err.message === 'No reason.'); // => true
err.message.should.equal('No reason.');
done(); // => Never reached.
});
});
});
我知道 Mocha 无法捕获异步异常。但是上面的代码很干净,没有抛出错误——或者不应该有任何错误。
编辑:添加调用的输出:
[zlatko@obelix ~/tmp]$ mocha test.spec.js
failing promise catcher
Error message: No reason.
true
1) should fail and I should catch it
0 passing (2s)
1 failing
1) failing promise catcher should fail and I should catch it:
Error: timeout of 2000ms exceeded
at null.<anonymous> (/usr/lib/node_modules/mocha/lib/runnable.js:158:19)
at Timer.listOnTimeout (timers.js:89:15)
我不明白什么?
【问题讨论】:
-
记录你的err.message类型,看看它是否是一个对象,兄弟
-
使用最新的 mocha,您只需从测试中返回 promise,无需添加 done 回调。如果您告诉
done()未到达,您一定会看到错误,对吧?哪一个? -
我知道我可以回报一个承诺。我想断言我从被拒绝的呼叫中得到的错误的属性,这就是我这样做的原因。我已经显示了错误,让我显示整个输出。
-
@KevinSimple 它是一个字符串 - 看到
err.message === 'No reason.'中的三倍相等? -
@Zlatko 你使用的是什么
Promise实现?
标签: javascript promise mocha.js should.js