Does Jest automatically restores the real timers after each test case?

126 Views Asked by At

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.

1

There are 1 best solutions below

0
Lin Du On

The Fake Timers API documentation explain clearly:

Calling jest.useFakeTimers() will use fake timers for all tests within the file, until original timers are restored with jest.useRealTimers()

Yes, you need to call jest.useRealTimers().

You can call jest.useFakeTimers() or jest.useRealTimers() from anywhere: top level, inside an test block, etc. Keep in mind that this is a global operation and will affect other tests within the same file.

You can also take a look at the source code of useFakeTimers() and useRealTimers()

They set the real timers and fake timers on the global object.

The fake setTimeout is not a mock function(can be checked by jest.isMockFunction()), it's a general function, that is not created by jest.fn(), see source code of _fakeSetTimeout()

describe('78076173', () => {
  test('should pass', () => {
    jest.useFakeTimers();

    expect(jest.isMockFunction(setTimeout)).toBeFalsy(); // pass
  });
});

that's why console.log(setTimeout) gives you

[Function: setTimeout]

Rather than

[Function: mockConstructor]