Stable Playwright tests begin with two deliberate choices: locating elements through the same signals users rely on, and asserting the outcome the user should observe. This guide explains which locator and assertion to use for common UI patterns, how to replace brittle selectors, and how to investigate flaky failures without adding arbitrary delays.
Overview
Playwright locators are more than CSS shortcuts. A locator describes how a test finds an element, while an assertion describes the condition that must eventually become true. Keeping those responsibilities separate makes browser tests easier to read and more resistant to ordinary UI changes.
As a default, prefer locators that reflect the accessible interface: getByRole, getByLabel, getByPlaceholder, and getByText. Use a dedicated getByTestId when the element has no useful user-facing identity or when a stable testing contract is appropriate. Treat CSS selectors and XPath as implementation-level fallbacks rather than the first choice.
Playwright locators are designed to retry while an element becomes actionable, and web-first assertions retry while the expected state is reached. That means a good test usually waits by expressing an observable condition, not by pausing for a guessed amount of time.
Locator decision table
| UI situation | Preferred locator | Why |
|---|---|---|
| Button, link, heading, checkbox, or navigation item | getByRole | Matches the element’s semantic role and accessible name. |
| Form control with a visible label | getByLabel | Connects the test to the label a user sees. |
| Distinct visible copy | getByText | Useful when text is the meaningful identity of the element. |
| Element with no stable user-facing identity | getByTestId | Creates an intentional, low-coupling testing hook. |
| Unique structural relationship | CSS locator | Useful for a constrained component boundary or state attribute. |
| Legacy markup with no practical alternative | XPath | Use sparingly and document why it is necessary. |
What to track
Choose locators by user meaning
For a sign-in form, use the accessible labels and submit button rather than class names:
const page = await browser.newPage();
await page.getByLabel('Email').fill('[email protected]');
await page.getByLabel('Password').fill('correct-horse-battery-staple');
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
If several elements share a role, narrow the locator with an accessible name, a filter, or a component boundary. Avoid relying on an element’s position, such as “the second button,” unless order itself is the behavior being tested.
Match assertions to the user-visible result
Use the narrowest assertion that explains the requirement:
toBeVisible()for content the user should see.toBeHidden()when a loading indicator or dialog should disappear.toHaveText()ortoContainText()for rendered copy.toHaveValue()for an input’s current value.toBeChecked()for checkbox or radio state.toHaveAttribute()for a meaningful state or link target.toHaveURL()andtoHaveTitle()for page-level navigation outcomes.
await expect(page.getByLabel('Remember me')).toBeChecked();
await expect(page).toHaveURL(//dashboard/);
await expect(page.getByRole('status')).toHaveText('Saved');
Use component-specific patterns
For a table, locate the row by meaningful content before addressing a cell or action:
const row = page.getByRole('row').filter({ hasText: 'Quarterly report' });
await expect(row).toBeVisible();
await row.getByRole('button', { name: 'Download' }).click();
For a dialog, assert its heading and scope the controls to the dialog:
const dialog = page.getByRole('dialog', { name: 'Delete project' });
await expect(dialog).toBeVisible();
await dialog.getByRole('button', { name: 'Cancel' }).click();
await expect(dialog).toBeHidden();
For menus, use the menu’s role and item names. If opening the menu changes the DOM asynchronously, the click followed by an assertion on the menu state is usually preferable to a fixed timeout.
Wait for causes and outcomes, not time
A Playwright wait should describe a real synchronization point. For a request triggered by a user action, coordinate the action and response:
const responsePromise = page.waitForResponse(response =>
response.url().includes('/api/projects') && response.request().method() === 'POST'
);
await page.getByRole('button', { name: 'Create project' }).click();
const response = await responsePromise;
expect(response.ok()).toBeTruthy();
await expect(page.getByRole('status')).toHaveText('Project created');
Use response waits when the network result is part of the behavior under test. Still assert the UI outcome when the user’s success condition is visual. Avoid testing private implementation details when a visible result is sufficient.
Cadence and checkpoints
Review locator health as part of the normal developer workflow rather than waiting for a large end-to-end failure. A practical cadence is:
- During component work: add or revise locators alongside the UI change. If a button’s accessible name changes intentionally, update the test and treat that review as part of the same change.
- After a flaky failure: inspect the trace, locator resolution, actionability checks, and relevant network activity before changing the test.
- Monthly or quarterly: review repeated selectors, skipped tests, long-running suites, and failures that require retries. These are signals that the test contract may be unclear.
- After browser or Playwright upgrades: run the suite across the project’s supported configuration and check failures for genuine behavior changes versus outdated assumptions.
Keep a small locator inventory for important flows: login, checkout, permissions, data creation, and destructive actions. Record the preferred locator, the asserted outcome, and any deliberate test ID. This makes selector decisions visible during code review and helps prevent a return to brittle patterns.
For project configuration, keep the test command, base URL, browser projects, retries, and trace policy in version control. A representative configuration might enable traces only when a test retries or fails, so diagnostic output is available without making every run unnecessarily heavy:
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
baseURL: 'http://127.0.0.1:3000',
trace: 'on-first-retry'
}
});
How to interpret changes
When a test fails, first classify the change. A locator failure can mean the element was renamed, the page is in a different state, the element is not accessible as expected, or the test is racing a real asynchronous operation. These causes require different fixes.
- Check the trace and screenshot. Confirm what the page actually rendered at the failure point.
- Inspect the locator. Ask whether it resolves to zero elements, multiple elements, or the wrong element. A strictness failure often indicates that the locator needs a meaningful name or filter.
- Review the assertion. Replace a broad assertion with one that captures the requirement. For example, assert the dialog’s heading and the saved status instead of waiting for a generic container.
- Check synchronization. If the UI depends on a request, route transition, animation, or background update, wait for an observable condition related to that operation.
- Only then change the selector. Do not hide a product regression by switching immediately to a less meaningful CSS or XPath expression.
For screenshots, compare stable states rather than capturing immediately after a click. Wait for the page’s meaningful heading, status, or loading state to settle first. Visual comparisons can complement functional assertions, but they should not replace checks for the behavior that matters.
If a test is still unstable, reproduce it repeatedly with the same data and inspect whether the failure follows a particular browser project, viewport, response, or test order. Remove shared state between tests where possible. Retries can provide diagnostic evidence, but they are not a substitute for fixing an unclear synchronization point.
When to revisit
Revisit this Playwright locator and assertion strategy whenever a component’s accessible name, form labels, navigation model, or asynchronous behavior changes. Also review it on a monthly or quarterly maintenance cycle, after a Playwright or browser upgrade, and whenever a new flaky pattern appears in CI.
Use this migration checklist to turn a brittle test into a stable one:
- Find selectors based on generated classes, deep CSS chains, numeric indexes, or absolute XPath.
- Replace each selector with a role-and-name, label, text, or intentional test ID where appropriate.
- Scope repeated elements with
filter({ hasText }), a component locator, or a unique accessible name. - Replace fixed delays with web-first assertions, navigation assertions, or request coordination.
- Assert the user-visible outcome after every important action.
- Run the changed flow repeatedly, inspect traces for failures, and document any remaining implementation-level selector.
As a next step, choose one high-value flow and audit five selectors today. For each one, write down the user signal it represents, the assertion that proves success, and the event that should synchronize the test. This small, recurring review keeps browser tests aligned with the interface instead of allowing temporary markup details to become permanent dependencies.