Timer Mocks

Learn how to effectively mock and leverage timers in Jest.

Why do we mock timers?

Our discussion on mocking timers largely covers two use cases. The first is mocking timers in our code for efficiency reasons. The second is mocking for the same reasons that we often mock functions: we want to be able to watch them and assert on how timers were called and run.

Mocking for efficiency

Timers, by nature, take time—a resource that we are constantly looking to optimize and reduce in our test runs. We don’t necessarily need our timers to run through their entirety in our test runs. At times we may want to, but we often want to hit the timer and keep running. Mocking the timer at hand allows us to do this.

Mocking for deeper insights

At other times, we don’t need to speed up the execution. Instead, we want to gain the same insights we do by mocking other functions. We might want to see if a timer was called, how many times it was called, with what argument, and so on.

How to mock a timer

The good news is we can use the same strategy for mocking in both scenarios. The core of timer mocking comes down to two Jest functions, jest.useFakeTimers() and jest.useRealTimers(). The first tells Jest to replace all implementations of setTimeout() and setInterval() with mocked versions of them. This implementation looks something like the example below.

In this example, we see a newYearsEveCountdown function that counts down from the number of seconds passed to it, defaulting to 10 if nothing is passed. The function logs the count at each second. Notice how the test that uses fake timers logs all seconds rapidly, while the test that uses real timers actually performs the timed countdown:

Get hands-on with 1200+ tech skills courses.