javascript - 在 Jest : done() not being called as expected 中测试异步代码

标签 javascript unit-testing jestjs

这是一个用 Jest (v20.0.4) 编写的测试套件。
前 3 个测试是预期行为,我的问题与 Test4 有关。

test('Test1: the list should contain 7', () => {
  const data = [1, 2, 7, 9];
  expect(data).toContain(7);
});
// > Passes as expected
test('Test2: the list should contain 7', () => {
  const data = [1, 2, 7, 9];
  expect(data).toContain(8);
});
// > Fails as expected; Expected array: [1, 2, 7, 9] To contain value: 8
test('Test3: the list should contain 7', (done) => {
  function callback(data) {
    expect(data).toContain(7);
    done();
  }
  setTimeout(() => {
    callback([1, 2, 7, 9]);
  }, 500);
});
// > Passes as expected
test('Test4: the list should contain 7', (done) => {
  function callback(data) {
    expect(data).toContain(8);
    done();
  }
  setTimeout(() => {
    callback([1, 2, 7, 9]);
  }, 500);
});
// > Fails with Error "Timeout - Async callback was not invoked within timeout specified"
这是我的问题:
在 Test4 中,done()expect 之后立即调用陈述。
所以,即使期望语句没有通过,我猜它应该会失败并出现类似于 Test2: (Expected array: [1, 2, 7, 9] To contain value: 8) 的错误。
但是,它失败并出现如上所示的超时错误,这表明 done()永远不会被调用。
为什么?我不明白!
有人可以指导我完成这种行为吗?
我扫描了docs但找不到与此相关的任何内容。

最佳答案

在您的代码中,expect调用 throws 和 done永远达不到。因此,Jest 会一直等到超时并发出您注意到的令人讨厌的、不清楚的错误。
解决方案是捕获抛出并调用 done(error)向 Jest 运行者表明测试失败。

test('Test4: the list should contain 7', done => {
  function callback(data) {
    try {
      expect(data).toContain(8);
      done();
    }
    catch (err) {
      done(err);
    }
  }
  setTimeout(() => {
    callback([1, 2, 7, 9]);
  }, 500);
});
运行此操作会产生所需的结果:
Error: expect(received).toContain(expected) // indexOf

Expected value: 8
Received array: [1, 2, 7, 9]
来自 docs :

If the expect statement fails, it throws an error and done() is not called. If we want to see in the test log why it failed, we have to wrap expect in a try block and pass the error in the catch block to done. Otherwise, we end up with an opaque timeout error that doesn't show what value was received by expect(data).

关于javascript - 在 Jest : done() not being called as expected 中测试异步代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52603954/

相关文章:

javascript - 无法填充数组并返回

javascript - 如何在Nodejs中模拟外部依赖方法回调参数?

forms - React-Bootstrap 无效表单反馈始终可见如何测试?

javascript - React-testing-library 渲染函数抛出语法错误

javascript - Angular 5 中的 RxJs Store - 保存应用程序参数/数据

javascript - Jquery Fullcalendar 在“今天” View 中隐藏一些小时

javascript - 如何使用 Jquery 的 AJAX 提交复杂的表单?

unit-testing - 如何覆盖 Quarkus 中一个 Unittest 的配置属性

c# - 在 C# 中引发事件的单元测试(按顺序)

javascript - 为什么更改 testMatch 正则表达式时 Jest 覆盖率报告会中断?