Playwright · Reliable end-to-end tests
Why prefer getByRole and other user-facing locators?
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.
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();The user-facing order of preference
getByRolefor buttons, links, headings, inputs and other semantic controlsgetByLabelfor form fields with an associated labelgetByPlaceholderwhen the placeholder is the only visible hintgetByTextfor non-interactive content such as paragraphs or list itemsgetByAltTextfor images andgetByTitlefor title attributesgetByTestIdwhen 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.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What makes an accessible name?
- 2When is getByTestId justified?
- 3Why can a role locator fail on an unlabelled button?
- 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.