开玩笑的单元测试:setTimeout在异步测试中不触发 [英] Jest unit test: setTimeout not firing in async test

查看:108
本文介绍了开玩笑的单元测试:setTimeout在异步测试中不触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解Jest中异步测试的工作方式.

I'm trying to understand how asynchronous testing works in Jest.

我想要做的事情类似于Jest文档中的示例.效果很好..

What I'm trying to do is similar to an example from the Jest documentation. This works fine ..

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

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

But I want to delay the callback invocations so I tried this ....

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

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

but the test fails with the message Expected two assertions to be called but received zero assertion calls..

控制台中未显示日志消息超时已触发".

The log message 'timeout fired' doesn't appear in the console.

请有人能解释为什么会失败吗?

Please can someone explain why it fails?

推荐答案

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

You need to use jest's timer mocks https://jestjs.io/docs/en/timer-mocks

首先,您告诉玩笑者使用模拟计时器,然后在测试中运行计时器.

First you tell jest to use mock timers, then you run the timers within your test.

它看起来像:

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

这篇关于开玩笑的单元测试:setTimeout在异步测试中不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆