Back to Automation BlogPlaywright

Playwright locators that do not flake

Why role and label based locators beat CSS chains, and how auto-waiting removes most sleep statements from a suite.

6 min read14 July 2026Tech Vista Global

Flakiness is usually a locator problem

Most intermittent failures are not timing bugs, they are identity bugs: the locator matched a different element, or matched nothing while the DOM was still settling. Playwright locators are lazy — they resolve at the moment of the action and retry until the element is actionable — so a well written locator removes the majority of waits from a suite.

Prefer user-facing locators

Query the page the way a user perceives it. Role, label, placeholder and text locators survive refactors of class names and DOM structure, and they double as accessibility checks: if getByRole cannot find your button, a screen reader cannot either.

await page.getByRole('button', { name: 'Book a demo' }).click();
await page.getByLabel('Email address').fill('qa@example.com');
await page.getByTestId('cart-total').toBeVisible;

Use test ids for the genuinely ambiguous

When a widget has no accessible name and no stable text — charts, canvases, virtualised rows — add a data-testid with the development team. A test id is a contract, not a shortcut: agree on it, document it, and keep it out of styling.

Never chain waitForTimeout

Replace fixed sleeps with web-first assertions. expect(locator).toHaveText() polls until the timeout, so the test is fast when the app is fast and patient when it is slow.

await expect(page.getByRole('status')).toHaveText('Payment confirmed');
await expect(page.getByRole('row')).toHaveCount(12);

Checklist before you commit

Run the spec with --repeat-each=5 locally. Any test that fails once in five runs will fail every day in CI.

  • No waitForTimeout in the diff
  • Every locator resolves to exactly one element
  • Assertions are web-first (expect(locator)), not on raw strings
  • Test data is created by the test, not assumed to exist

Turn this into hands-on practice

Book a free demo class and work through these patterns with a mentor.