Search⌘ K

Dates

Understand why and how to mock JavaScript dates using Jest's spyOn function. Learn techniques to control the current date in tests, avoiding flaky results from real-time dependencies.

Why do we mock dates?

The dates in JavaScript's native global are notoriously difficult to work with. Testing them can be equally frustrating. If we are testing a function that we pass a date into, that can be fairly straightforward since we have control over what we are passing in and therefore can make assertions on what we get back.

What about those times that we are not passing in a date, though? What about dates that are derived or are simply based on today's date? That's not quite as simple because an expectation written today that passes will fail tomorrow. For this very reason, we often ...