javascript - 使用 Mocha/Chai 测试异步函数时,无法满足期望总是会导致超时

标签 javascript unit-testing asynchronous mocha.js chai

例如,我有这样的基本内容:

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.

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

最佳答案

期望不是暂停脚本,而是在您点击完成回调之前抛出异常,但由于它不再位于测试方法的上下文中,因此也不会被测试套件拾取,因此您永远无法完成测试。然后你的测试就会一直旋转,直到达到超时为止。

您需要在回调或 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 。这为您提供了一些用于此类测试的不错的实用程序。

关于javascript - 使用 Mocha/Chai 测试异步函数时,无法满足期望总是会导致超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33748343/

相关文章:

javascript - 等待在 AngularJS/通用 javascript 中应用更改?

javascript - firebase 直接运行时 Redux saga 调用错误

javascript - 无法使用 Chrome 扩展程序单击按钮,但可以在开发人员工具中单击

c# - 使用 Moq 模拟单元测试的异步方法

java - Java 类的 Groovy Spock 测试 - 如何模拟 Clob

javascript - 从多级 JSON 递归创建目录(使用 async.js)

asynchronous - 预期为 `async` block ,发现了不同的 `async` block

JavaScript 函数不起作用

java - 使用仅适用于第一次测试的流进行单元测试日志

javascript - 使用 javascript/nodejs 分割 url 并存储在数组、对象或字符串中