πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Questions
Question 64 of 100
Mechanics
Intermediate

What are common synchronization pitfalls in Playwright?

The Answer

The most common pitfalls are: using `waitForTimeout` (sleep), asserting with `isVisible()` instead of `toBeVisible()`, not awaiting async calls, and checking state before navigation completes.

Deep Dive Explanation

The most impactful change you can make to a flaky test suite is removing all `waitForTimeout` calls and replacing them with proper Web-First assertions. Each hard sleep is a bet on timing that will eventually lose.

example.spec.ts
// ❌ PITFALL 1: Hard sleep
await page.waitForTimeout(3000); // Slow AND unreliable

// βœ… FIX: Wait for specific condition
await expect(page.locator('.data-loaded')).toBeVisible();

// ❌ PITFALL 2: Non-retrying check as assertion
const visible = await page.locator('#result').isVisible();
expect(visible).toBe(true); // Fails if element not yet rendered

// βœ… FIX: Web-First assertion
await expect(page.locator('#result')).toBeVisible();

// ❌ PITFALL 3: Missing await on navigation
page.goto('/dashboard'); // NOT awaited - race condition!

// βœ… FIX: Always await
await page.goto('/dashboard');

// ❌ PITFALL 4: Acting before load
await page.goto('/app');
await page.click('#btn'); // Page may not be fully interactive

// βœ… FIX: Wait for network
await page.goto('/app', { waitUntil: 'networkidle' });