Using Jest and Enzyme for testing in React. For one function inside a react component I am using setTimeOut to change a status.
Now to test that function in jest I am using jest.useFakeTimer. Using it for only one it() like below -
it('resets text after 2 seconds', async () => {
jest.useFakeTimers();
......
.....
jest.advanceTimersByTime(2000);
wrapped.update();
expect(....).toBe('Data');
});
Now do I need to use jest.useRealTimers() for this test case. As Jest automatically restores the real timers after each test case, so generally we don't need to manually call jest.useRealTimers() to restore the original timer functions.
Is it correct?
if I add one more test after this like -
it('test time out', () => {
console.log(setTimeout);
});
It doesn't print the mocked version.
So do I need to use jest.useRealTimers() here ? I am confused.
The Fake Timers API documentation explain clearly:
Yes, you need to call
jest.useRealTimers().You can also take a look at the source code of useFakeTimers() and useRealTimers()
They set the real timers and fake timers on the
globalobject.The fake
setTimeoutis not a mock function(can be checked byjest.isMockFunction()), it's a general function, that is not created byjest.fn(), see source code of_fakeSetTimeout()that's why
console.log(setTimeout)gives youRather than