使用Mocha/Chai测试异步功能时,未能符合期望总是会导致超时 [英] When testing async functions with Mocha/Chai, a failure to match an expectation always results in a timeout

查看:78
本文介绍了使用Mocha/Chai测试异步功能时,未能符合期望总是会导致超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一些基本的东西:

For example, I have something basic like this:

it.only('tests something', (done) => {
  const result = store.dispatch(fetchSomething());
  result.then((data) => {
    const shouldBe = 'hello';
    const current = store.something;
    expect(current).to.equal(shouldBe);
    done();
  }
});

currentshouldBe不匹配时,我收到一条通用超时消息,而不是一条消息,指出它们不匹配:

When current does not match shouldBe, instead of a message saying that they don't match, I get the generic timeout message:

错误:超时超过2000毫秒.确保已完成done()回调 在此测试中被调用.

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

就好像期望正在暂停脚本之类的东西一样.我该如何解决?这使得调试几乎变得不可能.

It's as if the expectation is pausing the script or something. How do I fix this? This is making debugging nearly impossible.

推荐答案

期望不是暂停脚本,它会在您按下done回调之前引发异常,但是由于它是不再在测试方法的上下文中,测试套件也不会使用它,因此您永远都不会完成测试.然后您的测试就会旋转直到达到超时为止.

The expectation is not pausing the script, it is throwing an exception before you hit the done callback, but since it is no longer inside of the test method's context it won't get picked up by the test suite either, so you are never completing the test. Then your test just spins until the timeout is reached.

您有时需要在回调或Promise的错误处理程序中捕获异常.

You need to capture the exception at some point, either in the callback or in the Promise's error handler.

it.only('tests something', (done) => {
  const result = store.dispatch(fetchSomething());
  result.then((data) => {
    const shouldBe = 'hello';
    const current = store.getState().get('something');
    try {
      expect(current).to.equal(shouldBe);
      done();
    } catch (e) {
      done(e);
    } 
  });
});

OR

it.only('tests something', (done) => {
  const result = store.dispatch(fetchSomething());
  result.then((data) => {
    const shouldBe = 'hello';
    const current = store.getState().get('something');
    expect(current).to.equal(shouldBe);

  })
  .catch(done);
});

修改

如果您不反对引入另一个库,则有一个相当不错的库调用 chai -按承诺.这为您提供了一些不错的工具来进行这种测试.

If you are not opposed to bringing in another library, there is a fairly nice library call chai-as-promised. That gives you some nice utilities for this kind of testing.

这篇关于使用Mocha/Chai测试异步功能时,未能符合期望总是会导致超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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