getByRole in depth: options and precision
getByRole finds an element in the accessibility tree by role and accessible name, not by tag or class. The name matches as a case-insensitive substring by default, and exact: true or a regex gives precision. If the element is in the DOM but getByRole cannot find it, it is often a markup defect (no label or aria-label) that should be fixed in the app.
Playwright · Locators
The button is in the DOM but getByRole cannot find it. Is it a test bug or an app bug?
A developer added an icon button "×", the test looks for getByRole('button', { name: 'Close' }) and times out although the button is visible on screen. Another test with name: 'Save' suddenly finds two buttons. Both cases come from one mechanism: getByRole does not search by tags but by the accessibility tree, and the name matches by specific rules. This lesson shows how it works, how to read a failure, and where the test's responsibility ends and an app bug begins.
How it works and why. From the DOM the browser builds a separate accessibility tree in which every element has a role (button, link, heading, textbox) and an accessible name. Screen readers read this tree, and getByRole searches it. The role comes from an explicit role attribute or is derived from the tag: <button> is a button, <a href> is a link, <h2> is a heading, <input type="checkbox"> is a checkbox. The name is built from the element's content, aria-label, aria-labelledby, an associated <label> or alt. The design decision: the locator checks what a real assistive-technology user gets, so a test also catches lost accessibility.
From the DOM to getByRole
How name matches. By default name is a case-insensitive substring search and whitespace is normalised. So { name: 'Save' } finds both "Save" and "Save draft". For a full match there is exact: true (case-sensitive, the whole string), for a flexible match a regex. Extra options filter by state: checked, pressed, expanded, selected, disabled, and level for headings.
page.getByRole('button', { name: 'Save' }); // substring
page.getByRole('button', { name: 'Save', exact: true }); // exact only
page.getByRole('link', { name: /^Order #\d+$/ }); // regex
page.getByRole('heading', { name: 'Cart', level: 1 });
page.getByRole('checkbox', { name: 'I agree', checked: true });
page.getByRole('button', { name: 'Menu', expanded: false });
Substring or exact match
{ name: 'Save' }
Case-insensitive substring: finds "Save" and "Save draft". Two buttons, and the action fails with a strict mode violation.
{ name: 'Save', exact: true }
The whole string, case-sensitive: one button only. For text variants a regex with anchors is better.
first().Example: a test fails and we trace the cause. The close button looks like "×", and the markup is:
<button class="close">×</button>
Error: expect(locator).toBeVisible() failed
Locator: getByRole('button', { name: 'Close' })
Expected: visible
Timeout: 5000ms
Error: element(s) not found
The log (shortened) says there is no element with this role and name. The element does have the button role, but its name is "×", not "Close". This is not a locator mistake: a screen reader user hears "×" and cannot tell what the button does. The correct fix is in the app:
<button class="close" aria-label="Close">×</button>
After that getByRole('button', { name: 'Close' }) works, and the test doubles as an accessibility check. A workaround through locator('.close') would make the test green while the defect stays.
Hidden content. By default elements with display: none, visibility: hidden and aria-hidden="true" are not in the accessibility tree, and getByRole does not see them. That is convenient: a closed modal will not be found by accident. When you need such an element, includeHidden: true exists. It also explains the puzzle "the element is in the DOM but getByRole does not see it".
Aria snapshot. To check the structure of a whole block (menu, navigation, form), version 1.49 added toMatchAriaSnapshot: it compares the accessibility tree with a YAML template. Composition and order matter, exact markup does not:
await expect(page.getByRole('navigation')).toMatchAriaSnapshot(`
- list:
- listitem:
- link "Home"
- listitem:
- link "Courses"
`);
The template can be generated from the current page state (UI Mode and codegen have an action for it), and names in it may be regular expressions.
Limits and tools. getByRole depends on markup quality: on pages without semantics (div instead of button) it is useless, and then you either fix the app or take getByTestId. Role and name do not tell two identical buttons in different blocks apart: chaining does that (the next lesson). To avoid guessing, use npx playwright codegen or the locator picker in UI Mode: they suggest the role and name. In Cypress the equivalent comes from Testing Library, while Selenium has none out of the box: people search by CSS or XPath.
Common mistakes.
- Forgetting that name is a substring: a strict mode violation appears. Fix it with
exact: trueor a regex, not withfirst(). - Working around a missing name with CSS: the test is green while the icon button is inaccessible to a screen reader.
- Expecting
getByRoleto see a hidden element withoutincludeHidden. - Writing long copy text instead of a short name or a regex: every wording change breaks the test.
- Looking for
getByRole('button')on a<div onClick>: there is no role, and that is a real accessibility defect.
Check yourself
getByRole('textbox', { name: 'Email' }) does not find a field that is visible on screen. What do you check first?
Answer
Whether the field has an accessible name: an associated <label>, aria-label or aria-labelledby. A placeholder also gives a name, but only when there is no label or title, and it disappears once text is typed, so the field needs a real label. If there is no name at all or it differs, that is an accessibility defect to fix in the app, not to bypass with CSS.
The page has the buttons "Add" and "Add to favourites". Why does { name: 'Add' } give a strict mode violation and what do you do?
Answer
Name is a case-insensitive substring, so both buttons match. You need exact: true or the regex /^Add$/. Adding first() is wrong: the test would depend on DOM order.
getByRole finds an element by role and accessible name, and the name matches as a case-insensitive substring by default. For precision there are exact: true and a regex. Middle/Senior: It works on the accessibility tree, so "not found" often means a markup defect: a field without a label or an icon button without aria-label. I pass such things to developers instead of bypassing them with CSS. State options (checked, expanded) and includeHidden refine the search, and I check a block's structure with toMatchAriaSnapshot.