Date and time
Loading "Intro to Date and Time"
Run locally for transcripts
If you've worked with date, time, or timezones in the past, you know how quickly it can become a complete pain. The time is constantly changing. Likely, a few seconds have already passed since you've started reading this sentence. If I had to write a test for how long it will take you to read this entire exercise, I'd have to resort to guessing. There's just so many things that affect that time!
Duration isn't the only variable here either. Date can also differ based on the timezone of the computer that creates it. In other words, you and your colleague might get different test results for the same test if they happened to live half a world away from you. Do you have to guess a better date for that test now...?
No. Guessing is not something you should do while testing. You need to find a way to achieve reliable test results, and when it comes to unpredictable things like date and time, your task is to make them predictable.
In other words, you need to eliminate date and time from tests completely by freezing them!
This is where mocking comes in handy. While you can, technically, replace the
Date
constructor and make it return a fixed date, there are far nicer APIs provided in Vitest to work with date and time.Besides, time manifests itself in more things than just date. There's also timers, like
setTimeout
and setInterval
, as well as event loop ticks for when you schedule operations to complete on the next loop cycle. Those are, too, dependent on time!In this exercise, you will learn how to mock date, timers, and event loop ticks in Vitest. Let's begin!