Learn how to properly mock JavaScript's Date global.

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 want to mock our dates. If our code requires today's date, a representation of last year, or the time 30 minutes from now, we need to be able to control what “now” is equal to, so that we can form an expectation of the result.

Get hands-on with 1200+ tech skills courses.