简体   繁体   中英

How to do unit test for settimeout in reactJs

How to test a setTimeout function in react using jest/enzyme

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

I tried with this :

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

but the test is failing with

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

Can anyone please help me with this??

你可以使用这个:

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

You can use jest.useFakeTimers() to enable fake timers to test setTimeout to implement the test cases you want.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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