Categories
JavaScript Answers

How to mock a constructor like new Date() with Jest and JavaScript?

Spread the love

Sometimes, we want to mock a constructor like new Date() with Jest and JavaScript.

In this article, we’ll look at how to mock a constructor like new Date() with Jest and JavaScript.

How to mock a constructor like new Date() with Jest and JavaScript?

To mock a constructor like new Date() with Jest and JavaScript, we can use the setSystemTime method.

For instance, we write

beforeAll(() => {
  jest.useFakeTimers("modern");
  jest.setSystemTime(new Date(2022, 3, 1));
});

afterAll(() => {
  jest.useRealTimers();
});

to call useFakeTimers to use a mock timer.

Then we call setSystemTime to set the date and time in the test environment.

We make the calls in the beforeAll callback to run the code before any tests are run.

Then in the afterAll callback, we call useRealTimers to clear the mocked timers and use the real ones.

Conclusion

To mock a constructor like new Date() with Jest and JavaScript, we can use the setSystemTime method.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.