Playwright · Reliable end-to-end tests

Why prefer getByRole and other user-facing locators?

Mediumlocatorsaccessibilityrole selectorsUpdated Oct 2026
Quiz this track

Short answer

Role locators query the accessibility tree the way assistive technology does. They survive CSS and DOM refactors and push the UI toward accessible, meaningful markup.

Playwright's recommended locators mirror what a user perceives: role, label, placeholder, text, alt text and title. getByRole is usually the best default because it combines the element's semantic role with its accessible name.

ts
await page.getByRole("textbox", { name: "Email" }).fill("asha@example.com");
await page.getByRole("button", { name: "Save changes" }).click();
await page.getByRole("link", { name: "Billing" }).click();
await page.getByRole("checkbox", { name: "Remember me" }).check();
Each locator names the role a user or screen reader would encounter.

The user-facing order of preference

  • getByRole for buttons, links, headings, inputs and other semantic controls
  • getByLabel for form fields with an associated label
  • getByPlaceholder when the placeholder is the only visible hint
  • getByText for non-interactive content such as paragraphs or list items
  • getByAltText for images and getByTitle for title attributes
  • getByTestId when no user-facing query is stable or meaningful

An accessible name can come from visible text, a label, aria-label or aria-labelledby. If a button has no accessible name, a role locator cannot find it, which is often a real accessibility defect rather than a reason to switch to a CSS selector.

Test IDs are not forbidden. They are a good escape hatch for elements with no stable user-facing identity, such as a chart container. The problem is making them the default and letting the rest of the markup stay inaccessible.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What makes an accessible name?
  2. 2When is getByTestId justified?
  3. 3Why can a role locator fail on an unlabelled button?
  4. 4How does getByRole relate to screen readers?

Say it in the interview

I default to getByRole because it matches how users and assistive technology identify controls, and it ties the test to accessible names rather than CSS. I use getByLabel for form fields and getByText for non-interactive content. Test IDs are a fallback for elements with no meaningful user-facing identity. If a role query cannot find a control, I first check whether the control is actually accessible.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Playwright mock interview and get scored feedback on depth, clarity and confidence.