Mastering Timers: Why `waitFor` and Local Fake Timers Are Your Testing MVPs
Ever found your unit tests inexplicably hanging, only to time out after a frustrating 5 seconds? If you're using Testing Library's waitFor alongside Vitest's global fake timers, you've likely stumbled upon a subtle but critical interaction that can bring your testing suite to a halt. The culprit isn't a bug, but a fundamental misunderstanding of how these powerful tools interact.
In the motos-max-cordialidad project, as we refined our reception order-form hooks, we recently expanded our test coverage. This involved adding 17 new unit tests across three new hooks, bringing our apps/web test suites from 5 to 8, now totaling 32 tests. During this expansion, we encountered precisely this timeout issue, necessitating a deeper dive into timer management in our tests.
The Problem: waitFor and Global Fake Timers
When Vitest's vi.useFakeTimers() is enabled globally (or even implicitly through a setup file), it replaces the real timer functions (setTimeout, setInterval, etc.) with mock versions. This is incredibly useful for speeding up tests that rely on time-based logic, as you can manually advance time rather than waiting for real-world delays.
However, Testing Library's waitFor utility, designed to poll for asynchronous changes in the UI or component state, uses real timers by default for its polling mechanism. The conflict arises because waitFor expects these real timers to advance naturally, but a globally faked timer environment means no real time passes unless explicitly advanced by Vitest's utilities. waitFor then polls endlessly against non-advancing fake timers, eventually hitting its default timeout (typically 5 seconds) and failing the test.
The Local Timers Solution
The key to resolving this is to manage fake timers locally within each test or test suite where they are needed, and crucially, to avoid waitFor in those specific scenarios. Instead of letting waitFor poll, we can explicitly advance our fake timers and then assert directly.
Here’s how we approached it in motos-max-cordialidad:
import { renderHook, act } from '@testing-library/react';
import { vi } from 'vitest';
import { useState, useEffect } from 'react';
function useTimerHook() {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setCount((prevCount) => prevCount + 1);
}, 1000);
return () => clearInterval(timer);
}, []);
return count;
}
describe('useTimerHook with local fake timers', () => {
// Activate fake timers only for this describe block
beforeAll(() => {
vi.useFakeTimers();
});
// Restore real timers after this describe block
afterAll(() => {
vi.useRealTimers();
});
it('should increment count after time passes', async () => {
const { result } = renderHook(() => useTimerHook());
expect(result.current).toBe(0);
// Advance timers by 1 second
await act(async () => {
await vi.advanceTimersByTimeAsync(1000);
});
expect(result.current).toBe(1);
// Advance timers by another 2 seconds
await act(async () => {
await vi.advanceTimersByTimeAsync(2000);
});
expect(result.current).toBe(3); // 1 (from previous) + 2 = 3
});
});
In this example, vi.useFakeTimers() is activated beforeAll within the specific describe block that needs it, and vi.useRealTimers() is called afterAll to clean up. Crucially, instead of waitFor to detect the count change, we use vi.advanceTimersByTimeAsync within an act block to simulate time passing. After advancing, we directly assert the state, knowing that our hook's setInterval has executed.
The Takeaway
When working with time-dependent logic in React hooks and unit tests:
- Prefer local fake timers: Activate
vi.useFakeTimers()only within the specificdescribeoritblocks that require them. This isolates your time-sensitive tests without affecting others. - Avoid
waitForwith local fake timers: When fake timers are active, do not rely onwaitFor's polling. Instead, usevi.advanceTimersByTimeAsync(orvi.runAllTimersAsyncfor immediate execution of all pending timers) to manually control time progression. - Assert directly: After explicitly advancing timers, assert the expected state changes directly without relying on
waitFor's polling mechanism. This makes your tests more explicit, faster, and less prone to unexpected timeouts.
This approach ensures your tests are fast, reliable, and predictable, preventing those frustrating timeouts and giving you precise control over time-sensitive logic in your component tests.
Generated with Gitvlg.com