JavaScript Answers

How to set a mock date in Jest?

Spread the love

To set a mock date in Jest, we can use the useFakeTimers and setSysttemTime methods.

For instance, we write:

  .setSystemTime(new Date('2022-01-01').getTime());

to call useFakeTimers to let us mock timers.

Then we call setSystemTime to set the time of the mock timer by calling it with a timestamp in milliseconds.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.