使用 mocha/chai 进行测试时获得 UnhandledPromiseRejectionWarning [英] Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

查看:20
本文介绍了使用 mocha/chai 进行测试时获得 UnhandledPromiseRejectionWarning的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在测试一个依赖于事件发射器的组件.为此,我想出了一个使用 Promises with Mocha+Chai 的解决方案:

So, I'm testing a component that relies on an event-emitter. To do so I came up with a solution using Promises with Mocha+Chai:

it('should transition with the correct event', (done) => {
  const cFSM = new CharacterFSM({}, emitter, transitions);
  let timeout = null;
  let resolved = false;
  new Promise((resolve, reject) => {
    emitter.once('action', resolve);
    emitter.emit('done', {});
    timeout = setTimeout(() => {
      if (!resolved) {
        reject('Timedout!');
      }
      clearTimeout(timeout);
    }, 100);
  }).then((state) => {
    resolved = true;
    assert(state.action === 'DONE', 'should change state');
    done();
  }).catch((error) => {
    assert.isNotOk(error,'Promise error');
    done();
  });
});

在控制台上,即使调用了拒绝函数,我也会收到UnhandledPromiseRejectionWarning",因为它会立即显示消息AssertionError: Promise error"

On the console I'm getting an 'UnhandledPromiseRejectionWarning' even though the reject function is getting called since it instantly shows the message 'AssertionError: Promise error'

(node:25754) UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:2):AssertionError:承诺错误:预期{ Object (message, showDiff, ...) } 是假的

(node:25754) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): AssertionError: Promise error: expected { Object (message, showDiff, ...) } to be falsy

  1. 应该使用正确的事件进行转换

然后,2秒后我得到

错误:超过了 2000 毫秒的超时时间.确保 done() 回调是在本次测试中被调用.

Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

自从执行了 catch 回调以来,这更奇怪(我认为由于某种原因,断言失败阻止了其余的执行)

Which is even weirder since the catch callback was executed(I think that for some reason the assert failure prevented the rest of the execution)

现在有趣的是,如果我注释掉 assert.isNotOk(error...) 测试运行良好,控制台中没有任何警告.在执行捕获的意义上它仍然失败".
但是,我仍然无法通过承诺来理解这些错误.有人能指教我吗?

Now the funny thing, if I comment out the assert.isNotOk(error...) the test runs fine without any warning in the console. It stills 'fails' in the sense that it executes the catch.
But still, I can't understand these errors with promise. Can someone enlighten me?

推荐答案

问题是由这个引起的:

.catch((error) => {
  assert.isNotOk(error,'Promise error');
  done();
});

如果断言失败,则会抛出错误.这个错误将导致 done() 永远不会被调用,因为代码在它之前出错了.这就是超时的原因.

If the assertion fails, it will throw an error. This error will cause done() never to get called, because the code errored out before it. That's what causes the timeout.

未处理的承诺拒绝" 也是由失败的断言引起的,因为如果在 catch() 处理程序中抛出错误,并且没有不是后续的 catch() 处理程序,错误将被吞下(如 这篇文章).UnhandledPromiseRejectionWarning 警告提醒您注意这一事实.

The "Unhandled promise rejection" is also caused by the failed assertion, because if an error is thrown in a catch() handler, and there isn't a subsequent catch() handler, the error will get swallowed (as explained in this article). The UnhandledPromiseRejectionWarning warning is alerting you to this fact.

一般来说,如果你想在 Mocha 中测试基于 promise 的代码,你应该依赖 Mocha 本身已经可以处理 promise 的事实.你不应该使用 done(),而是从你的测试中返回一个 promise.然后 Mocha 会自己捕捉任何错误.

In general, if you want to test promise-based code in Mocha, you should rely on the fact that Mocha itself can handle promises already. You shouldn't use done(), but instead, return a promise from your test. Mocha will then catch any errors itself.

像这样:

it('should transition with the correct event', () => {
  ...
  return new Promise((resolve, reject) => {
    ...
  }).then((state) => {
    assert(state.action === 'DONE', 'should change state');
  })
  .catch((error) => {
    assert.isNotOk(error,'Promise error');
  });
});

这篇关于使用 mocha/chai 进行测试时获得 UnhandledPromiseRejectionWarning的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆