Playwright NotesRohit’s interview study guide
Chapter 04

Locators

How Playwright finds things on the page: what a locator really is, the built-in locators and which to reach for first, how accessible names are computed, filtering and chaining, tables and lists, frames, shadow DOM and new tabs, and why some locators break on the first redesign while others last for years. Every test was run with Playwright 1.65.1 against the Practice Shop.

8 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#What a locator is

Added

A 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 −:

tests/recipe.spec.ts
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");
});
npx playwright test
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)
What’s happening
  1. signIn opens 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.
  2. In the first test, plus and quantity are created while the browser is still on the shop page. No cart exists yet; that's fine, because a locator is only a description.
  3. 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.
  4. The second plus.click() runs the recipe again and finds the new + button. The quantity goes 1 → 2 → 3, and toHaveText("3") passes.
  5. 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' })).
  6. 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.
AdvancedElement handles go stale; locators don't

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:

tests/handle.spec.ts
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");
});
npx playwright test
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)
What’s happening
  1. 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 return null.
  2. The first click works. The cart then rebuilds its table, so the node the handle points at is detached from the page.
  3. 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.
  4. 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.

#The built-in locators and the priority order

Added

Playwright has a getBy… method for each way a user recognises something on a page, plus getByTestId for when nothing user-facing is reliable, and locator(css or xpath) as the escape hatch. The docs list the built-ins and say "we recommend prioritizing user-facing attributes and explicit contracts such as page.getByRole()". In practice that gives an order to try them in:

#LocatorFinds byPractice Shop example
1getByRole(role, { name })the role and accessible name, as a screen reader sees themgetByRole("button", { name: "Sign in" })
2getByLabel(text)a form control's labelgetByLabel("Search products")
3getByPlaceholder(text)an input's placeholdergetByPlaceholder("Type a message") (chat)
4getByText(text)visible text, for non-interactive contentgetByText("Sold out")
5getByAltText(text)an image's altgetByAltText("Your profile picture")
6getByTitle(text)the title attributegetByTitle("Support chat") (the iframe)
7getByTestId(id)data-testid, a contract between developers and testsgetByTestId("cart-total")
8locator("css=…") / locator("xpath=…")the DOM's structure, classes and idslocator("#search"): last resort

Why this order: the higher a locator is, the more it tests what the user experiences and the less it depends on how the page is built. A button found by role and name keeps working when a developer swaps a <div> for a <button>, renames every CSS class or moves the markup around, and it fails when the user would be affected: the button disappears, is renamed, or loses its accessible name. CSS and XPath are the reverse: they break on refactors users never notice and keep passing when the user-facing text changes.

Here's each built-in finding something real in the shop:

tests/built-ins.spec.ts
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("every built-in locator, on the shop and account pages", async ({ page }) => {
  await signIn(page);
  await expect(page.getByRole("heading", { name: "Products", level: 1 })).toBeVisible();
  await expect(page.getByLabel("Search products")).toBeEditable();
  await expect(page.getByPlaceholder("Try")).toHaveAttribute("type", "search");
  await expect(page.getByText("Sold out")).toHaveCount(1);
  await expect(page.getByTestId("product-ms-02")).toContainText("Vertical Mouse");

  await page.getByRole("link", { name: "Account" }).click();
  await page.getByLabel("Profile picture").setInputFiles({ name: "me.png", mimeType: "image/png", buffer: Buffer.alloc(2048) });
  await expect(page.getByAltText("Your profile picture")).toHaveAttribute("src", /^blob:/);
  await expect(page.getByTitle("Support chat")).toBeVisible();
  await expect(page.locator("#displayName")).toHaveValue("Rohit"); // works, but tied to an id
});
npx playwright test
Running 1 test using 1 worker

  ✓  1 [chromium] › tests/built-ins.spec.ts:11:1 › every built-in locator, on the shop and account pages (1.9s)

  1 passed (2.3s)
What’s happening
  1. getByRole("heading", { name: "Products", level: 1 }) is the page's <h1>. level narrows headings to one level, so an <h2> called "Products" wouldn't match.
  2. getByLabel("Search products") finds the input through its <label for="search">. getByPlaceholder("Try") finds the same input by its placeholder, Try “mouse”: like the other text locators, a plain string matches a case-insensitive substring, so "Try" is enough (and saves typing the curly quotes).
  3. getByText("Sold out") finds the one product with that note. getByTestId("product-ms-02") finds the Vertical Mouse card by its data-testid, which the shop puts on every product for exactly this purpose.
  4. On the account page, the upload makes the preview image's src a blob: URL; getByAltText finds the image by its alt. (Uploads are Chapter 5.)
  5. getByTitle("Support chat") finds the chat <iframe> by its title attribute, which is also what gives the frame its accessible name for screen readers.
  6. The last line uses CSS. It passes, but it says "the element whose id is displayName", which only a developer knows and anyone can rename. getByLabel("Display name") says the same thing the way a user does. The test passes in about 2 seconds.
AdvancedWhen a test id is the right choice
Which locator would you use?

For each, pick a locator: (a) the "Place order" button, (b) the "Email" field on checkout, (c) the checkout total, which is a number with no label, (d) the "Your cart is empty." message.

Show answer

(a) getByRole("button", { name: "Place order" }). (b) getByLabel("Email"). (c) getByTestId("order-total"). (d) getByText("Your cart is empty.").

What’s happening
  1. A button has a role and a name, so role comes first; it also proves a screen reader can find it.
  2. A form field is identified by its label, which is exactly how a user finds it.
  3. The total's text is the value you want to check, so you can't find it by its text. Nothing user-facing names it, which is when a test id is the right tool.
  4. A message is non-interactive text, so getByText is the natural fit. (If it were in a role="status" or role="alert" region, getByRole("alert") would also work and checks the region's role.)

#getByRole and accessible names

Added

getByRole finds elements the way assistive technology does. Every element has a role (what it is: button, link, heading, textbox, checkbox, row, listitem…) and many have an accessible name (what it's called). Native HTML gives roles for free: <button> is a button, <a href> a link, <h2> a heading, <input type=checkbox> a checkbox, <tr> a row. ARIA attributes (role="status", aria-label) add or override them.

The accessible name is computed by the browser, following the W3C "accname" rules. The short version, in priority order:

  1. aria-labelledby: the text of the element(s) it points at.
  2. aria-label: the attribute's value.
  3. For form fields, the associated <label> (by for= or by wrapping), then title or placeholder as fallbacks.
  4. For buttons, links, headings, cells and similar: their text content, including the names of children.
  5. title as a last resort.

The mental model: the name is what a screen reader would say. If you can't work out what it would say, print it: locator.ariaSnapshot() shows roles and names exactly as getByRole sees them.

tests/names.spec.ts
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("what getByRole sees on the account page", async ({ page }) => {
  await signIn(page, "/practice/account");
  const profile = page.getByRole("region", { name: "Profile" });
  console.log(await profile.ariaSnapshot());

  await expect(profile.getByRole("button", { name: "Why we ask for a name" })).toHaveText("?");
  await expect(profile.getByRole("textbox", { name: "Display name" })).toHaveValue("Rohit");
  await expect(profile.getByRole("button", { name: "Profile picture" })).toHaveAttribute("type", "file");
});

test("exact, level, checked and disabled", async ({ page }) => {
  await signIn(page);
  await expect(page.getByRole("button", { name: "Add to cart", disabled: true })).toHaveCount(1);
  await page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).click();
  await page.getByRole("listitem").filter({ hasText: "USB Microphone" }).getByRole("button", { name: "Add to cart" }).click();
  await page.getByRole("link", { name: "Cart (2)" }).click();

  await expect(page.getByRole("button", { name: "Remove" })).toHaveCount(2); // substring: both Remove buttons
  await expect(page.getByRole("button", { name: "Remove", exact: true })).toHaveCount(0);
  await expect(page.getByRole("button", { name: /^Remove USB/ })).toHaveCount(1);

  await page.getByRole("link", { name: "Checkout" }).click();
  await expect(page.getByRole("heading", { level: 2 })).toHaveText("Order summary");
  await expect(page.getByRole("radio", { checked: true })).toHaveAccessibleName("Standard (3–5 days, free)");
});
npx playwright test
Running 2 tests using 1 worker

- region "Profile":
  - heading "Profile" [level=2]
  - text: Display name
  - button "Why we ask for a name": "?"
  - textbox "Display name": Rohit
  - button "Save"
  - status
  - text: Profile picture
  - button "Profile picture"
  - status
  ✓  1 [chromium] › tests/names.spec.ts:11:1 › what getByRole sees on the account page (1.0s)
  ✓  2 [chromium] › tests/names.spec.ts:21:1 › exact, level, checked and disabled (1.9s)

  2 passed (3.4s)
What’s happening
  1. getByRole("region", { name: "Profile" }): each account <section> has aria-labelledby pointing at its <h2>, which gives it the role region and the heading's text as its name (rule 1). Sections without a name aren't regions at all.
  2. The aria snapshot prints what's inside, in YAML. The "?" button shows as button "Why we ask for a name": "?": its aria-label (rule 2) beats its text, so its name is the label and its text is "?". The test asserts both.
  3. The text box is named "Display name" by its <label for> (rule 3), and the file input shows up as a button named "Profile picture" (it did in Chromium, Firefox and WebKit). That's useful to know when getByRole("textbox") doesn't find an upload field; getByLabel("Profile picture") finds it either way. The preview image isn't in the snapshot: it stays hidden until a picture is uploaded, and hidden elements aren't part of the accessibility tree. (An earlier version of the shop had CSS that overrode hidden and showed an empty image box; this very snapshot is what revealed it, and it's fixed.)
  4. In the second test, disabled: true keeps only disabled buttons: the sold-out Vertical Mouse's. On the cart, name: "Remove" is a case-insensitive substring, so it matches "Remove Wireless Mouse" and "Remove USB Microphone". exact: true means case-sensitive and whole-string, so nothing is called exactly "Remove". A regular expression gives full control.
  5. On checkout, level: 2 finds the one <h2>, and checked: true finds the selected radio. toHaveAccessibleName confirms its name comes from the wrapping <label>, including the en dash, exactly as the page writes it.
AdvancedHidden elements and includeHidden

By default getByRole ignores elements hidden from assistive technology (display: none, hidden, aria-hidden="true"). That's usually right: a user can't interact with them. It also explains a puzzle on the account page: the tooltip <p role="tooltip" hidden> isn't found by getByRole("tooltip") until you hover the "?" button, while getByText("Shown on your orders") finds it even while hidden (text locators match hidden elements; assertions like toBeVisible then tell you it's hidden). Pass includeHidden: true when you really need to find a hidden element by role, for example to assert that a collapsed menu's items exist.

AdvancedRoles you'll use most, and their HTML
RoleComes fromTypical name source
button<button>, <input type=submit>, role="button"text, or aria-label
link<a href>text
heading<h1>–<h6> (level 1–6)text
textbox<input> (text, email…), <textarea>its <label>
searchbox<input type=search>its <label>
checkbox / radio<input type=checkbox/radio>its <label>
combobox<select>its <label>
list / listitem<ul>, <ol> / <li>aria-label on the list; items usually have none
table, row, cell, columnheader, rowheader<table>, <tr>, <td>, <th scope=col/row><caption>; a row's name is all its cells' text
status / alertrole="status", <output> / role="alert"aria-label, often none
region<section> with an accessible namearia-labelledby

The shop's search box is a searchbox, not a textbox, because it's type="search". If a role locator finds nothing, print an aria snapshot rather than guessing.

#Filtering and chaining

Added

Most real locators are built in steps: find the right container, then the thing inside it. "The Add to cart button" is ambiguous on a page with eight products; "the Add to cart button in the Wireless Mouse card" isn't. Playwright gives you three ways to narrow:

  • Chaining: a.getByRole(…) searches only inside what a matched. products.getByRole("button") means buttons inside products.
  • Filtering: a.filter({ hasText, hasNotText, has, hasNot, visible }) keeps the elements of a that pass a test, without changing what you point at. has takes another locator, searched inside each element.
  • Combining: a.and(b) (matches both), a.or(b) (either).

Then there are the positional ones, first(), last() and nth(i), which pick by order. The docs say to use them "with caution", and the example below shows why. Two newer helpers round it off: visible() (1.63+) keeps only visible elements, and within(parent) (1.64+) runs a locator, including its nth, separately inside each parent.

The mental model: narrow by meaning, not by position. "The card that has the Wireless Mouse heading" stays right when the list is re-sorted; "the third card" doesn't.

tests/filtering.spec.ts
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("filter, chain, and/or", async ({ page }) => {
  await signIn(page);
  const products = page.getByRole("list", { name: "Products" }).getByRole("listitem");
  await expect(products).toHaveCount(8);

  await expect(products.filter({ hasText: "Mouse" })).toHaveCount(2);
  await expect(products.filter({ hasNotText: "Sold out" })).toHaveCount(7);
  const mouse = products.filter({ has: page.getByRole("heading", { name: "Wireless Mouse" }) });
  await expect(mouse.getByText("$")).toHaveText("$29.50");

  const soldOut = products.filter({ has: page.getByRole("button", { disabled: true }) });
  await expect(soldOut.getByRole("heading")).toHaveText("Vertical Mouse");
  await expect(page.getByRole("button", { name: "Add to cart" }).and(page.getByRole("button", { disabled: true }))).toHaveCount(1);

  await page.getByLabel("Search products").fill("lamp");
  const resultsOrEmpty = products.or(page.getByText(/No products match/));
  await expect(resultsOrEmpty).toHaveCount(1);
  await expect(resultsOrEmpty).toHaveText("No products match “lamp”.");
});

test("first, last and nth follow the order on screen", async ({ page }) => {
  await signIn(page);
  const products = page.getByRole("listitem");
  const third = products.nth(2).getByRole("heading");
  await expect(products.first().getByRole("heading")).toHaveText("Mechanical Keyboard");
  await expect(products.last().getByRole("heading")).toHaveText("Monitor Light Bar");
  await expect(third).toHaveText("Wireless Mouse");

  await page.getByLabel("Sort by").selectOption("Price: low to high");

  await expect(products.first().getByRole("heading")).toHaveText("Wireless Mouse");
  await expect(third).toHaveText("Vertical Mouse"); // same locator, different product
});
npx playwright test
Running 2 tests using 1 worker

  ✓  1 [chromium] › tests/filtering.spec.ts:11:1 › filter, chain, and/or (2.6s)
  ✓  2 [chromium] › tests/filtering.spec.ts:31:1 › first, last and nth follow the order on screen (1.8s)

  2 passed (4.8s)
What’s happening
  1. getByRole("list", { name: "Products" }).getByRole("listitem") is a chain: list items, but only inside the list named "Products" (its aria-label). toHaveCount(8) also waits for the products to load.
  2. filter({ hasText: "Mouse" }) keeps cards whose text contains "Mouse" (case-insensitive): Wireless and Vertical. hasNotText: "Sold out" drops the one sold-out card, leaving 7.
  3. filter({ has: getByRole("heading", { name: "Wireless Mouse" }) }) keeps the card that contains that heading. The inner locator is searched inside each card, not from the page, even though it's written as page.getByRole(…). Then mouse.getByText("$") chains into that card to read its price.
  4. has: getByRole("button", { disabled: true }) finds the card with a disabled button: the Vertical Mouse. and() gives the same answer from the other side: elements that are both an "Add to cart" button and a disabled button.
  5. or() matches either side: "the products, or the empty-state message". Right after typing "lamp" the 8 products are still showing (the search waits 0.3 s), so the union has 8 elements; toHaveCount(1) waits until only the message is left, and toHaveText then reads it. The count step matters: this page's first draft went straight to toHaveText, which needs exactly one element, and a strict mode violation inside an assertion fails at once instead of retrying. The run failed in under 2 seconds, listing the 8 products.
  6. The second test shows the danger of position. third is nth(2), the Wireless Mouse in the featured order. After sorting by price (low to high: $29.50, $39.00, $45.00…), the same locator reads "Vertical Mouse", because it's re-resolved and the third card is now a different product. A test that clicked nth(2) to buy the Wireless Mouse would now be trying to buy the sold-out Vertical Mouse.
Advancedvisible() and within(): the two newest helpers

visible() (1.63+) keeps only elements that are visible right now (checked each time the locator is used). within(parent) (1.64+) returns "this locator's elements inside each element matched by parent", and resolves positional parts like nth(2) separately in each parent: the docs' example is "the third cell of every row".

tests/newest.spec.ts
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("visible() and within()", async ({ page }) => {
  // Two past orders, so the account page has an Orders table (Chapter 8 shows better ways to set up state).
  await page.addInitScript(() => {
    const day = (d: number) => Date.UTC(2026, 10, d, 12);
    localStorage.setItem("shop-history", JSON.stringify([
      { id: "ORD-1001", placedAt: day(2), items: 2, total: 104.49 },
      { id: "ORD-1002", placedAt: day(20), items: 1, total: 29.5 },
    ]));
  });
  await signIn(page, "/practice/account");

  // The tooltip is in the page but hidden until you hover the "?" button.
  const tip = page.getByText("Shown on your orders and reviews.");
  await expect(tip).toHaveCount(1);
  await expect(tip.visible()).toHaveCount(0);
  await page.getByRole("button", { name: "Why we ask for a name" }).hover();
  await expect(tip.visible()).toHaveCount(1);

  // The last cell of every order row: the Total column.
  const rows = page.getByRole("table", { name: "Your orders" }).getByRole("row");
  await expect(page.getByRole("cell").last().within(rows)).toHaveText(["$104.49", "$29.50"]);
  // The inner locator must start from the page: it's searched inside each row.
  const wrong = page.getByRole("table", { name: "Your orders" }).getByRole("cell").last().within(rows);
  await expect(wrong).toHaveCount(0);
  console.log(String(wrong));
});
npx playwright test
Running 1 test using 1 worker

getByRole('table', { name: 'Your orders' }).getByRole('row').locator(getByRole('table', { name: 'Your orders' }).getByRole('cell').last())
  ✓  1 [chromium] › tests/newest.spec.ts:11:1 › visible() and within() (1.1s)

  1 passed (1.5s)
What’s happening
  1. addInitScript runs before the shop's own script on every page of this test and puts two past orders into localStorage, so the account page draws its Orders table. The dates are fixed in UTC, so the test gives the same result in any time zone.
  2. getByText finds the tooltip even while it's hidden, so the count is 1. tip.visible() counts only visible matches: 0 before hovering, 1 after. That's the replacement for the old :visible CSS pseudo-class, which the docs now say to avoid in favour of visible().
  3. page.getByRole("cell").last().within(rows) means "in each row, the last cell". The header row has no cells (only column headers), so it contributes nothing, and the two order rows give their totals. Without within, getByRole("cell").last() would be one cell: the last in the whole table.
  4. The trap: the inner locator is nested inside each row, so it must describe what to find in a row. wrong starts from the table, so it means "a table inside each row", and matches nothing. The printed locator shows how Playwright rewrote it: within is shorthand for rows.locator(innerLocator).
AdvancedFiltering is not the same as chaining

#Lists, tables and repeated items

Added

Repeated items (products, table rows, search results, wishlist entries) are where most locator mistakes happen, because the tempting answer is nth(). The reliable pattern is always the same: find the item by something that identifies it, then the part you want inside it. For a table: find the row by its key (the product, the order id), then the cell.

Tables give you good roles for free: row, columnheader, rowheader (a <th scope="row">) and cell. A row's accessible name is all of its cells' text joined, so getByRole("row", { name: /ORD-1002/ }) finds a row by any value in it. Playwright has no "cell under the Total column" locator, so you either count cells (when the column order is part of the design) or compute the index from the headers.

Counting and reading all items is the other common need: toHaveCount(n) and toHaveText([…]) assert the whole list at once (and wait), while all() and allTextContents() read it once, right now.

tests/tables.spec.ts
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("the cart: find the row, then the cell", async ({ page }) => {
  await signIn(page);
  for (const name of ["Wireless Mouse", "USB Microphone"]) {
    await page.getByRole("listitem").filter({ hasText: name }).getByRole("button", { name: "Add to cart" }).click();
  }
  await page.getByRole("link", { name: "Cart (2)" }).click();

  const table = page.getByRole("table", { name: "Your cart" });
  const mic = table.getByRole("row", { name: /USB Microphone/ });
  await mic.getByRole("button", { name: /^Increase/ }).click();

  // Columns: Product (a row header), Price, Quantity, Subtotal, Remove. Cells count from Price.
  await expect(mic.getByRole("cell").nth(2)).toHaveText("$149.98");
  await expect(table.getByRole("rowheader")).toHaveText(["Wireless Mouse", "USB Microphone", "Total"]);
  await expect(page.getByTestId("cart-total")).toHaveText("$179.48");
});

test("the orders table: a cell by its column header, and every row", async ({ page }) => {
  await page.addInitScript(() => {
    const day = (d: number) => Date.UTC(2026, 10, d, 12);
    localStorage.setItem("shop-history", JSON.stringify([
      { id: "ORD-1001", placedAt: day(2), items: 2, total: 104.49 },
      { id: "ORD-1002", placedAt: day(20), items: 1, total: 29.5 },
      { id: "ORD-1003", placedAt: day(23), items: 3, total: 216.0 },
    ]));
  });
  await signIn(page, "/practice/account");
  const table = page.getByRole("table", { name: "Your orders" });
  const bodyRows = table.getByRole("row").filter({ has: page.getByRole("rowheader") });
  await expect(bodyRows).toHaveCount(3);

  const headers = await table.getByRole("columnheader").allTextContents();
  const cellIn = (orderId: string, column: string) =>
    table.getByRole("row", { name: orderId }).getByRole("rowheader").or(table.getByRole("row", { name: orderId }).getByRole("cell")).nth(headers.indexOf(column));
  await expect(cellIn("ORD-1002", "Total")).toHaveText("$29.50");
  await expect(cellIn("ORD-1003", "Date")).toHaveText("2026-11-23");

  for (const row of await bodyRows.all()) {
    console.log(await row.getByRole("rowheader").textContent(), "→", await row.getByRole("cell").last().textContent());
  }
});

test("the wishlist: assert the whole list in order", async ({ page }) => {
  await signIn(page, "/practice/account");
  const wishes = page.getByRole("list", { name: "Wishlist" }).getByRole("listitem");
  await expect(wishes).toHaveText([/Monitor Light Bar/, /USB Microphone/, /Standing Desk Mat/]);
  await wishes.filter({ hasText: "Standing Desk Mat" }).getByRole("button", { name: /up$/ }).click();
  await expect(wishes).toHaveText([/Monitor Light Bar/, /Standing Desk Mat/, /USB Microphone/]);
});
npx playwright test
Running 3 tests using 1 worker

  ✓  1 [chromium] › tests/tables.spec.ts:11:1 › the cart: find the row, then the cell (2.0s)
ORD-1001 → $104.49
ORD-1002 → $29.50
ORD-1003 → $216.00
  ✓  2 [chromium] › tests/tables.spec.ts:28:1 › the orders table: a cell by its column header, and every row (1.0s)
  ✓  3 [chromium] › tests/tables.spec.ts:53:1 › the wishlist: assert the whole list in order (1.0s)

  3 passed (4.5s)
What’s happening
  1. The cart. The row is found by its product (name: /USB Microphone/, a regex because a row's name is all its cells' text). Inside the row, the + button is "the button whose name starts with Increase": scoped to the row, there's only one. The subtotal is nth(2) of the row's cells because the product name is a rowheader, not a cell: Price is 0, Quantity 1, Subtotal 2. $74.99 × 2 = $149.98, and the total is $29.50 + $149.98 = $179.48.
  2. table.getByRole("rowheader") reads the first column of every row, including the footer's "Total". toHaveText([...]) checks the count and each text in order, and waits until they all match.
  3. The orders table. bodyRows keeps rows that have a row header, which skips the header row. toHaveCount(3) waits for the table, and only then is it safe to read the headers once with allTextContents(): ["Order", "Date", "Items", "Total"].
  4. cellIn(orderId, column) finds the row by its order id, takes its row header or cells (in page order, so the union lines up with the headers), and picks the column's index. "Total" is index 3, so ORD-1002 gives $29.50; "Date" is index 1, so ORD-1003 gives 2026-11-23. This keeps working if someone reorders the columns.
  5. bodyRows.all() turns the locator into one locator per row as the page is now: it doesn't wait, which is why the count was asserted first. The loop prints each order id and its last cell.
  6. The wishlist is an ordered list. toHaveText with an array of regexes checks all three items in order (each <li> also contains the arrow buttons' text, so a regex is simpler than the exact text). After "Move Standing Desk Mat up", the array assertion waits for the new order.
AdvancedCounting and iterating without flakes
  • Assert counts with toHaveCount, which waits; await locator.count() reads once and is 0 while the list is still loading (Chapter 1 showed exactly that).
  • Assert all texts with toHaveText([...]) (exact, in order) or toContainText([...]) (a subset, in order). One assertion instead of a loop, and it retries as a whole.
  • Iterate with all() only after waiting, and only when you need to do something per item (open each product, compare each row with an API). all() takes a snapshot of how many items there are; items added later aren't in it.
  • Don't iterate to find one item. A loop that checks each row's text and clicks the matching one is filter({ hasText }) written the slow, flaky way.

#Frames, shadow DOM and new tabs

Added

Three things on real pages sit outside the normal document, and each needs a small step:

  • An iframe is a separate document inside the page (a chat widget, a payment form, an embedded video). Locators don't cross into it by themselves: you enter it with page.frameLocator(selector), or locator.contentFrame() on the <iframe> element, and chain from there. Since 1.63, page.frameLocator() with no selector searches every frame, and throws if the rest of the locator matches in more than one.
  • Shadow DOM is a component's private subtree (web components like the shop's <newsletter-signup>). Playwright's locators pierce open shadow roots automatically, so you write them as if the shadow root weren't there. Two exceptions from the docs: XPath doesn't pierce shadow roots, and closed shadow roots aren't supported.
  • A new tab (a link with target="_blank", window.open) is a new Page in the same context. You can't locate in it from the old page; you catch it with page.waitForEvent("popup"), started before the click.

The mental model: an iframe is a different house (you must go through its door), a shadow root is a room in this house with an open door (walk straight in), and a new tab is a second house your test has to be told about.

tests/boundaries.spec.ts
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("the support chat lives in an iframe", async ({ page }) => {
  await signIn(page, "/practice/account");
  await expect(page.getByRole("textbox", { name: "Message" })).toHaveCount(0); // not in the main page

  const chat = page.frameLocator('iframe[title="Support chat"]');
  await chat.getByRole("textbox", { name: "Message" }).fill("Where is my order?");
  await chat.getByRole("button", { name: "Send" }).click();
  await expect(chat.getByRole("listitem").last()).toHaveText("Support: Thanks! A human will reply within 1 business day.");

  // The same frame, two other ways in.
  await expect(page.getByTitle("Support chat").contentFrame().getByRole("listitem")).toHaveCount(3);
  await expect(page.frameLocator().getByRole("button", { name: "Send" })).toBeVisible(); // 1.63+
});

test("the newsletter box is inside an open shadow root", async ({ page }) => {
  await signIn(page, "/practice/account");
  await page.getByLabel("Email for newsletter").fill("rohit@example.com");
  await page.getByRole("button", { name: "Subscribe" }).click();
  await expect(page.getByText("Subscribed! Watch rohit@example.com for the next issue.")).toBeVisible();

  await expect(page.locator("newsletter-signup input")).toHaveCount(1); // CSS pierces too
  await expect(page.locator("//input[@id='nl-email']")).toHaveCount(0); // XPath does not
});

test("the help centre opens in a new tab", async ({ page }) => {
  await signIn(page, "/practice/account");
  const popupPromise = page.waitForEvent("popup"); // start waiting before the click
  await page.getByRole("link", { name: "Help centre" }).click();
  const help = await popupPromise;

  await expect(help).toHaveTitle("Help centre · Practice Shop");
  await help.getByText("Do you have promo codes?").click();
  await expect(help.getByText("Try SAVE10 for 10% off")).toBeVisible();
  await expect(page.getByRole("heading", { name: "Your account" })).toBeVisible(); // the first tab is still there
});
npx playwright test
Running 3 tests using 1 worker

  ✓  1 [chromium] › tests/boundaries.spec.ts:11:1 › the support chat lives in an iframe (2.4s)
  ✓  2 [chromium] › tests/boundaries.spec.ts:25:1 › the newsletter box is inside an open shadow root (1.0s)
  ✓  3 [chromium] › tests/boundaries.spec.ts:35:1 › the help centre opens in a new tab (1.1s)

  3 passed (5.0s)
What’s happening
  1. The iframe. The first assertion proves the point: from the main page, there's no "Message" text box (count 0), because it lives in /practice/chat, a separate document. page.frameLocator('iframe[title="Support chat"]') enters the frame; every locator chained from chat searches inside it.
  2. Sending the message adds "You: …" to the conversation, and the reply appears a second later. toHaveText on the last list item waits for it, through the frame boundary, like any other assertion.
  3. page.getByTitle("Support chat").contentFrame() is the other route in: find the <iframe> element with an ordinary locator, then step into its content. page.frameLocator() with no selector (1.63+) searches all frames; it works here because only the chat has a "Send" button. If the main page also had one, it would throw instead of guessing.
  4. The shadow root. getByLabel("Email for newsletter") and getByRole("button", { name: "Subscribe" }) reach straight into <newsletter-signup>'s open shadow root; nothing in the test mentions it. CSS selectors pierce too (newsletter-signup input matches), but the XPath for the same input matches nothing.
  5. The new tab. waitForEvent("popup") is started first, without await, then the click opens the tab, and awaiting the promise gives the new Page. Starting the wait after the click could miss a fast popup. On the new page, toHaveTitle waits for it to load; clicking the <summary> opens the <details>, and its answer becomes visible.
  6. The original page is untouched: both tabs belong to the same browser context (same localStorage), and the test can use either. When the new page isn't opened by this page (another tab opens it, say), context.waitForEvent("page") catches any new page in the context instead.
AdvancedPayment iframes and other origins

A cross-origin iframe (a Stripe or PayPal card form on your checkout) works the same way: frameLocator enters it regardless of origin, because Playwright drives the browser from outside rather than from inside the page. That's one of the practical differences from Cypress, which runs inside the page and needs extra commands for other origins (Chapter 1). Don't test the provider's form itself, though: use its test mode or mock it (Chapter 9).

Frames, shadow roots or neither?

Which of these needs frameLocator: (a) the "Subscribe" button, (b) the "Send" button, (c) the "Delete account" button?

Show answer

Only (b), the chat's "Send" button, because it's in an iframe. (a) is in a shadow root, which locators pierce automatically, and (c) is in the main document.

What’s happening
  1. An iframe is a separate document; locators on page never look inside one.
  2. An open shadow root is part of the same document, just encapsulated; Playwright's locators (except XPath) walk into it.
  3. If you're unsure, the aria snapshot of the main page shows an iframe entry with nothing inside it for (b), while (a)'s text box and button appear inline.

#Locators that break and locators that last

Added

A locator is a bet on what won't change. CSS paths bet on the markup's structure and class names. XPath bets on the exact tree of tags. Positions bet on order. Role and label locators bet on what users see, which changes only when the product changes. Test ids bet on a contract the team agreed to keep.

The best way to see the difference is to change the page. The test below runs the same "add the Wireless Mouse to the cart" step three ways, first against the real shop and then against a redesigned shop. The redesign is the kind of change a front-end developer makes on a normal Tuesday: product names become <h3> instead of <h2>, and each button is wrapped in a <div> for layout. Nothing a user can see changes. page.route (Chapter 9) serves the changed practice.js to the browser, so the real shop stays as it is.

tests/redesign.spec.ts
import { test, expect, type Page, type Locator } 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);
}

// A markup refactor users never notice: h2 → h3, and each button wrapped in a div.
async function redesign(page: Page) {
  await page.route("**/practice/practice.js", async (route) => {
    const response = await route.fetch();
    const js = (await response.text())
      .replace("`<h2>${esc(p.name)}</h2>", "`<h3>${esc(p.name)}</h3>")
      .replace('`<button type="button" data-add="${p.id}">Add to cart</button>`', '`<div class="buy"><button type="button" data-add="${p.id}">Add to cart</button></div>`');
    await route.fulfill({ response, body: js });
  });
}

const locators: Record<string, (page: Page) => Locator> = {
  "CSS path": (page) => page.locator("ul.products > li:nth-child(3) > button"),
  "XPath": (page) => page.locator("//li[h2='Wireless Mouse']/button"),
  "role + filter": (page) =>
    page.getByRole("listitem").filter({ has: page.getByRole("heading", { name: "Wireless Mouse" }) }).getByRole("button", { name: "Add to cart" }),
  "test id": (page) => page.getByTestId("product-ms-01").getByRole("button"),
};

for (const shop of ["today's shop", "redesigned shop"]) {
  test.describe(shop, () => {
    for (const [kind, find] of Object.entries(locators)) {
      test(kind, async ({ page }) => {
        if (shop === "redesigned shop") await redesign(page);
        await signIn(page);
        await find(page).click({ timeout: 3000 });
        await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible();
      });
    }
  });
}
npx playwright test
Running 8 tests using 1 worker

  ✓  1 [chromium] › tests/redesign.spec.ts:33:7 › today's shop › CSS path (1.8s)
  ✓  2 [chromium] › tests/redesign.spec.ts:33:7 › today's shop › XPath (1.8s)
  ✓  3 [chromium] › tests/redesign.spec.ts:33:7 › today's shop › role + filter (1.8s)
  ✓  4 [chromium] › tests/redesign.spec.ts:33:7 › today's shop › test id (1.8s)
  ✘  5 [chromium] › tests/redesign.spec.ts:33:7 › redesigned shop › CSS path (4.0s)
  ✘  6 [chromium] › tests/redesign.spec.ts:33:7 › redesigned shop › XPath (4.0s)
  ✓  7 [chromium] › tests/redesign.spec.ts:33:7 › redesigned shop › role + filter (1.8s)
  ✓  8 [chromium] › tests/redesign.spec.ts:33:7 › redesigned shop › test id (1.7s)


  1) [chromium] › tests/redesign.spec.ts:33:7 › redesigned shop › CSS path ─────────────────────────

    TimeoutError: locator.click: Timeout 3000ms exceeded.
    Call log:
      - waiting for locator('ul.products > li:nth-child(3) > button')


      34 |         if (shop === "redesigned shop") await redesign(page);
      35 |         await signIn(page);
    > 36 |         await find(page).click({ timeout: 3000 });
         |                          ^
      37 |         await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible();
      38 |       });
      39 |     }
        at <project>/tests/redesign.spec.ts:36:26

    Error Context: test-results/redesign-redesigned-shop-CSS-path-chromium/error-context.md

  2) [chromium] › tests/redesign.spec.ts:33:7 › redesigned shop › XPath ────────────────────────────

    TimeoutError: locator.click: Timeout 3000ms exceeded.
    Call log:
      - waiting for locator('//li[h2=\'Wireless Mouse\']/button')


      34 |         if (shop === "redesigned shop") await redesign(page);
      35 |         await signIn(page);
    > 36 |         await find(page).click({ timeout: 3000 });
         |                          ^
      37 |         await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible();
      38 |       });
      39 |     }
        at <project>/tests/redesign.spec.ts:36:26

    Error Context: test-results/redesign-redesigned-shop-XPath-chromium/error-context.md

  2 failed
    [chromium] › tests/redesign.spec.ts:33:7 › redesigned shop › CSS path ──────────────────────────
    [chromium] › tests/redesign.spec.ts:33:7 › redesigned shop › XPath ─────────────────────────────
  6 passed (19.7s)
What’s happening
  1. redesign intercepts the shop's script, fetches the real one, and changes two strings in the product card template before handing it to the browser. The shop then renders <h3> names and <div class="buy"><button>…</button></div>.
  2. The loops create 8 tests: the 4 locators against each shop. Each test adds one product and checks the header says "Cart (1)". The click has a 3-second timeout so a broken locator fails quickly.
  3. On today's shop, all four pass. Every locator looks fine on the day it's written, which is why brittle locators get merged.
  4. On the redesigned shop, the CSS path fails: li:nth-child(3) > button needs the button to be a direct child of the third item, and it's now inside a <div>. The XPath fails for two reasons: the name is no longer in an h2, and the button isn't a direct child. Both errors are "waiting for locator(…)" until the timeout: the element is there, the recipe just no longer describes it.
  5. The role locator passes: a heading is a heading whether it's h2 or h3, and getByRole("button") inside the card doesn't care how deep the button is. The test id passes too: nobody touched data-testid.
  6. Notice what the CSS path also bet on: position. Even without the wrapper, re-sorting the products would make it click a different product and still pass the "Cart (1)" check. Brittle locators fail in two ways: loudly on harmless refactors, and silently on real changes.
AdvancedTest ids as a contract

Test ids are the right answer when the user-facing text isn't stable or unique: user-generated content, translated UIs where the text changes per language, icons without labels, data cells. Treat them as an API:

  • Name them for what they are, not how they look: order-total, product-ms-01, not blue-box-2.
  • Put them on the stable container, then use roles inside: getByTestId("product-ms-01").getByRole("button") combines a contract for "which product" with a user-facing check for "the button".
  • Keep them out of the way of real users. Some teams strip data-testid in production builds; Playwright's testIdAttribute lets you pick any attribute name.
  • Don't let them replace accessibility. A button found only by test id might have no accessible name at all, and the test would never notice. Prefer roles, and use test ids where roles can't do the job.

#Your turn: locate it yourself

Added

These exercises use the live shop at rohit-playwright.pages.dev/practice/. Try each one in your own project (Chapter 2) before opening the answer.

Your turn: fix the strict-mode violation

This line fails on the shop page with "strict mode violation: getByRole('button', { name: 'Add to cart' }) resolved to 8 elements". Write a test that adds the Compact Keyboard instead, with no nth, first or last, and checks the cart has it.

await page.getByRole("button", { name: "Add to cart" }).click();

Show answer

Narrow by the product card first, then find the button inside it:

tests/strict-fix.spec.ts
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("ana");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page).toHaveURL(path);
}

test("adds the Compact Keyboard by its card, not its position", async ({ page }) => {
  await signIn(page);
  const card = page.getByRole("listitem").filter({ has: page.getByRole("heading", { name: "Compact Keyboard" }) });

  await card.getByRole("button", { name: "Add to cart" }).click();

  await page.getByRole("link", { name: "Cart (1)" }).click();
  await expect(page.getByRole("row", { name: /Compact Keyboard/ })).toBeVisible();
  await expect(page.getByTestId("cart-total")).toHaveText("$59.00");
});
npx playwright test
Running 1 test using 1 worker

  ✓  1 [chromium] › tests/strict-fix.spec.ts:11:1 › adds the Compact Keyboard by its card, not its position (1.8s)

  1 passed (2.3s)
What’s happening
  1. The original locator is fine as a description, it just describes eight buttons. Strictness turns that into a clear error instead of a silent click on the first one.
  2. filter({ has: getByRole("heading", { name: "Compact Keyboard" }) }) picks the one card containing that heading, and chaining getByRole("button", …) finds the button inside that card only.
  3. The check goes past "the click happened": the header link says "Cart (1)", the cart has a Compact Keyboard row, and the total is its price, $59.00.
  4. Re-sorting or adding products wouldn't change which card this finds, which is the difference from nth(1).
Your turn: read an order from the table

With the three past orders below in localStorage, write a test that checks ORD-1003 has 3 items and a total of $216.00, and that the table has exactly three orders. Find the row by its order id.

{ id: "ORD-1001", placedAt: Date.UTC(2026, 10, 2, 12), items: 2, total: 104.49 }, { id: "ORD-1002", placedAt: Date.UTC(2026, 10, 20, 12), items: 1, total: 29.5 }, { id: "ORD-1003", placedAt: Date.UTC(2026, 10, 23, 12), items: 3, total: 216 }

Show answer
tests/orders.spec.ts
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("ana");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page).toHaveURL(path);
}

test("ORD-1003 shows its items and total", async ({ page }) => {
  await page.addInitScript(() => {
    localStorage.setItem("shop-history", JSON.stringify([
      { id: "ORD-1001", placedAt: Date.UTC(2026, 10, 2, 12), items: 2, total: 104.49 },
      { id: "ORD-1002", placedAt: Date.UTC(2026, 10, 20, 12), items: 1, total: 29.5 },
      { id: "ORD-1003", placedAt: Date.UTC(2026, 10, 23, 12), items: 3, total: 216 },
    ]));
  });
  await signIn(page, "/practice/account");
  const table = page.getByRole("table", { name: "Your orders" });

  const order = table.getByRole("row").filter({ has: page.getByRole("rowheader", { name: "ORD-1003" }) });
  await expect(order.getByRole("cell")).toHaveText(["2026-11-23", "3", "$216.00"]);
  await expect(table.getByRole("rowheader")).toHaveCount(3);
});
npx playwright test
Running 1 test using 1 worker

  ✓  1 [chromium] › tests/orders.spec.ts:11:1 › ORD-1003 shows its items and total (996ms)

  1 passed (1.4s)
What’s happening
  1. addInitScript seeds the order history before the account page's script reads it, so the table has three rows.
  2. The row is found by its row header, ORD-1003, using filter({ has }). That's stricter than getByRole("row", { name: /ORD-1003/ }), which would also match a row that merely mentioned ORD-1003 in another cell.
  3. order.getByRole("cell") gives the three data cells (the order id is a row header, not a cell), and one array assertion checks the date, the item count and the total in order: 216 is shown as $216.00.
  4. Counting row headers in the table gives the number of orders, 3; the header row has column headers only, so it isn't counted.
Your turn: through the frame and the shadow root

Write one test on the account page that (1) sends "Hello" in the support chat and waits for the reply, and (2) tries to subscribe to the newsletter with rohit@ and checks the error.

Show answer
tests/frame-and-shadow.spec.ts
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("ana");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page).toHaveURL(path);
}

test("chat in the iframe, newsletter in the shadow root", async ({ page }) => {
  await signIn(page, "/practice/account");

  const chat = page.getByTitle("Support chat").contentFrame();
  await chat.getByPlaceholder("Type a message").fill("Hello");
  await chat.getByRole("button", { name: "Send" }).click();
  await expect(chat.getByRole("listitem")).toHaveText([/Hi! How can we help/, "You: Hello", /A human will reply/]);

  await page.getByLabel("Email for newsletter").fill("rohit@");
  await page.getByRole("button", { name: "Subscribe" }).click();
  await expect(page.getByRole("region", { name: "Newsletter" }).getByRole("status")).toHaveText("Enter a valid email.");
});
npx playwright test
Running 1 test using 1 worker

  ✓  1 [chromium] › tests/frame-and-shadow.spec.ts:11:1 › chat in the iframe, newsletter in the shadow root (2.4s)

  1 passed (2.8s)
What’s happening
  1. getByTitle("Support chat").contentFrame() enters the iframe; getByPlaceholder("Type a message") finds the message box by its placeholder (its label is visually hidden, so getByLabel("Message") would work too).
  2. After Send, the conversation has the greeting, your message, and, a second later, the reply. The array assertion waits for all three in order.
  3. The newsletter's field and button are in an open shadow root, so ordinary locators reach them. rohit@ fails the component's email check.
  4. The status message is also inside the shadow root. Scoping to the "Newsletter" region keeps it from matching the page's other status messages (there are three more on the account page), which would be a strict mode violation.

Written fresh, no doc. Tests were run with @playwright/test 1.65.1 (Chrome for Testing 159, Firefox 159, WebKit 27.2) against the Practice Shop at /practice/; facts come from playwright.dev, read 2026-11-24.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.