繁体   English   中英

如何在reactJs中对settimeout进行单元测试

[英]How to do unit test for settimeout in reactJs

如何使用玩笑/酶在反应中测试 setTimeout 函数

setTimeout(() => {
        
}, 500);

我试过这个:

  expect(setTimeout).toHaveBeenCalledTimes(1);
  expect(setTimeout).toHaveBeenLastCalledWith(() => { }, 500);

但测试失败了

Expected: [Function anonymous], 500
Received: [Function anonymous], 500

任何人都可以帮我解决这个问题吗??

你可以使用这个:

  expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 500);

您可以使用jest.useFakeTimers()启用假计时器来测试setTimeout以实现您想要的测试用例。

jest.useFakeTimers();

test('test setTimeout', () => {
  const fn = jest.fn();
  setTimeout(fn, 500);

  expect(setTimeout).toHaveBeenCalledTimes(1);
  expect(setTimeout).toHaveBeenLastCalledWith(fn, 500);
});

https://jestjs.io/docs/en/timer-mocks

暂无
暂无

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

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