| | |

Playwright 05 ๐ŸŽญ Locators โ€” getByRole, getByText, getByLabel, and getByTestId

โฑ๏ธ Estimated read: 10 min | |

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

PriorityLocatorBest For
1getByRoleButtons, links, headings, inputs
2getByLabelForm fields
3getByPlaceholderInputs without labels
4getByTextNon-interactive content
5getByAltTextImages
6getByTitleElements with title attribute
7getByTestIdNo user-facing identity

Options

OptionEffect
{ 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

ItemDefault
Attributedata-testid
Config keyuse.testIdAttribute
Alternative attributesdata-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

PitfallWhy It HappensFix
Strict mode violationLocator matches multiple elementsUse role + name, or .first() deliberately
Role locator finds nothingElement is not accessibleFix the accessibility, not the locator
Text locator clicks wrong elementText is inside a childUse role locator for interactive elements
Test id changes on refactordata-testid is a test hookAccept; 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

ItemValue
Role locatorgetByRole(role, { name })
Label locatorgetByLabel(text)
Text locatorgetByText(text)
Test id locatorgetByTestId(id)
Default test id attributedata-testid
Priority orderRole, label, placeholder, text, alt, title, test id
Strict modeMultiple matches fail on action

Key takeaways:

  • getByRole is 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 .
  • getByLabel is 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 .
  • getByText is 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.
  • getByTestId is 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.

Was this helpful?


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!