[英]Mocha, should.js, and Promise catch callback
我正在嘗試使用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)
我不明白什么?
您可能不should
加載實現err.message.should.equal()
,因此運行時將引發異常。
通常,除非在承諾鏈中添加另一個.catch()
子句(如@Bergi在評論中建議的那樣.catch()
否則將忽略在.catch()
引發的異常。
另一個選擇是使用更詳盡的promise實現,該警告會警告您未處理的拒絕,例如bluebird
,它會向您顯示以下內容:
Unhandled rejection TypeError: Cannot read property 'equal' of undefined
at ...
您可以這樣:
promise.catch(function(err) {
done(err.message !== 'No reason.' ? new Error('Failed') : undefined); // => Never reached.
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.