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