Why Vitest Fake Timers Fail With Async Code and How to Fix It
When using fake timers in Vitest, calling the synchronous `advanceTimersByTime` does not allow promise continuations to run before assertions are evaluated, causing tests to silently fail or hang. This happens because synchronous timer advancement fires callbacks in the same tick, while microtasks queued by resolved promises only execute after the current synchronous block yields. The fix is to use the async counterparts — such as `advanceTimersByTimeAsync` — which advance the clock and drain the microtask queue between timer callbacks. Sync timer methods remain appropriate only when the code under test is entirely callback-based with no promises involved. Developers are also advised to call `vi.useRealTimers()` in an `afterEach` hook to prevent fake timers from leaking across test files.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in