October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Designing Reusable Locators for More Stable Playwright Tests

Design reusable Playwright locators around user-facing meaning, scope repeated controls to their components, and reserve custom selector engines for needs built-in APIs cannot express cleanly.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Build reusable Playwright locators from what a user can identify—such as a button’s role and accessible name—then scope them to the right page component. This makes each action’s target clear and lets Playwright resolve it against the current DOM. Reserve custom selector engines for recurring needs that built-in locators cannot express cleanly; a custom engine is not automatically more stable.

What makes a Playwright locator stable?

A stable locator identifies the intended element by meaningful, distinctive context without depending unnecessarily on how the page is implemented. Playwright calls locators “the central piece of Playwright’s auto-waiting and retry-ability.” Locator actions resolve against the current DOM, which helps when a page rerenders between actions. These features support resilient tests, but the documentation does not quantify how much any locator design reduces flakiness.

As an Amazon Associate I earn from qualifying purchases.

Use four questions to assess a locator or abstraction:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Does it express what a user or assistive technology can perceive?
  • Does it identify exactly one intended element?
  • How much does it depend on markup or structure that may change?
  • Can it be reused without concealing the page behavior it represents?

Playwright’s guidance favors user-facing locator APIs over brittle selectors. That is a qualitative design principle, not a published ranking or measured comparison.

Choose the locator that matches the behavior

Use roles and accessible names for interactive controls

For a button users recognize as “Save,” prefer getByRole('button', { name: 'Save' }). This describes the control through its role and accessible name instead of its tag, class, or position in the DOM. Playwright recommends locators that reflect user-visible behavior in its Best Practices and Locators documentation.

Use labels for form controls

For a labeled email field, getByLabel('Email') expresses the relationship a user encounters. It is generally a clearer choice than selecting an input by a CSS attribute when the label is the behavior your test cares about.

Use test IDs as an explicit testing contract

When visible text or semantic roles are not the behavior under test, a test ID can provide a deliberate contract between the application and tests. For example, getByTestId('account-menu') is explicit, but unlike a role or label it is not user-facing. The team must maintain the attribute as part of its testing interface.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep CSS and XPath exceptional

A short CSS or XPath selector can be appropriate when there is a specific reason to target implementation details. Long selectors anchored to nested structure are more exposed to markup changes; Playwright’s Other locators guidance notes that XPath is tied to implementation structure and can be less reliable as the DOM changes.

Scope repeated controls to meaningful components

Repeated cards, rows, and list items often contain controls with identical names. Locate the relevant component first, distinguish it by user-visible content, and then find the action within that component. For example, this helper identifies a list item by its heading and locates its button inside the matched item:

import { expect, type Locator, type Page } from '@playwright/test';

class ProductList {
  constructor(private readonly page: Page) {}

  product(name: string): Locator {
    return this.page
      .getByRole('listitem')
      .filter({ has: this.page.getByRole('heading', { name }) });
  }

  saveButton(name: string): Locator {
    return this.product(name).getByRole('button', { name: 'Save' });
  }

  async save(name: string): Promise {
    const button = this.saveButton(name);
    await expect(button).toHaveCount(1);
    await button.click();
  }
}

The example assumes each product is exposed as a list item and its name as a heading; adapt the roles and accessible names to the page’s actual semantics. A has filter is evaluated relative to each candidate locator match, so the inner locator must describe content within that candidate, not an unrelated page-wide element. See Playwright’s locator chaining and filtering guidance.

The uniqueness assertion makes ambiguity visible before the click. Playwright actions are strict when multiple elements match; a clear failure is usually safer than silently acting on a different element.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Encapsulate behavior without hiding it

A page object or component helper is useful when multiple tests perform the same meaningful interaction. It can centralize locator construction and operations such as saving a product, opening a menu, or submitting a form. Playwright’s page object models guide demonstrates this selector encapsulation.

Keep the abstraction aligned with the interface’s behavior. Named methods such as saveButton(name) or save(name) tell readers what the test intends; a generic helper that accepts opaque selector strings merely moves complexity elsewhere. For reusable components, accepting a scoped Locator can also keep the helper independent of unrelated page structure.

When to register a custom selector engine

Playwright supports custom selector engines through selectors.register(), documented under Extensibility. That API is an extension mechanism, not evidence that custom engines are more reliable than built-in locators.

Before adding an engine, check whether a role, label, text, test ID, chaining, or filtering already expresses the recurring need clearly. A custom engine can centralize a genuine domain-specific selection rule, but it also adds an extension layer that the team must understand and maintain. Use one only when the repeated need is demonstrated and built-in locators do not offer a sufficiently clear expression.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical review checklist

  • Prefer a role and accessible name for interactive controls, and a label for labeled form fields.
  • Use a test ID when the team intentionally maintains a testing contract that is not user-facing.
  • For repeated elements, scope by a meaningful container and distinguish it with relevant content.
  • Use has filters with a locator relative to the candidate being filtered.
  • When uniqueness is plausible but uncertain, assert it; do not routinely mask ambiguity with first(), last(), or nth().
  • Keep CSS and XPath short and justified rather than tying tests to a long chain of DOM details.
  • Extract repeated interactions into page or component helpers with names that expose their purpose.
  • Introduce a custom selector engine only for a recurring need that built-in locators do not handle clearly.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.