Part 14 / Topic 4 of 7
Fake timers
A component on a real setTimeout either makes its own test wait out real seconds, or needs a fake clock. examples/04_fake_timers.jsx's AutoDismissBanner auto-dismisses after dismissAfterMs:
// examples/04_fake_timers.jsx
useEffect(() => {
const timer = setTimeout(() => setVisible(false), dismissAfterMs);
return () => clearTimeout(timer);
}, [dismissAfterMs]);
vi.useFakeTimers() (set up in beforeEach, torn back down with vi.useRealTimers() in afterEach - a leaked fake clock into the next test file is a confusing, unrelated-looking failure waiting to happen) replaces real time with a clock the test controls directly. vi.advanceTimersByTime(3999) really leaves the banner showing; one more millisecond really removes it (examples/04_fake_timers.test.jsx). The one detail that is easy to miss: advancing the fake clock runs the timer's callback, which calls setState - and that has to happen inside act() (imported from @testing-library/react, not from vitest) so React finishes the resulting re-render before the next assertion reads the DOM. This course's own stage-2-intermediate/part-07-custom-hooks/examples/06_use_debounce.test.jsx and stage-2-intermediate/part-06-useeffect-and-side-effects/examples/02_live_clock_cleanup.test.jsx have used this exact beforeEach/afterEach/act shape since Stage 2 - this section just names what it is doing.
Done here? The practice set for Part 14 — including the solutions — is on the part page.