To mock a date in Jest, we can use the useFakeTimers
and setSysttemTime
methods.
jest
.useFakeTimers('modern')
.setSystemTime(new Date('2020-08-09'));
For clean up, you can reset it with
jest.useRealTimers()
One of the places you can cleanup is in afterEach()
, likewise you can apply the mock dates for all tests in beforeEach()
.
e.g.
beforeEach(() => {
jest.useFakeTimers('modern')
.setSystemTime(new Date('2020-08-09'))
})
afterEach(() => {
jest.runOnlyPendingTimers()
jest.useRealTimers()
})