繁体   English   中英

笑话单元测试:setTimeout 未在异步测试中触发

[英]Jest unit test: setTimeout not firing in async test

我试图了解异步测试在 Jest 中是如何工作的。

我正在尝试做的类似于 Jest 文档中的示例。 这工作正常..

function doAsync(c) {
  c(true)
}

test('doAsync calls both callbacks', () => {

  expect.assertions(2);

  function callback1(data) {
    expect(data).toBeTruthy();
  }

  function callback2(data) {
    expect(data).toBeTruthy();
  }

  doAsync(callback1);
  doAsync(callback2);
});

但是我想延迟回调调用,所以我尝试了这个....

 function doAsync(c) {
    setTimeout(() => {
      console.log('timeout fired')
      c(true)
    }, 1000)
  }

但测试失败并显示消息Expected two assertions to be called but received zero assertion calls. .

日志消息“超时触发”未出现在控制台中。

请有人解释为什么它失败了?

您需要使用 jest 的计时器模拟https://jestjs.io/docs/en/timer-mocks

首先,您告诉 jest 使用模拟计时器,然后在测试中运行计时器。

它看起来像:

function doAsync(c) {
  setTimeout(() => {
      c(true)
    }, 1000)
}

jest.useFakeTimers()

test('doAsync calls both callbacks', () => {

  expect.assertions(2);

  function callback1(data) {
    expect(data).toBeTruthy();
  }

  function callback2(data) {
    expect(data).toBeTruthy();
  }

  doAsync(callback1);
  doAsync(callback2);

  jest.runAllTimers(); // or jest.advanceTimersByTime(1000)
});

使用jest.runAllTimers(); 可能导致以下错误:

跑了 100000 个计时器,还有更多! 假设我们遇到了无限递归并退出...

在浏览了JEST 计时器模拟文档之后,我突然想到setTimeout进入了无限递归,如文档中所述。 建议使用jest.runOnlyPendingTimers() ,这样可以解决无限递归错误。

快进并仅耗尽当前挂起的计时器(但不是在该过程中创建的任何新计时器)

jest.runOnlyPendingTimers();

在您的测试用例中使用以下代码设置 setTime out。

it('saveSubscription', () => {
  function doAsync(c) {
    setTimeout(() => {
      component.addSubscription();
      expect(component.subscription.freq).toEqual('immediate');
      component.saveSubscription();
      expect(component.subscription.name).toBe('Untitled 1');
    }, 30000);
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM