timetofly
timetofly

Reputation: 3077

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

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.

Upvotes: 2

Views: 875

Answers (1)

paulpdaniels
paulpdaniels

Reputation: 18663

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.

Upvotes: 2

Related Questions