These tests will only pass during the third phase of a new moon. Photo by Ramazan Tokay on Unsplash

Mocking the time: Using Timers in Jest

A great Unit Test covers the 3 R’s; Repeatable, Reliable, Resilient. One thing that does not help with achieving the 3 R’s are test cases that only work at a certain time. Jest has a way to mock timers in tests. In this article we’re going to look at how 3 of these methods work.

Kris Raven
Published in
3 min readFeb 3, 2023

--

The Code

Below is the code that we’re going to write tests for. This function takes in a “days” parameter and calculates the Unix Epoch time (the milliseconds that have elapsed since 00:00:00 UTC on 1 January 1970).

Line 1: sets a parameter to a default value of 0.

Line 4: Date.parse() will always return Unix Epoch time. In this case we are passing a human-readable date and adding a certain amount of time to it (daysToAdd).

Below is the code for the Unit Test. We’ll walk through it line by line, and discuss some interesting points.

--

--

Kris Raven
Geek Culture

Quality Engineering Manager | A wholesome mix of QA, Automated Testing, music and philosophy | Enjoys unit tests | Favours integration tests