How to mock a constructor like new Date()

Since jest 26, you can use the ‘modern’ fakeTimers implementation (see article here) wich supports the method jest.setSystemTime.

beforeAll(() => {
    jest.useFakeTimers('modern');
    jest.setSystemTime(new Date(2020, 3, 1));
});

afterAll(() => {
    jest.useRealTimers();
});

Note that 'modern' will be the default implementation from jest version 27.

See documentation for setSystemTime here.

Leave a Comment