Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 35 ยท Finding Elements

Writing Selectors That Do Not Break

Choose selectors that survive redesigns: test ids, accessible roles and labels, and what to avoid (CSS classes, XPath, positions), with a brittleness rater.

Most end-to-end test maintenance is not about logic. It is about selectors that stop matching after someone renames a class, wraps a button in another div, or reorders a list. The test says the checkout is broken; the checkout is fine; only the test's idea of where the button lives has gone out of date.

A good selector answers one question: which element do I mean, in terms that will still be true after the page is restyled? This lesson gives you a ladder of selector choices from most to least stable, a list of smells to recognize on sight, and a few before-and-after refactors. It applies to both tools. For the tool-specific syntax, see Selecting Elements in Cypress and Locators in Playwright.

Real versus stand-in. Cypress and Playwright snippets are real code but read-only here: the site cannot run a browser. The runnable example is a small rule-based scorer written for this lesson. Its numbers are made up to illustrate the ideas; no tool ships a "brittleness score".

Why selectors break

Every selector couples your test to something in the page. The question is what you couple to, and how often that thing changes for reasons unrelated to behavior.

You couple to Changes when Verdict
Page structure (div > div:nth-child(3)) Any wrapper or order changes Very fragile
Styling (.btn.primary, .mt-4) A redesign or CSS refactor Fragile
Generated names (.css-1x9f2a, #input-48213) Every build Very fragile
Copy ('Place your order now!') Marketing edits the wording Moderate
Role and name (button called "Place order") The feature itself changes Stable
A test attribute (data-testid="place-order") Someone deletes it by mistake Stable

The stable rows share one trait: they describe what the element is for, not where it sits or how it looks.

The ladder: from best to worst

flowchart TD
  A["Need to find an element"] --> B{"Has a role and a name<br/>a user would recognize?"}
  B -- yes --> C["Role plus name<br/>(getByRole)"]
  B -- no --> D{"Form control with<br/>a label?"}
  D -- yes --> E["Label or placeholder<br/>(getByLabel)"]
  D -- no --> F{"Stable visible text?"}
  F -- yes --> G["Text, scoped to a region"]
  F -- no --> H["Dedicated test attribute<br/>(data-testid or data-cy)"]
  H --> I["CSS or XPath: last resort"]

Walk down until you find something that describes meaning. Stop at the first rung that works.

1. Role and accessible name. This is also a free accessibility check: if the control cannot be found this way, assistive technology probably struggles too. In Playwright it is getByRole. Cypress does not include a role query in its core, so teams add Testing Library's cypress-testing-library (cy.findByRole) or fall back to cy.contains('button', 'Place order'), which combines a tag and visible text.

2. Labels and placeholders for form fields: getByLabel('Email address') in Playwright, or cy.findByLabelText('Email address') with Testing Library.

3. Text, for headings, messages and static content. Keep it short and scope it so one change in the footer cannot break checkout tests.

4. A test attribute. Add data-testid (Playwright's default) or data-cy (a Cypress convention) to elements that have no role or text of their own, such as a container, a chart or a list row. The attribute exists only for tests, so nobody restyles it away. Agree on a naming scheme (order-summary, cart-row) and treat the attribute as part of the component's contract.

5. CSS or XPath, only when nothing above is available. Prefer a short selector anchored to a stable attribute: [data-state="open"] rather than body > div:nth-child(3) .panel.

Smells to recognize on sight

  • Positional selectors. :nth-child(2), eq(3), //li[4], .nth(2). They break when the list order changes, and worse, they can silently click the wrong thing. Pick by content (filter({ hasText: 'Coffee' })) when you can.
  • Absolute XPath. /html/body/div[2]/div/form/button[1] encodes the entire page layout.
  • Styling classes. .btn-primary, .mt-4, .text-red-500. A designer owns those names, not you.
  • Hashed or generated classes and ids. CSS-in-JS and bundlers produce names like .css-1x9f2a. They are different on every build.
  • Deep chains. #app > div > main > section > form > div > button. Each wrapper is another way to break.
  • Bare tags. button or div matches too much. cy.get('button') with three buttons on the page is a bug waiting to happen.
  • Long literal copy. A whole sentence as a selector fails when someone fixes a typo. Match a short, meaningful fragment, or use a regular expression.
  • Selecting by unrelated state. A selector like .active can mean different things in different widgets.

Refactoring examples

Each pair below targets the same element. The "after" versions say what the element is rather than where it is.

TypeScript
// Playwright, before
await page.locator('#app > div:nth-child(2) > form > div:nth-child(4) > button').click();
// after
await page.getByRole('button', { name: 'Place order' }).click();

// Playwright, before
await page.locator('.css-1x9f2a input').fill('[email protected]');
// after
await page.getByLabel('Email address').fill('[email protected]');

// Playwright, before: the third row, whatever it holds
await page.locator('li').nth(2).getByRole('button').click();
// after: the row that mentions Cocoa
await page.getByTestId('cart-row').filter({ hasText: 'Cocoa' })
  .getByRole('button', { name: 'Remove' }).click();
JavaScript
// Cypress, before
cy.get('.btn.primary').click();
cy.get('form div:nth-child(2) input').type('[email protected]');

// after: a test attribute you added
cy.get('[data-cy=place-order]').click();
cy.get('[data-cy=email]').type('[email protected]');

// after: visible text with a tag, when the wording is part of the feature
cy.contains('button', 'Place order').click();

Cypress's official guidance favors data-* attributes for exactly this reason, and many Cypress projects wrap them in a helper (cy.getByCy('email')) defined as a custom command; see Hooks, Fixtures and Custom Commands.

Text versus structure

Text selectors are tempting because they read well, but they come with two problems:

  • Internationalization. If your app is translated, a test that clicks "Place order" fails in the German build. Either run tests in one fixed locale, or use test ids for strings that vary.
  • Copy churn. Product text is edited constantly. Use text for things that are the feature (a confirmation message the user must see) and not for incidental labels. In assertions, a regular expression such as /order (placed|confirmed)/i tolerates small rewording.

Structure is worse, but a little structure is fine. Scoping is the healthy kind: "the Remove button inside the row that mentions Cocoa" uses structure only to narrow a search, while naming what you want.

Working with developers

Stable selectors are a team agreement. Ask for test attributes on important elements during code review, write down the naming convention, and do not strip data-testid in production builds unless you have a reason (stripping is possible, but then your staging runs and production smoke tests need different builds). If a component library renders your control, check whether it forwards data-* attributes to the DOM.

A brittleness rater you can run

The stand-in below scores selector strings with a few rules from the smell list. It is deliberately crude (a real project should rely on review, not a regex), but running candidates through it makes the principles concrete. Add your own selectors to the list and watch the score change.

JS Rate selectors from solid to brittle

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The three top lines name meaning (role, label, test attribute) and score high. Everything with a position, a generated class or a long chain scores near zero. The bare div and the long sentence land in the middle for different reasons: one matches too much, the other depends on exact wording.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which selector is least likely to break during a visual redesign?

    Role plus name describes what the control is for. The other three depend on styling, position or generated class names, all of which change in a redesign.
  2. 2. Why are positional selectors such as :nth-child(3) risky?

    A position says nothing about meaning. When the page changes the selector keeps matching, but possibly the wrong element, so the test may pass or fail for the wrong reason.
  3. 3. When is a dedicated data-testid or data-cy attribute the best choice?

    Roles and labels come first because they also verify accessibility. A test attribute is the right fallback for elements that have nothing user-facing to describe them.
  4. 4. A test passes in English and fails in the German build because it clicks getByText('Place order'). What is the most robust fix?

    Copy changes with language. A test attribute (or a pinned locale) removes the dependence on wording. XPath and sleeps do not address the cause.

Summary

  • Selectors couple a test to the page; choose coupling that describes meaning, not position or styling.
  • Prefer role plus name, then labels, then short scoped text, then data-testid or data-cy; keep CSS and XPath for last.
  • Avoid positions, absolute XPath, styling classes, generated names, deep chains and bare tags.
  • Scoping (a row, a dialog) is a healthy use of structure; pick rows by content rather than index.
  • Treat test attributes as a contract with developers, and agree on naming.
  • The scorer here is a teaching toy: the rules are illustrative, not a standard.

Next: Clicking, Typing and Other Actions.