[英]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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.