Lesson 3 of 9 · 26m
Deterministic Waiting, Timeouts, and Application Signals
Replace sleeps with explicit state transitions, bounded response waits, clock control, and assertions that retry for the right reason.
Every flaky suite has a graveyard of waitForTimeout calls. Somebody added 500 milliseconds here, then two seconds there, until the suite became slow and still unreliable. Time is not a synchronization primitive. State is. Your job is to identify which application signal proves the transition you need and wait on that signal with a bounded timeout.
Wait for the cause of readiness
If a button becomes enabled after validation, wait for enabled. If navigation happens after a save, wait for the URL or response. If content appears after a query, wait for the content.
waitForResponse has a race you must understand
Set up the wait before triggering the action. The response may complete before you begin listening if you click first. The correct pattern is:
const responsePromise = page.waitForResponse('**/api/save');
await page.getByRole('button', { name: 'Save' }).click();
const response = await responsePromise;That small ordering detail eliminates an entire class of intermittent failures.
Control time when time is the dependency
Retry windows, token expiry, cron labels, relative timestamps, and polling behavior are time-dependent. If the application uses Date.now() or browser timers, Playwright's clock API can freeze and advance time in supported versions:
await page.clock.install();
await page.clock.setFixedTime(new Date('2026-01-15T12:00:00Z'));
await page.goto('/billing/invoices');
await expect(page.getByText('Due in 7 days')).toBeVisible();
await page.clock.tick(24 * 60 * 60 * 1000);Use clock control surgically. Freezing all time before application boot can break libraries that expect monotonic progress if you do not understand their timer behavior.
Tune timeouts as budgets, not superstition
Playwright has action, assertion, navigation, and test-level timeouts. A five-minute global timeout hides product regressions and wastes CI. Set realistic defaults in config and explain exceptions:
export default defineConfig({
timeout: 30_000,
expect: { timeout: 5_000 },
use: {
actionTimeout: 10_000,
navigationTimeout: 15_000,
},
});A timeout should answer: how long would a real user reasonably wait before we call this broken?
Field notes
- A flaky test that passes after increasing timeout was not fixed; its probability distribution shifted.
networkidleis seductive but dangerous on apps with analytics, websockets, polling, or long-lived connections.- Polling applications need explicit synchronization because there may always be another request in flight.
- Animation waits belong in visual tests more often than functional tests; CSS transitions can still affect click stability.
- When a wait fails, capture whether the trigger happened. Half of debugging is discovering that the click never reached the application.
Was this lesson helpful?