Playwright 05 ๐ญ Locators โ getByRole, getByText, getByLabel, and getByTestId
A locator is Playwright’s way of describing how to find an element on the page. It is not a DOM query that runs once; it is a recipe that Playwright re-evaluates on every action and assertion, with auto-waiting and retry built in. The choice of locator determines whether the test is resilient to markup changes, whether it matches the element a screen reader would identify, and whether it fails with a clear message when the element is missing.
This chapter covers the four user-facing locators that cover most cases: getByRole, getByLabel, getByText, and getByTestId. The sections that follow walk through the priority order that Playwright recommends, the accessibility semantics that getByRole relies on, and the cases where getByTestId is the right fallback.
Key point: Playwright recommends user-facing locators in priority orderโrole, label, text, then test idโbecause a locator that matches what a user sees also survives refactors that change class names and DOM structure.
Why locator choice matters
The brittleness problem. A CSS selector like .btn-primary > span breaks when the class changes, when the markup adds a wrapper, or when the component is refactored. The test fails not because the behavior changed but because the selector did. A role-based locator like getByRole("button", { name: "Submit" }) finds the button by what it is and what it says, which is what a user does. The refactor that changes the class name does not break the test.
The accessibility problem. getByRole queries the accessibility tree, the same structure a screen reader uses. A test that uses getByRole("button", { name: "Submit" }) fails when the button is not accessibleโmissing an accessible name, hidden from assistive technology, or rendered as a <div> with a click handler. The test is therefore a check on accessibility as well as behavior.
The ambiguity problem. A locator that matches more than one element fails on action with a “strict mode violation” error that lists the matches. The error is a feature: it forces the test to be specific. getByText("Submit") may match a button and a heading; getByRole("button", { name: "Submit" }) matches only the button.
a. getByRole and the accessibility tree
getByRole(role, options) finds elements by their ARIA role. The role is the implicit or explicit role of the elementโbutton, link, heading, textbox, checkbox, listitem, and so on . The name option filters by accessible name, which is the label the element is announced with: the text of a button, the associated label of an input, the aria-label attribute.
import { test, expect } from "@playwright/test";
test("role locators", async ({ page }) => {
await page.goto("/");
// Button by its accessible name
await page.getByRole("button", { name: "Sign in" }).click();
// Heading by level and name
await expect(
page.getByRole("heading", { level: 1, name: "Dashboard" })
).toBeVisible();
// Textbox by its label
await page.getByRole("textbox", { name: "Email" }).fill("a@b.com");
// Checkbox by its label
await page.getByRole("checkbox", { name: "Remember me" }).check();
// Link by its name
await page.getByRole("link", { name: "Forgot password?" }).click();
});
The name option matches by substring by default, case-insensitively, and ignores whitespace. The exact: true option makes it an exact, case-sensitive match . The level option is specific to headings; checked is specific to checkboxes and radio buttons; expanded is specific to expandable elements.
getByRole is the first choice because it is the closest to how a user identifies an element. It also fails when the element is not accessible, which is the failure the test should catch.
b. getByLabel, getByText, and the form-field patterns
getByLabel(text) finds a form control by its associated <label>, aria-label, or aria-labelledby. It is the specific tool for inputs, and it is what a screen reader announces when the field receives focus.
// Label element associated with the input
await page.getByLabel("Email").fill("a@b.com");
// Aria-label on the input
await page.getByLabel("Search").fill("playwright");
// Exact match
await page.getByLabel("Password", { exact: true }).fill("secret");
getByText(text) finds an element by its text content. It matches the smallest element that contains the text, which is usually what the test wants, but it can match multiple elements when the text appears in several places. The exact option changes the match from substring to exact, and the useInnerText option matches the rendered text rather than the DOM text.
// Substring match (default)
await expect(page.getByText("Welcome back")).toBeVisible();
// Exact match
await expect(page.getByText("Welcome back", { exact: true })).toBeVisible();
// Regex match
await expect(page.getByText(/Welcome, \w+/)).toBeVisible();
getByText is for non-interactive contentโheadings, paragraphs, list items, status messages. For interactive elements, the role locator is more specific. A test that clicks getByText("Submit") may click a <span> inside the button rather than the button itself, and the click handler may not fire.
c. getByTestId and the fallback cases
getByTestId(id) finds elements by the data-testid attribute. The attribute is a test-only hook that is not visible to users and does not change when the design changes. Playwright recommends it only when the role, label, and text locators cannot identify the elementโa dynamic list item with no accessible name, a canvas, a component that renders differently per platform .
// The markup
// <button data-testid="submit-order">Place order</button>
// The locator
await page.getByTestId("submit-order").click();
The attribute name is configurable through testIdAttribute in the config, which is useful when the project already uses a different attribute like data-cy or data-test. The default is data-testid .
// playwright.config.ts
export default defineConfig({
use: {
testIdAttribute: "data-test",
},
});
The fallback order is documented as role, label, placeholder, text, alt text, title, then test id . The test id is last because it is the only locator that does not verify anything about the user experience: a data-testid on a <div> that is not a button passes getByTestId and fails the user who cannot click it.
Complete Example Session
// ============================================
// PART 1: THE MARKUP UNDER TEST
// ============================================
// <form>
// <label for="email">Email</label>
// <input id="email" type="email" />
//
// <label for="password">Password</label>
// <input id="password" type="password" />
//
// <button type="submit">Sign in</button>
// </form>
//
// <h1>Welcome back</h1>
// <div data-testid="session-timer">29:59</div>
// ============================================
// PART 2: ROLE AND LABEL LOCATORS
// ============================================
import { test, expect } from "@playwright/test";
test("sign in flow", async ({ page }) => {
await page.goto("/login");
// Label locator for inputs
await page.getByLabel("Email").fill("user@example.com");
await page.getByLabel("Password").fill("password123");
// Role locator for the button
await page.getByRole("button", { name: "Sign in" }).click();
// Text locator for the heading
await expect(page.getByText("Welcome back")).toBeVisible();
});
// ============================================================
// PART 3: TEST ID FOR THE ELEMENT WITH NO USER-FACING IDENTITY
// ============================================================
test("session timer is visible", async ({ page }) => {
await page.goto("/login");
await expect(page.getByTestId("session-timer")).toBeVisible();
});
The parts covered the markup, the label and role locators for the form, the text locator for the heading, and the test id locator for the element that has no user-facing identity.
Quick Reference
Locator Priority
| Priority | Locator | Best For |
|---|---|---|
| 1 | getByRole | Buttons, links, headings, inputs |
| 2 | getByLabel | Form fields |
| 3 | getByPlaceholder | Inputs without labels |
| 4 | getByText | Non-interactive content |
| 5 | getByAltText | Images |
| 6 | getByTitle | Elements with title attribute |
| 7 | getByTestId | No user-facing identity |
Options
| Option | Effect |
|---|---|
{ name: "text" } | Filter by accessible name |
{ exact: true } | Exact, case-sensitive match |
{ level: 1 } | Heading level |
{ checked: true } | Checked state |
{ useInnerText: true } | Rendered text, not DOM text |
Test ID Configuration
| Item | Default |
|---|---|
| Attribute | data-testid |
| Config key | use.testIdAttribute |
| Alternative attributes | data-cy, data-test |
Best Practices
โ Do This:
// Role locator for interactive elements
page.getByRole("button", { name: "Submit" }) // โ
// Label locator for form fields
page.getByLabel("Email") // โ
// Text locator for static content
page.getByText("Welcome back") // โ
// Test id only when no user-facing identity exists
page.getByTestId("canvas") // โ
โ Don’t Do This:
// CSS selectors tied to styling
page.locator(".btn-primary") // โ
// XPath
page.locator("//button[text()='Submit']") // โ
// Test id on an interactive element with a role
page.getByTestId("submit-btn") // use getByRole instead // โ
// Text locator for a clickable element
page.getByText("Submit").click() // may click a span // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Strict mode violation | Locator matches multiple elements | Use role + name, or .first() deliberately |
| Role locator finds nothing | Element is not accessible | Fix the accessibility, not the locator |
| Text locator clicks wrong element | Text is inside a child | Use role locator for interactive elements |
| Test id changes on refactor | data-testid is a test hook | Accept; it is the trade-off |
Real-World Examples
1. Button by role
page.getByRole("button", { name: "Sign in" })
2. Heading by level
page.getByRole("heading", { level: 1, name: "Dashboard" })
3. Input by label
page.getByLabel("Email")
4. Text by substring
page.getByText("Welcome")
5. Text exact
page.getByText("Welcome", { exact: true })
6. Test id
page.getByTestId("session-timer")
7. Custom test id attribute
// config: use: { testIdAttribute: "data-cy" }
page.getByTestId("submit")
8. Link by role
page.getByRole("link", { name: "Forgot password?" })
9. Checkbox by role
page.getByRole("checkbox", { name: "Remember me" })
10. Regex text
page.getByText(/Welcome, \w+/)
Visual
Locator Priority
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ HIGHEST PRIORITY โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ getByRole (accessibility tree) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ
โ โ getByLabel (form fields) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ
โ โ getByText (static content) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ
โ โ getByTestId (no user-facing identity) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ LOWEST PRIORITY โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Accessibility Tree
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ DOM ACCESSIBILITY TREE โ
โ <button>Sign in</button> role: button โ
โ name: "Sign in" โ
โ โ
โ getByRole("button", { โ
โ name: "Sign in" โ
โ }) โ
โ โ โ
โ โผ โ
โ Finds the element by what the screen reader sees โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Locator Re-evaluation
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ const button = page.getByRole("button", { name: "X" }) โ
โ โ
โ Action 1: button.click() โ
โ โ resolves X, clicks โ
โ โ
โ Action 2: button.click() โ
โ โ resolves X again (re-evaluated) โ
โ โ
โ A locator is a recipe, not a snapshot. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Strict Mode
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ page.getByText("Submit") โ
โ โ โ
โ โผ โ
โ Matches: <button>Submit</button> โ
โ <h2>Submit</h2> โ
โ โ โ
โ โผ โ
โ Strict mode violation: 2 elements โ
โ โ
โ Fix: getByRole("button", { name: "Submit" }) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Role locator | getByRole(role, { name }) |
| Label locator | getByLabel(text) |
| Text locator | getByText(text) |
| Test id locator | getByTestId(id) |
| Default test id attribute | data-testid |
| Priority order | Role, label, placeholder, text, alt, title, test id |
| Strict mode | Multiple matches fail on action |
Key takeaways:
getByRoleis the first choice. It queries the accessibility tree, so it finds the element by what a user would identify and fails when the element is not accessible .getByLabelis for form fields. It finds the input by the label a screen reader announces, which is the same text the user sees next to the field .getByTextis for static content. It matches the smallest element containing the text, which is usually what the test wants, but it can match multiple elements and it can click a child rather than the interactive parent.getByTestIdis the fallback. It does not verify anything about the user experience, which is why it is last in the priority order. Use it when the element has no user-facing identity, and configure the attribute name if the project already uses a custom one .- Locators re-evaluate on every action. A locator is a recipe, not a snapshot. The same locator resolves again on the next action, which is how auto-waiting and retry work .
Remember: A locator is a description of how to find an element, and the description should match how a user would find it. getByRole is the closest to the user’s view, getByLabel is the form-field version, getByText is for content, and getByTestId is the last resort. When a locator matches multiple elements, the strict mode violation is the test telling you to be more specific, not a bug to work around. When a role locator fails, the element is not accessible, and that is a finding.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!