Test runners, assertions and mocks · mid
Fake timers: testing debounce, throttle, polling and dates
Fake timers replace setTimeout, setInterval and Date with a clock you move by hand, so you can test debounce, retries, polling and countdowns instantly and deterministically instead of sleeping in tests.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- jest.useFakeTimers() / vi.useFakeTimers(), then advanceTimersByTime(ms), runOnlyPendingTimers(), or runAllTimers(). Restore with useRealTimers() after each test.
- With promises inside timers, use the async versions (advanceTimersByTimeAsync) so awaited code between timers can run.
- Mock the date with setSystemTime(new Date('2026-11-13')) for 'today', expiry and countdown logic. Vitest 5 also fakes Temporal.
- user-event and fake timers: userEvent.setup({ advanceTimers: jest.advanceTimersByTime }) (or vi.advanceTimersByTime), otherwise typing waits on real timers and the test hangs.
- Test both sides of the boundary: nothing happens at 299 ms, the call happens at 300 ms.
- Node's own runner has mock.timers (setTimeout, setInterval, Date) with tick(ms).
The red pen
Common traps: mistake → fix
Mistake: "Use await new Promise(r => setTimeout(r, 500)) in tests"
Fix: slow and flaky; use fake timers.
Mistake: "runAllTimers is always fine"
Fix: with setInterval or timers that schedule timers it can loop forever; use advanceTimersByTime or runOnlyPendingTimers.
Mistake: "Fake timers also flush promises"
Fix: sync advance functions don't run awaited code between timers; use the async variants.
Easy to hard
Questions interviewers ask, easy to hard
- How do you test a debounced search input?
- What are fake timers and what do they replace?
- Why does my test hang when I use user-event with fake timers?
- How would you test a retry with exponential backoff without waiting 7 seconds?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.