#What a locator is
AddedA locator is a recipe for finding an element, not the element itself. page.getByRole("button", { name: "Sign in" }) doesn't search the page when you write it. It stores the description "a button whose accessible name is Sign in", and Playwright looks for a match every time you use it: when you click, fill, or assert. If the page has re-rendered since the last use, the next use finds the new element.
That one design decision explains most of how Playwright behaves:
- You can create a locator before the element exists. Writing it costs nothing; only using it waits.
- Re-renders don't break it. Frameworks throw away and rebuild DOM nodes all the time. A locator doesn't hold a node, so there's nothing to go stale.
- It's strict. An action like
click()needs exactly one element. If the recipe matches two, Playwright refuses to guess and fails with a strict mode violation, listing what it found. Guessing would mean clicking whichever came first in the DOM today, which is how tests click the wrong thing silently.
The mental model: a locator is a search you've saved, not a result you've kept. Think of a saved search in your email ("from: Ana, unread"): opening it tomorrow shows tomorrow's emails. A kept result would be yesterday's list.
Here's both halves on the cart, which rebuilds its whole table every time you press + or −:
import { test, expect, type Page } from "@playwright/test";
// Open a page while signed out: the shop sends you to sign in, then back to that page.
async function signIn(page: Page, path = "/practice/shop") {
await page.goto(path);
await page.getByLabel("Username").fill("rohit");
await page.getByLabel("Password").fill("playwright");
await page.getByRole("button", { name: "Sign in" }).click();
await expect(page).toHaveURL(path);
}
test("a locator is found again after every re-render", async ({ page }) => {
await signIn(page);
await page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).click();
// Written before the cart page exists. Nothing is searched yet.
const plus = page.getByRole("button", { name: "Increase quantity of Wireless Mouse" });
const quantity = page.getByRole("status", { name: "Quantity of Wireless Mouse" });
await page.getByRole("link", { name: "Cart (1)" }).click();
await plus.click(); // the cart rebuilds its table: this button is thrown away
await plus.click(); // a brand-new button; the recipe finds it
await expect(quantity).toHaveText("3");
});
test("strictness: an action or assertion needs exactly one element", async ({ page }) => {
await signIn(page);
await page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).click();
await page.getByRole("link", { name: "Cart (1)" }).click();
await expect(page.getByLabel("Quantity of Wireless Mouse")).toHaveText("1");
});Running 2 tests using 1 worker
✓ 1 [chromium] › tests/recipe.spec.ts:12:1 › a locator is found again after every re-render (2.0s)
✘ 2 [chromium] › tests/recipe.spec.ts:26:1 › strictness: an action or assertion needs exactly one element (1.8s)
1) [chromium] › tests/recipe.spec.ts:26:1 › strictness: an action or assertion needs exactly one element
Error: expect(locator).toHaveText(expected) failed
Locator: getByLabel('Quantity of Wireless Mouse')
Expected: "1"
Error: strict mode violation: getByLabel('Quantity of Wireless Mouse') resolved to 3 elements:
1) <button type="button" data-dec="ms-01" aria-label="Decrease quantity of Wireless Mouse">−</button> aka getByRole('button', { name: 'Decrease quantity of Wireless' })
2) <output aria-label="Quantity of Wireless Mouse">1</output> aka getByRole('status', { name: 'Quantity of Wireless Mouse' })
3) <button type="button" data-inc="ms-01" aria-label="Increase quantity of Wireless Mouse">+</button> aka getByRole('button', { name: 'Increase quantity of Wireless' })
Call log:
- Expect "toHaveText" getByLabel('Quantity of Wireless Mouse') with timeout 5000ms
- waiting for getByLabel('Quantity of Wireless Mouse')
29 | await page.getByRole("link", { name: "Cart (1)" }).click();
30 |
> 31 | await expect(page.getByLabel("Quantity of Wireless Mouse")).toHaveText("1");
| ^
32 | });
33 |
at <project>/tests/recipe.spec.ts:31:63
Error Context: test-results/recipe-strictness-an-actio-6a3ec-n-needs-exactly-one-element-chromium/error-context.md
1 failed
[chromium] › tests/recipe.spec.ts:26:1 › strictness: an action or assertion needs exactly one element
1 passed (4.2s)signInopens the page it's given while signed out. The shop redirects to the sign-in page with?next=/practice/shop, and after signing in sends you back there. The last line waits for that URL, so the next step never runs on a half-finished sign-in.- In the first test,
plusandquantityare created while the browser is still on the shop page. No cart exists yet; that's fine, because a locator is only a description. - The first
plus.click()finds the + button, clicks it, and the cart re-renders by replacing its table's HTML. The button Playwright just clicked is gone from the page. - The second
plus.click()runs the recipe again and finds the new + button. The quantity goes 1 → 2 → 3, andtoHaveText("3")passes. - The second test fails, on purpose.
getByLabel("Quantity of Wireless Mouse")matches by substring, so it also matches "Decrease quantity of Wireless Mouse" and "Increase quantity of Wireless Mouse". The error lists all three elements and, helpfully, a better locator for each (aka getByRole('status', { name: 'Quantity of Wireless Mouse' })). - This is the failure Chapter 3's first draft hit. The fixes:
getByLabel("Quantity of Wireless Mouse", { exact: true }), or the role locator the error suggests. Never "fix" it with.first(): that picks whichever element happens to come first, which here is the − button.
Before locators (Playwright 1.14), tests used element handles: page.$(selector) returns a pointer to one DOM node. It's still in the API, and the docs mark it discouraged. Here's why, on the same cart:
import { test, expect, type Page } from "@playwright/test";
async function signIn(page: Page, path = "/practice/shop") {
await page.goto(path);
await page.getByLabel("Username").fill("rohit");
await page.getByLabel("Password").fill("playwright");
await page.getByRole("button", { name: "Sign in" }).click();
await expect(page).toHaveURL(path);
}
test("an element handle points at one node, which the re-render throws away", async ({ page }) => {
await signIn(page);
await page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).click();
await page.getByRole("link", { name: "Cart (1)" }).click();
const plus = await page.$("button[aria-label='Increase quantity of Wireless Mouse']");
await plus!.click(); // works: the node is still on the page
const error = await plus!.click({ timeout: 2000 }).catch((e: Error) => e);
console.log(error.message.split("\n")[0]);
await expect(page.getByRole("status", { name: "Quantity of Wireless Mouse" })).toHaveText("2");
});Running 1 test using 1 worker
elementHandle.click: Element is not attached to the DOM
✓ 1 [chromium] › tests/handle.spec.ts:11:1 › an element handle points at one node, which the re-render throws away (2.0s)
1 passed (2.4s)page.$(…)searches once and returns a handle to the node it found. It doesn't wait either: if the cart hadn't rendered yet, it would returnnull.- The first click works. The cart then rebuilds its table, so the node the handle points at is detached from the page.
- The second click fails at once with "Element is not attached to the DOM". The test catches the error to print its first line, then shows the quantity really is 2: only one click landed.
- With a locator, the second click would simply have found the new button. That's the whole reason locators replaced handles: modern UIs re-render constantly, and a test shouldn't care.