使用 Mocha/Chai 测试异步函数时,未能匹配预期总是会导致超时

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

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

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 不匹配时,我收到的不是消息说它们不匹配,而是通用超时消息:

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

好像期望是暂停脚本什么的。我该如何解决?这使得调试几乎不可能。

预期不会暂停脚本,它会在您点击done回调之前抛出异常,但由于它不再在测试方法的内部context 它也不会被测试套件选中,所以你永远不会完成测试。然后你的测试就会旋转直到达到超时。

您需要在某个时候捕获异常,在回调或 Promise 的错误处理程序中。

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

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-as-promised。这为您提供了一些用于此类测试的实用工具。