Jest provides multiple methods for handling timers, used to test code involving setTimeout, setInterval, and other timers:
1. Using Fake Timers:
javascriptjest.useFakeTimers(); test('timer callback', () => { const callback = jest.fn(); setTimeout(callback, 1000); jest.runAllTimers(); expect(callback).toHaveBeenCalledTimes(1); });
2. Run All Timers:
javascriptjest.runAllTimers(); // Run all pending timers
3. Advance to Specific Time:
javascriptjest.advanceTimersByTime(1000); // Advance 1000ms jest.runOnlyPendingTimers(); // Run only currently pending timers
4. Testing setInterval:
javascripttest('interval timer', () => { const callback = jest.fn(); setInterval(callback, 1000); jest.advanceTimersByTime(3000); expect(callback).toHaveBeenCalledTimes(3); });
5. Cleanup Timers:
javascriptafterEach(() => { jest.useRealTimers(); // Restore real timers jest.clearAllTimers(); // Clear all timers });
6. Testing Timer Clearing:
javascripttest('clear timeout', () => { const callback = jest.fn(); const timeoutId = setTimeout(callback, 1000); clearTimeout(timeoutId); jest.runAllTimers(); expect(callback).not.toHaveBeenCalled(); });
Best Practices:
- Use
jest.useFakeTimers()at the start of test suites - Restore real timers after testing
- Use
advanceTimersByTimeto test time-dependent logic - Ensure cleanup of all timers to avoid memory leaks