【问题标题】:Mocha, should.js, and Promise catch callbackMocha、should.js 和 Promise 捕获回调
【发布时间】: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


【解决方案1】:

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

一般来说,.catch() 中抛出的异常将被忽略,除非您将另一个 .catch() 子句添加到您的承诺链中(正如 @Bergi 在 cmets 中所建议的那样)。

另一种选择是使用更精细的 promises 实现,它会警告您未处理的拒绝,例如 bluebird,它会向您显示:

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

【讨论】:

  • 是的,就是这样。现在得去构建另一个最小的例子,看看为什么我的实际代码失败了。 Bergi 建议的另一个抓钩会有所帮助。
【解决方案2】:

你可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 2013-12-10
    • 2013-09-06
    • 1970-01-01
    相关资源
    最近更新 更多