Use jest.fakeTimers correctly

rbeier

Robin

Posted on December 4, 2023

Use jest.fakeTimers correctly

If you are wondering why useFakeTimers() in jest does not seem to work every time, wonder no more! Here is your solution :)

Setup

I needed to write a unit test that checks if a form reset action is executed correctly:

it('should reset form state', () => {
  store.dispatch(new ResetForm());
  expect(store.state.form).toStrictEqual(testData.formDefaults());
});
Enter fullscreen mode Exit fullscreen mode

Problem

The problem were the new Date() calls in the default form state and in the formDefaults() method. Both created a new date object at runtime that was different in milliseconds.

-  "date": 2023-12-04T08:55:27.697Z,
+  "date": 2023-12-04T08:55:27.501Z,
Enter fullscreen mode Exit fullscreen mode

I remembered there were fakeTimers in Jest that I wanted to use. As the docs say, you can call jest.useFakeTimers() anywhere in your test file. So I called it in beforeAll() and got another error.

-  "date": 2023-01-01T00:00:00.000Z,
+  "date": 2023-12-04T09:23:24.315Z,
Enter fullscreen mode Exit fullscreen mode

As you can see, the expected date is now correct (2023-01-01), but the received date is still the current date, which means that the fakeTimers from jest were not executed in the ResetForm action.

Solution

Without going into the details of the NGXS state library that was used, the problem is that the fake timers mock are not present when the state is set up with some default values.

The solution is very simple, just call jest.useFakeTimers(); before importing any modules (very top of file) into your test and you're good to go. 馃コ

Of course, you can use your test-setup.ts to set this globally.

馃挅 馃挭 馃檯 馃毄
rbeier
Robin

Posted on December 4, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related