Course contentsShow
← React
Lesson 2167 of 2,39648. End-to-End TestingFree lesson

Assertions with expect()

Use Playwright's expect() assertions for visibility, text content, attributes, and custom conditions with auto-retry.

Assertions with expect()

You'll learn how Playwright's expect() gives you powerful, auto-retrying assertions that wait for conditions to be true.

The Core Idea

After interacting with elements (clicking, typing, etc.), you need to verify your app behaved correctly. Playwright's expect() function automatically retries assertions for a few seconds, waiting for your condition to become true. This is crucial for testing dynamic React apps where state updates happen asynchronously.

Think of it like checking your oven temperature: instead of looking once and declaring "it's not hot yet!" (failing immediately), you keep checking every second until it reaches the target temperature or times out.

Common Assertions

Visibility checks:

await expect(page.getByRole('button', { name: 'Submit' })).toBeVisible();
await expect(page.getByText('Loading...')).toBeHidden();

Text content:

await expect(page.getByRole('heading')).toHaveText('Welcome Back');
await expect(page.getByTestId('counter')).toContainText('5');

Attributes:

await expect(page.getByRole('link')).toHaveAttribute('href', '/dashboard');
await expect(page.getByRole('button')).toBeDisabled();

Custom conditions:

await expect(page.locator('.items')).toHaveCount(3);
await expect(page).toHaveURL(/.*checkout/);

Each assertion waits up to 5 seconds by default, constantly rechecking until the condition passes or timeout occurs. This handles React's rendering delays, animations, and state updates without manual waitFor calls.

Why Auto-Retry Matters

Your React component might update after an API call or state change. Instead of asserting immediately (and failing because React hasn't re-rendered yet), expect() keeps trying, making your tests resilient to timing issues.

Key Takeaway: Playwright's expect() assertions automatically retry until conditions are met, eliminating flaky tests caused by React's asynchronous rendering and making your E2E tests reliable without manual waiting logic.