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.
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:
Now to mock the
Date in the tests I used the
Any call to
new Date() or
Date.now() will now return the hardcoded time we set above.
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.
You can also remove the mocking entirely by calling
jest.useRealTimers(). This is something you might like to do in a
afterEach() function perhaps.