When testing async functions with Mocha/Chai, a failure to match an expectation always results in a timeout

雨燕双飞 提交于 2019-12-11 09:58:42

问题


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();
  }
});

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

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.


回答1:


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.

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);
});

Edit

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.



来源:https://stackoverflow.com/questions/33748343/when-testing-async-functions-with-mocha-chai-a-failure-to-match-an-expectation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!