How do I set a mock date in Jest?
To ensure all new Date() calls return a fixed date, use jest.spyOn to mock the global Date object.
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:
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:
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:
Time manipulation is an exact science!⚗️
Control over timer functions
Manipulate setTimeout or setInterval timer functions in collaboration with the mocked Date:
A more robust experience with MockDate library and Timekeeper
Want something more sturdy? The MockDate library or Timekeeper could be a great fit:
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():
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.
Was this article helpful?
