How do I set a mock date in Jest?
MockDate can be used in jest tests to change what new Date()
returns:
var MockDate = require('mockdate');
// I use a timestamp to make sure the date stays fixed to the ms
MockDate.set(1434319925275);
// test code here
// reset to native Date()
MockDate.reset();
For quick and dirty solution use jest.spyOn for locking time:
let dateNowSpy;
beforeAll(() => {
// Lock Time
dateNowSpy = jest.spyOn(Date, 'now').mockImplementation(() => 1487076708000);
});
afterAll(() => {
// Unlock Time
dateNowSpy.mockRestore();
});
UPDATE:
For a more robust solution look at timekeeper:
import timekeeper from 'timekeeper';
beforeAll(() => {
// Lock Time
timekeeper.freeze(new Date('2014-01-01'));
});
afterAll(() => {
// Unlock Time
timekeeper.reset();
});
Since momentjs uses Date
internally, you can just overwrite the Date.now
function to always return the same moment.
Date.now = jest.fn(() => 1487076708000) //14.02.2017
or
Date.now = jest.fn(() => new Date(Date.UTC(2017, 1, 14)).valueOf())
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
.