DEV Community

Robin
Robin

Posted on β€’ Edited on

1 1

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.

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay