Skip to main content

Locator strategy in depth

Why This Matters

The previous lesson gave you the order to try locators in. This one explains what happens underneath: how getByRole decides what an element is called, why a locator sometimes finds two elements where you expected one, or none where you expected one. Every rule below is checked against the practice site in tests/module-2/locators.spec.ts of the example repository. Several of those tests assert that a locator finds nothing or too much, because that is the point they make.

How getByRole sees a page

getByRole does not read the HTML the way you do. It reads the accessibility tree: the version of the page a screen reader gets. Every element there has a role and an accessible name.

The role usually comes from the HTML element itself:

HTML on the practice siteRole
<button>Sort by Price</button>button
<a href="/webelements">link
<input type="text">textbox
<input type="checkbox">checkbox
<select>combobox
<input type="range">slider
<h1> … <h6>heading, with a level
<tr>, <th>, <td>row, columnheader, cell
<nav aria-label="Main navigation">navigation

The accessible name comes from, in order of priority: aria-labelledby, aria-label, a connected <label>, and otherwise the element’s own text. The pagination buttons show the difference. Their text is 1, 2 and →, but they have aria-label="Page 2" and aria-label="Next page", so that is their name:

await page.getByRole("button", { name: "Page 2" }).click();
await expect(page.getByRole("button", { name: "Page 2" })).toHaveAttribute("aria-current", "page");

Rule 1: names match on a substring, unless you say exact

The sort button’s text is Sort by Name ▲: the arrow is part of it. All three of these are true on the practice site:

await expect(page.getByRole("button", { name: "Sort by Name" })).toBeVisible();
await expect(page.getByRole("button", { name: "Sort by Name", exact: true })).toHaveCount(0);
await expect(page.getByRole("button", { name: /^Sort by Name/ })).toBeVisible();

By default a string name matches case-insensitively, anywhere in the name. That is convenient here, because the arrow flips between ▲ and ▼. It is dangerous when one name is part of another, such as “Page 1” and “Page 10”, or “Log in” and “Log in with Google”. Then use exact: true, or a regular expression with ^ and $.

Rule 2: getByLabel needs a label that is connected

The filter panel shows the word “Category” above a dropdown. It looks like a label, but it is not connected to the <select>:

await expect(page.getByLabel("In Stock Only")).toBeVisible();     // <label> around the checkbox
await expect(page.getByLabel("Category")).toHaveCount(0);         // label not connected
await expect(page.getByTestId("category-filter")).toBeVisible();

A label counts when it wraps the field, or points to it with for="id", or when the field has aria-label or aria-labelledby. “In Stock Only” wraps its checkbox, so it works. “Category” does neither.

That is not just a testing problem. A screen reader announces the dropdown without a name, too. The right fix is in the application (<label for="category">). Until then, the test id is the right handle, and the failing getByLabel is a bug report you can hand to the developers. The two price sliders on the same page have the same problem.

Rule 3: what is hidden from a screen reader is not in the name

The cart button shows an icon, then “0 items”, then “$0.00”. The icon is a font ligature: the HTML contains the word shopping_cart, which the font draws as a cart. The site marks it as hidden for assistive technology:

<button data-testid="cart-button">
  <span aria-hidden="true">shopping_cart</span><span>0 items</span><span>$0.00</span>
</button>

So the text contains the word, and the accessible name does not:

const cart = page.getByTestId("cart-button");
await expect(cart).toContainText("shopping_cart");
await expect(cart).toHaveAccessibleName(/^0 items\s*\$0\.00$/);
await expect(page.getByRole("button", { name: "shopping_cart" })).toHaveCount(0);

This came out of the course’s own testing. The first version of this test expected shopping_cart in the name, because the page’s textContent contains it. The test failed in all three browsers, and the browsers were right. toHaveAccessibleName is the quickest way to find out what a role locator will see.

Rule 4: role options describe state

Besides name, getByRole accepts the state of an element:

await expect(page.getByRole("button", { name: "Out of Stock", disabled: true })).toHaveCount(1);
await expect(page.getByRole("heading", { level: 1 })).toHaveText("E-commerce Testing Practice");
await page.getByRole("button", { name: "Widgets", expanded: false }).click();   // an accordion

Others are checked (checkboxes, radio buttons), pressed (toggle buttons), selected (tabs, options) and includeHidden. Use them when the state is part of what you mean: “the collapsed Widgets section”, “the disabled button”.

Rule 5: filter on structure, not on any text

filter({ hasText }) keeps elements that contain the text anywhere inside, again as a case-insensitive substring. Usually that is fine. After sorting by price, it is not:

await page.getByRole("button", { name: "Sort by Price" }).click();
const cards = page.getByTestId(/^product-\d+$/);

await expect(cards.filter({ hasText: "Wireless" })).toHaveCount(2);
await expect(cards.filter({ has: page.getByRole("heading", { name: "Wireless Mouse" }) })).toHaveCount(1);

Two cards contain “wireless”: the Wireless Mouse, and the Bluetooth Headphones, whose description says Enjoy wireless freedom. Sorted by name, the two are on different pages and the bug stays hidden. Sorted by price, they are side by side. filter({ has }) with the heading says what you mean: the card whose title is Wireless Mouse.

The same happens in tables. On /webelements?el=webtables:

await expect(table.getByRole("row").filter({ hasText: "John" })).toHaveCount(2);   // John Doe, Bob Johnson
const jane = table.getByRole("row").filter({ has: page.getByRole("cell", { name: "Jane Smith", exact: true }) });
await expect(jane).toHaveCount(1);

Also useful: hasNot (cards without a SALE badge), hasNotText, and visible: true (only the visible matches).

Tables: a row by its content, a cell by its column

A test that reads “the third cell of the second row” breaks when someone sorts the table or adds a column. Find the row by what it contains, and the column by its header:

const table = page.getByTestId("web-table");
const headers = table.getByRole("columnheader");
await expect(headers).toHaveText(["ID", "Name", "Email", "Role"]);

const email = (await headers.allTextContents()).indexOf("Email");
await expect(jane.getByRole("cell").nth(email)).toHaveText("jane@example.com");

The toHaveText on the headers comes first for a reason. It waits until the table is there, so the allTextContents() that follows reads a finished table (module 3: read only after you have waited).

When order is the point

.first(), .last() and .nth() are a smell when you use them to get past strict mode: the test then depends on an order nobody promised. They are the right tool when the order is the behaviour you test:

await page.getByRole("button", { name: "Sort by Price" }).click();
await expect(cards.first().getByRole("heading")).toHaveText("Smartphone Stand");   // the cheapest

The site has “Web Elements”, “API” and “Shopping” links in the header and in the footer. getByRole("link", { name: "Web Elements" }) finds two. Instead of .first(), say which navigation you mean:

page.getByRole("navigation", { name: "Main navigation" }).getByRole("link", { name: "Web Elements" });

Chaining from a landmark (a navigation, a dialog, a table, a card) is the most reliable way to make a locator unique. Module 7 builds component objects on exactly this idea.

Shadow DOM and frames

Web components put their content in a shadow root. Playwright’s CSS and role locators look inside open shadow roots automatically. XPath does not. The practice site has a real example, although not on its “Shadow DOM” page (that one is simulated with an ordinary input). Next.js renders an invisible route announcer with role="alert" inside a shadow root on every page:

await expect(page.getByRole("alert")).toHaveCount(1);
await expect(page.locator("[role=alert]")).toHaveCount(1);
await expect(page.locator("//*[@role='alert']")).toHaveCount(0);

This is the element that broke a visual test in module 6. getByRole("alert") matched this announcer instead of the login error.

Frames are different: a page inside an <iframe> is a separate document, and no locator crosses into it by itself. Enter the frame first:

const frame = page.frameLocator("#payment-frame");
await frame.getByRole("textbox", { name: "Card number" }).fill("4242 4242 4242 4242");

The practice site has no iframes. You will meet them in payment forms, embedded editors and chat widgets.

A strategy you can explain to your team

  1. Role and name for anything a user interacts with or reads as a unit: buttons, links, fields, headings, rows.
  2. Label for form fields. If getByLabel fails, report the missing label as an accessibility bug.
  3. Text for non-interactive content you assert on: a message, a price.
  4. Test id where the accessibility tree has nothing usable: a container without a role (the product cards), an element whose name changes with the data (the cart button), or a gap the developers have not fixed yet.
  5. CSS or XPath only for what none of the above can reach, with a comment saying why.

Then make every locator unique by scoping (from a landmark or a card) and by filtering on structure (has), not by position.

Debugging a locator

  • UI mode (npm run test:ui): the Pick locator button shows what Playwright would use for any element, and highlights every match of a locator you type.
  • npx playwright test --debug: runs one step at a time. The Inspector shows the current locator, and you can edit it and see the matches live.
  • toHaveCount in a scratch test is the fastest way to check how many elements a locator finds.
  • toHaveAccessibleName tells you what a role locator sees, as Rule 3 showed.

Exercise

On https://practiceautomatedtesting.com, write locators for:

  1. The “4★” minimum-rating filter
  2. Bob Johnson’s role in the web table (/webelements?el=webtables), found through the Role column
  3. The “Next page” button, but only while it is enabled
  4. The “API” link in the footer

Check each with toHaveCount(1) before you use it.

Show suggested solution
page.getByRole("button", { name: "4★", exact: true });

const table = page.getByTestId("web-table");
const bob = table.getByRole("row").filter({ has: page.getByRole("cell", { name: "Bob Johnson", exact: true }) });
const role = (await table.getByRole("columnheader").allTextContents()).indexOf("Role");
bob.getByRole("cell").nth(role);   // "User"

page.getByRole("button", { name: "Next page", disabled: false });

page.getByRole("navigation", { name: "Footer navigation" }).getByRole("link", { name: "API" });

exact: true in the first one is a precaution: today no other button name contains “4★”, but a “4★ & up” label tomorrow would make the plain locator match two. For Bob, hasText: "Bob" would work today, but filtering on the cell keeps working when the table gets a “Bobby” too. Wait for the headers (toHaveText) before you read them.