Timeout Configuration for Slow Operations
You'll learn how to adjust test timeout limits to accommodate network calls, database queries, and other slow asynchronous operations that exceed default test timeouts.
The Problem with Default Timeouts
Most test runners impose a default timeout (often 5 seconds in Jest, 2 seconds in Node's test runner) to prevent tests from hanging indefinitely. But real-world async operations—fetching from external APIs, connecting to databases, or processing large files—sometimes legitimately take longer than these defaults.
When your test times out before your slow operation completes, you get a false failure. The code works fine; it just needs more time.
Configuring Per-Test Timeouts
You can extend timeout limits on individual tests that need extra time:
// Jest/Vitest syntax
it('fetches user data from slow API', async () => {
const user = await fetchUserFromSlowAPI(123);
expect(user.name).toBe('Alice');
}, 10000); // 10 second timeout (third argument)
// Node test runner syntax
it('processes large file', { timeout: 15000 }, async () => {
const result = await processLargeFile('data.csv');
expect(result.rows).toBeGreaterThan(1000);
});
The timeout is specified in milliseconds. Only the specific test gets the extended limit—other tests still use defaults.
Think of It Like a Parking Meter
Default timeouts are like 15-minute parking spots—fine for quick errands. But if you're moving furniture, you need to pay for extended parking. Timeout configuration tells the test runner "this operation legitimately needs more time; don't fail it prematurely."
Key Takeaway: Configure custom timeouts for tests involving genuinely slow operations like network calls or file I/O—but keep the timeout reasonable to still catch actual hangs.