Timer Mocks
Explore how to mock timers using Jest's useFakeTimers and useRealTimers functions. Understand how mocking timers can optimize test efficiency and provide insights by spying on timer calls. Learn best practices for integrating timer mocks into your testing environment to write reliable and fast JavaScript tests.
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 ...