乐闻世界logo
搜索文章和话题

How to test timers (setTimeout, setInterval) in Jest? How to use fake timers?

2月21日 15:57

Jest provides multiple methods for handling timers, used to test code involving setTimeout, setInterval, and other timers:

1. Using Fake Timers:

javascript
jest.useFakeTimers(); test('timer callback', () => { const callback = jest.fn(); setTimeout(callback, 1000); jest.runAllTimers(); expect(callback).toHaveBeenCalledTimes(1); });

2. Run All Timers:

javascript
jest.runAllTimers(); // Run all pending timers

3. Advance to Specific Time:

javascript
jest.advanceTimersByTime(1000); // Advance 1000ms jest.runOnlyPendingTimers(); // Run only currently pending timers

4. Testing setInterval:

javascript
test('interval timer', () => { const callback = jest.fn(); setInterval(callback, 1000); jest.advanceTimersByTime(3000); expect(callback).toHaveBeenCalledTimes(3); });

5. Cleanup Timers:

javascript
afterEach(() => { jest.useRealTimers(); // Restore real timers jest.clearAllTimers(); // Clear all timers });

6. Testing Timer Clearing:

javascript
test('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 advanceTimersByTime to test time-dependent logic
  • Ensure cleanup of all timers to avoid memory leaks
标签:Jest