Fake-timer leakage in Jest: the flake nobody sees coming
Blog post from Mergify
Fake-timer leakage in Jest is a subtle issue where a call to `jest.useFakeTimers()` in one test can inadvertently affect unrelated tests, leading to confusing and flaky test failures. This problem occurs because fake timers, once activated, remain active across tests in the same Jest worker process unless explicitly reset, causing scheduled callbacks to persist and potentially interfere with subsequent tests. The naive approach of switching back to real timers using `jest.useRealTimers()` is insufficient, as it does not clear the queued fake callbacks, which can still execute unexpectedly. The effective solution involves using an `afterEach` block to clear all timers and restore real timers and mocks, ensuring a clean state for each test. While configuring fake timers globally in Jest's setup can provide consistency, it may slow down integration tests, leading many teams to prefer per-file activation. Platforms like Mergify help identify such issues by rerunning tests in isolation to detect ordering-sensitive failures, highlighting the true source of the problem.