How do I set a mock date in Jest?

As of Jest 26 this can be achieved using “modern” fake timers without needing to install any 3rd party modules: https://jestjs.io/blog/2020/05/05/jest-26#new-fake-timers

jest
  .useFakeTimers()
  .setSystemTime(new Date('2020-01-01'));

If you want the fake timers to be active for all tests, you can set timers: 'modern' in your configuration: https://jestjs.io/docs/configuration#timers-string

EDIT: As of Jest 27 modern fake timers is the default, so you can drop the argument to useFakeTimers.

Leave a Comment

tech