Explain Codes LogoExplain Codes Logo

How do I set a mock date in Jest?

javascript
date-manipulation
jest-mocking
test-environment
Alex KataevbyAlex Kataev·Nov 29, 2024
TLDR

To ensure all new Date() calls return a fixed date, use jest.spyOn to mock the global Date object.

jest.spyOn(global, 'Date').mockImplementation(() => new Date('2021-01-01T00:00:00Z'));

With this snippet, all new Date() calls return January 1, 2021. Post-test, use jest.restoreAllMocks() to do the clean-up.

When and why to mock dates

Testing codes that rely on current dates can be quite challenging without proper management of date and time. To get consistent test results, unaffected by real-world changes, mocking the Date object in Jest is the way to go.

Universal Time Coordinated for the win!

To handle tests across different time zones, use UTC dates:

jest.spyOn(global, 'Date').mockImplementation(() => new Date(Date.UTC(2021, 0, 1)));

Just a friendly reminder, time zones don't change the universal laws of time travel! 😉

Interoperability with other date libraries

With moment.js and similar date libraries, this mocking idea ensures consistent date references:

const moment = require('moment'); jest.spyOn(global, 'Date').mockImplementation(() => new Date('2021-01-01T00:00:00Z')); const fixedDate = moment(); // moment.js is also partying on January 1, 2021!

Clean-up post-test

Remember to reset the mocked Date with jest.restoreAllMocks() to keep other tests unperturbed. It's always good housekeeping! 🧹

For the lovers of precision

For tests with high granularity, setSystemTime can be manipulated down to the millisecond:

// Assuming direct control over time... June 15, 2022, at 10:15:30.500 AM jest.setSystemTime(new Date(Date.UTC(2022, 5, 15, 10, 15, 30, 500)));

Time manipulation is an exact science!⚗️

Control over timer functions

Manipulate setTimeout or setInterval timer functions in collaboration with the mocked Date:

// Marty McFly style: Fast-forwarding time! jest.runAllTimers();

A more robust experience with MockDate library and Timekeeper

Want something more sturdy? The MockDate library or Timekeeper could be a great fit:

const MockDate = require('mockdate'); MockDate.set('2022-06-15T10:15:30.500Z'); // Conduct your tests here... MockDate.reset(); // Safe landing back to reality.

What goes around, comes around!🔄

Pro tips and special cases

Mock specific dates and exact moments

For mocking specific date methods or Date.now(), use jest.spyOn():

jest.spyOn(Date, 'now').mockImplementation(() => 1609459200000); // Who needs real time anyway?

We're all living in the past of our future self! 🛸

Clean-up: a must-do!

Post-tests, always remember to restore your mocks to maintain a neat testing environment. This keeps your future tests unsullied and sane!

Test fidelity across environments

Deploy these techniques to ensure your date-centric tests run harmoniously across various CI/CD pipelines and development environments.