To mock a constructor like new Date() with Jest and JavaScript, we can use the setSystemTime
method.
For instance, we write
beforeAll(() => {
jest.useFakeTimers("modern");
jest.setSystemTime(new Date(2022, 3, 1));
});
afterAll(() => {
jest.useRealTimers();
});
to call useFakeTimers
to use a mock timer.
Then we call setSystemTime
to set the date and time in the test environment.
We make the calls in the beforeAll
callback to run the code before any tests are run.
Then in the afterAll
callback, we call useRealTimers
to clear the mocked timers and use the real ones.
Conclusion
To mock a constructor like new Date() with Jest and JavaScript, we can use the setSystemTime
method.