首页 文章

Mocha,should.js和Promise捕获回调

提问于
浏览
0

我试图在使用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)

我不明白的是什么?

2 回答

  • 0

    您可能没有加载 should 来实现 err.message.should.equal() ,因此运行时抛出异常 .

    通常, .catch() 中抛出的异常将被忽略,除非您向您的承诺链添加另一个 .catch() 子句(正如@Bergi在评论中所建议的那样) .

    另一个选择是使用一个更精细的promises实现来警告你未处理的拒绝,比如bluebird,它会告诉你:

    Unhandled rejection TypeError: Cannot read property 'equal' of undefined
    at ...
    
  • 1

    你可以这样做:

    promise.catch(function(err) {
      done(err.message !== 'No reason.' ? new Error('Failed') : undefined);                                     // => Never reached.
    });
    

相关问题