The release of Jest 26 brought a new timer faking interface, which now supports Date mocks. I couldn’t readily find any documentation for this feature so, here is how I used in a project recently.

If you are not already running Jest 26 then upgrade and if you’re using TypeScript don’t forget to update the @types package at the same time.

First, you need to enable the new timer handling in your test file as it is currently behind a feature flag.

jest.useFakeTimers("modern");

When Jest 27 is released then it should be the default - you’ll still need to enable fake timers of course! At that point you should be able to get away with the following:

jest.useFakeTimers();

Now to mock the Date in the tests I used the jest.setSystemTime() function.

jest.setSystemTime(new Date("2012-10-10")); // a Date object
jest.setSystemTime(1349852318000); // same date as a unix time in milliseconds

Any call to new Date() or Date.now() will now return the hardcoded time we set above.

it("should return the hardcoded date", () => {
  jest.setSystemTime(1349852318268);
  expect(new Date().valueOf()).toBe(1349852318268);
});

This will affect any code that uses Date that is called after you’ve set the time - either in the test file itself or in the subject code that is under test (your application code for example).

You can still get to the real time in the test if you need it with jest.getRealSystemTime(). Here is an example test that you can try out in Jest that shows this in action.

it("should return the hardcoded date", () => {
  jest.setSystemTime(1349852318268);
  expect(new Date().valueOf()).toBe(1349852318268);
  expect(jest.getRealSystemTime().valueOf()).not.toBe(1349852318268);
});

You can also remove the mocking entirely by calling jest.useRealTimers(). This is something you might like to do in a afterEach() function perhaps.