当使用Mocha/Chai测试异步函数时,与期望值不匹配总是会导致超时

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

本文关键字:不匹配 期望值 超时 Mocha Chai 函数 异步 测试      更新时间:2023-09-26

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

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

错误:超过了2000ms的超时时间。确保done()回调正在在该测试中调用。

这就好像期望是暂停脚本或其他什么。我该如何解决这个问题?这使得调试几乎不可能。

期望的不是暂停脚本,而是在您调用done回调之前抛出异常,但由于它不再在测试方法的上下文中,它也不会被测试套件接收,因此您永远不会完成测试。然后你的测试只是旋转,直到达到超时。

您需要在某个时刻捕获异常,无论是在回调中还是在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);
});

编辑

如果你不反对引进另一个图书馆,有一个相当不错的图书馆叫柴。这为这种测试提供了一些不错的实用程序。