Stubbing/mocking Timers In Jest Unit Tests

February 1, 2024

Black and Gray Video Camera on White Table
Photo by Pavel Danilyuk on Pexels.

Introduction

When writing unit tests for JavaScript applications, it's often necessary to test code that involves timers or asynchronous operations. One common task is to stub or mock timers to ensure predictable behavior and avoid long wait times during test execution. In this article, we will explore how to stub and mock timers in Jest unit tests.

Stubbing Timers

Stubbing timers involves replacing the default implementation of timers with custom implementations. This allows us to control the flow of time during test execution and eliminate the need to wait for actual timers to elapse.

To stub timers in Jest, we can use the jest.useFakeTimers() function. This function sets up a fake timer implementation that allows us to manually advance time in our tests. Let's take a look at an example:

jest.useFakeTimers();

// Some code involving timers

jest.advanceTimersByTime(1000); // Advance time by 1 second

expect(someFunction).toBeCalledTimes(1); // Expect some function to be called