Playwright NotesRohit’s interview study guide
Chapter 03

How to Test: Thinking Like a Tester

How to decide what deserves an end-to-end test, how to turn a feature into a list of test cases, what a good test looks like, why tests must not depend on each other, what to assert, and a checklist for judging any test. The worked example is the Practice Shop's checkout, planned and then written as real tests that were run.

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

#What an end-to-end test is for

Added

Knowing Playwright's API is the easy half. The hard half, and what interviewers probe, is judgement: what to test, how much, and how to tell a test that protects you from one that only looks busy.

An end-to-end (E2E) test drives the whole running app the way a user does: a real browser, the real front end, the real API behind it. It answers one question nothing else can: can a person actually do this? Unit tests can prove that the total function adds tax correctly and that the cart component renders rows, and the checkout can still be broken because the button posts to the wrong URL, a CSS change put an invisible layer over it, or the API and the front end disagree about a field name. An E2E test catches those because it goes through every layer at once.

That reach has a cost. E2E tests are slow (seconds each, not milliseconds), they need the whole system running, they can fail for reasons that aren't bugs (a slow environment, shared data), and when one fails it tells you that something is wrong, not where. So the goal is a small number of E2E tests that cover what matters most, sitting on top of many cheaper tests that check the details.

The mental model: a fire drill. You don't test every smoke detector by running a fire drill; each detector has its own quick test. The drill checks that the whole building works together: alarms sound, doors open, people get out. A few drills, run regularly, on the routes people really use. That's what your E2E suite is.

You want to know…The cheapest test that can tell you
The total adds express delivery and rounds correctlya unit test of the pricing function
The email field rejects "rohit@"a unit test of the validator, or a component test of the form
POST /orders stores the order and returns its idan API (integration) test
The cart page shows a row per itema component test
A signed-in user can find a product, buy it and see a confirmationan E2E test: nothing smaller covers it

#Deciding what to test end to end

Added

You can't test every path through an app end to end, and you shouldn't try. Rank journeys by risk: how often they're used × how bad it is when they break. Start at the top and stop when the next test would mostly repeat what lower-level tests already cover.

Here's that ranking for the Practice Shop. Each row is a journey, something a user sets out to do, not a page or a component:

JourneyHow oftenCost if brokenE2E?
Sign inevery visitnobody can do anythingyes: the happy path and one failure
Find a product (search, filter)most visitscan't buy what you can't findyes: one search, one filter
Add to cart and see it in the cartmost visitslost salesyes
Check out and get a confirmationevery salelost sales, double charges, angry customersyes: the most important test in the suite
Change quantities, remove itemsoftenwrong totalsone test; the arithmetic goes in unit tests
Every checkout validation messagerarely seena confusing errorone test that errors are shown; each rule in unit tests
Sorting by price and namesometimesannoyingmaybe one smoke check, or a component test
A locked accountraresupport ticketsyes: cheap, and security-flavoured
The page title, footer, coloursalwayscosmeticno (a visual test, Chapter 10, if anything)

A few rules of thumb that hold on most teams:

  • Test journeys, not pages. "Buy a product" crosses four pages and is one test. "The cart page works" isn't something a user does.
  • The money path and the front door come first: sign-in, sign-up, checkout, payments, anything legal or security-related.
  • One E2E test per rule family, not per rule. One test proves the checkout shows validation errors and blocks the order. The twelve rules themselves (empty email, bad format, short address…) are a table-driven unit test that runs in milliseconds.
  • Where bugs have happened before. A production incident is the best argument for a new E2E test: add the test that would have caught it.
  • Don't test what you don't own. Don't drive Google's sign-in page or Stripe's checkout in your tests; mock them, or use their test modes, and test your side of the integration (Chapter 9).

#From a feature to test cases

Added

Once you know a journey deserves tests, turn it into a list of cases before writing any code. A reliable way is to walk through four kinds of case in order:

  1. The happy path: the main thing working, the way most users do it.
  2. The rules: each business rule that changes the outcome (express costs $9.99, the terms must be accepted).
  3. The edges: boundaries and unusual-but-valid inputs (one item vs many, the last item removed, a long address, a name with an accent).
  4. The failures: what happens when the user or the system gets it wrong (invalid email, nothing in the cart, the server is slow or down, you're not signed in).

Here's that walk for checkout in the Practice Shop, written the way you'd write it before coding: a case, what you do, what the user should see. Then the column that matters most: where each case should be tested.

#CaseDoExpectWhere
1Happy pathsign in, add a product, check out with standard delivery"Thank you, Rohit!", order ORD-1001, total equals the cart totalE2E
2Express deliverychoose Expresssummary shows $9.99 delivery; the confirmation total includes itE2E (it's the money)
3Terms not acceptedleave the box unticked, place order"You must agree to the terms."; still on checkoutE2E, as the one "errors block the order" test
4Invalid email formats"rohit@", "rohit.com", " " …the email errorunit test of the validator
5Name prefilledopen checkoutFull name is "Rohit"E2E check inside case 1 (cheap to add)
6Cart is cleared after orderingafter the confirmation, open the cart"Your cart is empty."E2E (it's state across pages)
7Empty cartopen /practice/checkout with nothing in the cartsent back to the cart pageE2E (a redirect, cheap)
8Not signed inopen /practice/checkout signed outsent to sign in, then back to checkoutE2E, in the sign-in tests
9Double click on Place orderclick twice fastone order, not twoE2E: the button must disable
10Server error placing the orderthe order API failsan error, cart keptE2E with a mocked failure (Chapter 9)
What’s happening
  1. The happy path (case 1) always comes first and is the test you'd keep if you could keep only one.
  2. The rules (2, 3) are where money and legal requirements live, so they earn E2E tests despite the cost.
  3. The edges split: case 5 rides along inside case 1 for free; case 9 needs its own test because double-submits are a classic real bug that only shows up in a browser.
  4. The failures split too: case 4 has many inputs and no wiring to prove, so it goes to a unit test, while cases 7, 8 and 10 are about what the whole app does, so they're E2E.
  5. Writing the "where" column is the point of the exercise. Without it, every case becomes an E2E test and the suite grows slow and fragile. With it, you get 7 or 8 focused E2E tests and a fast unit test for the long tail.

#The shape of a good test

Added

A good E2E test reads like a short story a product manager could follow: arrange (get to the starting point), act (do the one thing being tested), assert (check what the user sees). It tests one behaviour, its title names that behaviour, and it uses the page the way a user does: by labels, roles and visible text.

Here's the same check written twice. Both pass today. Only one of them is a good test:

tests/bad-and-good.spec.ts
import { test, expect } from "@playwright/test";

// ❌ What not to do: vague title, CSS selectors, a fixed sleep, several behaviours, weak checks.
test("test 1", async ({ page }) => {
  await page.goto("/practice/");
  await page.locator("#username").fill("rohit");
  await page.locator("#password").fill("playwright");
  await page.locator("form button").click();
  await page.waitForTimeout(2000);
  await page.locator(".product button").nth(2).click();
  await page.locator(".bar a.button").click();
  await page.locator("table button").nth(1).click();
  expect(await page.locator("td.num").count()).toBeGreaterThan(0);
});

// ✅ Better: named for the behaviour, arrange / act / assert, user-facing locators, web-first assertions.
test("increasing the quantity updates the subtotal and the total", async ({ page }) => {
  // Arrange: signed in, with one Wireless Mouse in the cart, on the cart page.
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).click();
  await page.getByRole("link", { name: "Cart (1)" }).click();

  // Act: one thing.
  await page.getByRole("button", { name: "Increase quantity of Wireless Mouse" }).click();

  // Assert: what the user sees.
  const row = page.getByRole("row", { name: /Wireless Mouse/ });
  await expect(page.getByLabel("Quantity of Wireless Mouse", { exact: true })).toHaveText("2");
  await expect(row.getByRole("cell").nth(2)).toHaveText("$59.00");
  await expect(page.getByTestId("cart-total")).toHaveText("$59.00");
});
npx playwright test
Running 2 tests using 1 worker

  ✓  1 [chromium] › tests/bad-and-good.spec.ts:4:1 › test 1 (2.3s)
  ✓  2 [chromium] › tests/bad-and-good.spec.ts:17:1 › increasing the quantity updates the subtotal and the total (1.5s)

  2 passed (4.2s)
What’s happening
  1. The title. "test 1" says nothing when it fails in CI. "increasing the quantity updates the subtotal and the total" tells you what broke before you open the file.
  2. The locators. #username, form button, .product button and nth(2) depend on IDs, CSS classes and the order of products: rename a class or re-sort the list and the bad test clicks the wrong thing (or nothing). The good test finds things the way a user does: the field labelled "Username", the button named "Sign in", the product card that says "Wireless Mouse".
  3. The sleep. waitForTimeout(2000) makes the bad test take at least 2 seconds and still fail on a machine where loading takes 2.1. The good test has no waits at all: its actions and assertions wait for exactly what they need.
  4. What's being tested. The bad test adds whatever the third product is, opens the cart, clicks the second button in the table (which happens to be "+" today) and checks that a number cell exists. It would pass if the quantity went to 7, if the total were wrong, even if the click removed the item and some other row stayed. The good test makes one change and checks the three numbers that change should produce.
  5. The numbers. The quantity has its own accessible label ("Quantity of Wireless Mouse"), so the test reads it directly, with exact: true: without it, label matching is a case-insensitive substring match, and "Decrease quantity of Wireless Mouse" and "Increase quantity of Wireless Mouse" match too. Playwright then refuses to guess (a "strict mode violation", Chapter 4) and the test fails, which is how this page's first draft of the test failed. The row's first cell is a header (the product name), so getByRole("cell") counts only the data cells: price nth(0), quantity nth(1), subtotal nth(2). One mouse is $29.50, so two must read $59.00, in the row and in the total.
  6. Both tests passed this time, which is the danger: a weak test looks exactly like a strong one until the day the feature breaks. The next sections show how to tell them apart before that day.
AdvancedLong arrange steps are a smell, not a rule-break

#Independent tests and test data

Added

Every test must be able to run alone, in any order, at the same time as any other test. Playwright gives each test a fresh browser context for exactly this reason, but you can still break it by writing a test that relies on something an earlier test did.

The classic mistake is splitting a journey into steps that pass work along:

tests/dependent.spec.ts
import { test, expect } from "@playwright/test";

// ❌ The second test only passes if the first one ran before it, in the same page. It can't.
let cartLink = "";

test("step 1: add the keyboard", async ({ page }) => {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await page.getByRole("button", { name: "Add to cart" }).first().click();
  cartLink = "/practice/cart";
});

test("step 2: the keyboard is in the cart", async ({ page }) => {
  await page.goto(cartLink || "/practice/cart");
  await expect(page.getByRole("row", { name: /Mechanical Keyboard/ })).toBeVisible({ timeout: 2000 });
});
npx playwright test
Running 2 tests using 1 worker

  ✓  1 [chromium] › tests/dependent.spec.ts:6:1 › step 1: add the keyboard (1.5s)
  ✘  2 [chromium] › tests/dependent.spec.ts:15:1 › step 2: the keyboard is in the cart (2.1s)


  1) [chromium] › tests/dependent.spec.ts:15:1 › step 2: the keyboard is in the cart ───────────────

    Error: expect(locator).toBeVisible() failed

    Locator: getByRole('row', { name: /Mechanical Keyboard/ })
    Expected: visible
    Timeout: 2000ms
    Error: element(s) not found

    Call log:
      - Expect "toBeVisible" getByRole('row', { name: /Mechanical Keyboard/ }) with timeout 2000ms
      - waiting for getByRole('row', { name: /Mechanical Keyboard/ })


      15 | test("step 2: the keyboard is in the cart", async ({ page }) => {
      16 |   await page.goto(cartLink || "/practice/cart");
    > 17 |   await expect(page.getByRole("row", { name: /Mechanical Keyboard/ })).toBeVisible({ timeout: 2000 });
         |                                                                        ^
      18 | });
      19 |
        at <project>/tests/dependent.spec.ts:17:72

    Error Context: test-results/dependent-step-2-the-keyboard-is-in-the-cart-chromium/error-context.md

  1 failed
    [chromium] › tests/dependent.spec.ts:15:1 › step 2: the keyboard is in the cart ────────────────
  1 passed (4.0s)
What’s happening
  1. Test 1 signs in and adds a keyboard, in its own browser context. It sets a module variable to remember the cart's address, as if handing over to the next test.
  2. When test 1 ends, its context closes. The signed-in user and the cart were in that context's localStorage, so they're gone.
  3. Test 2 gets a new, empty context. It opens the cart, the shop sees nobody signed in, and redirects to the sign-in page. The keyboard row never appears and the assertion fails after its 2-second timeout.
  4. The module variable did survive (both tests ran in the same worker process), which is what makes this pattern tempting. But with fullyParallel, --shuffle, sharding or --grep "step 2", test 2 runs without test 1 at all, so even that "works" only by accident.
  5. The fix is not to make test 2 wait for test 1. It's to make each test set up what it needs itself: test 2 signs in and adds the keyboard (or gets that state from a fixture, Chapter 7). Then each test can run alone and the order never matters.
AdvancedTest data on a real backend

The same rule applies to data on a real backend, where a fresh browser context doesn't help:

  • Each test creates its own data with unique names (order-${testInfo.workerIndex}-${Date.now()}, or a random id), usually through the API because it's faster than the UI (Chapter 9).
  • Never share one test account that tests change. Two tests changing the same user's address in parallel will fail at random. Give each worker its own account (Chapter 8 shows how), or make the shared account read-only.
  • Don't depend on data you didn't create, like "the first product in production is the keyboard". Seed it, or find it by what the test needs ("a product that's in stock").
  • Clean up if you must, but don't rely on it. A test that crashes halfway never runs its cleanup; tests that only pass when the last run cleaned up are order-dependent in disguise.

#What to assert, and what not to

Added

The assertion is where a test decides pass or fail, so it's where most weak tests are weak. Assert the outcome the user cares about, not a side effect that usually comes with it. And check your test can fail: a test that can't fail isn't testing anything.

Here's a way to see the difference. Two tests check "adding to the cart works". To find out whether they'd catch a real bug, the second pair of tests runs them against a broken shop: page.addInitScript makes the browser silently refuse to save the cart, so the "Added" message still appears but nothing is actually added. A good test must fail against the broken shop.

tests/what-to-assert.spec.ts
import { test, expect, type Page } from "@playwright/test";

async function signIn(page: Page) {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
}
// A bug on purpose: the cart is never saved, but the shop still says "Added".
async function breakTheCart(page: Page) {
  await page.addInitScript(() => {
    const setItem = Storage.prototype.setItem;
    Storage.prototype.setItem = function (key, value) {
      if (key !== "shop-cart") setItem.call(this, key, value);
    };
  });
}
async function weakCheck(page: Page) {
  await page.getByRole("button", { name: "Add to cart" }).first().click();
  await expect(page.getByRole("status").filter({ hasText: "Added" })).toBeVisible();
}
async function strongCheck(page: Page) {
  await page.getByRole("button", { name: "Add to cart" }).first().click();
  await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible({ timeout: 2000 });
  await page.getByRole("link", { name: /Cart/ }).click();
  await expect(page.getByRole("row", { name: /Mechanical Keyboard/ })).toBeVisible({ timeout: 2000 });
}

test("weak: checks the message", async ({ page }) => { await signIn(page); await weakCheck(page); });
test("strong: checks the cart", async ({ page }) => { await signIn(page); await strongCheck(page); });
test("weak, on the broken shop", async ({ page }) => { await breakTheCart(page); await signIn(page); await weakCheck(page); });
test("strong, on the broken shop", async ({ page }) => { await breakTheCart(page); await signIn(page); await strongCheck(page); });
npx playwright test
Running 4 tests using 1 worker

  ✓  1 [chromium] › tests/what-to-assert.spec.ts:29:1 › weak: checks the message (1.5s)
  ✓  2 [chromium] › tests/what-to-assert.spec.ts:30:1 › strong: checks the cart (1.5s)
  ✓  3 [chromium] › tests/what-to-assert.spec.ts:31:1 › weak, on the broken shop (1.4s)
  ✘  4 [chromium] › tests/what-to-assert.spec.ts:32:1 › strong, on the broken shop (3.5s)


  1) [chromium] › tests/what-to-assert.spec.ts:32:1 › strong, on the broken shop ───────────────────

    Error: expect(locator).toBeVisible() failed

    Locator: getByRole('link', { name: 'Cart (1)' })
    Expected: visible
    Timeout: 2000ms
    Error: element(s) not found

    Call log:
      - Expect "toBeVisible" getByRole('link', { name: 'Cart (1)' }) with timeout 2000ms
      - waiting for getByRole('link', { name: 'Cart (1)' })


      22 | async function strongCheck(page: Page) {
      23 |   await page.getByRole("button", { name: "Add to cart" }).first().click();
    > 24 |   await expect(page.getByRole("link", { name: "Cart (1)" })).toBeVisible({ timeout: 2000 });
         |                                                              ^
      25 |   await page.getByRole("link", { name: /Cart/ }).click();
      26 |   await expect(page.getByRole("row", { name: /Mechanical Keyboard/ })).toBeVisible({ timeout: 2000 });
      27 | }
        at strongCheck (<project>/tests/what-to-assert.spec.ts:24:62)
        at <project>/tests/what-to-assert.spec.ts:32:104

    Error Context: test-results/what-to-assert-strong-on-the-broken-shop-chromium/error-context.md

  1 failed
    [chromium] › tests/what-to-assert.spec.ts:32:1 › strong, on the broken shop ────────────────────
  3 passed (8.4s)
What’s happening
  1. On the real shop, both checks pass. From the outside, the weak test and the strong test look equally good.
  2. breakTheCart uses page.addInitScript, which runs a script in every page of this test before the page's own scripts. It replaces localStorage.setItem with a version that quietly ignores the shop-cart key. Sign-in still works (that's shop-user), the "Added" message still shows, but the cart is never saved.
  3. The weak test passes on the broken shop. It only checked the message, and the message is a side effect of clicking, not proof that anything went into the cart. In real life, this test stays green while customers' carts stay empty.
  4. The strong test fails on the broken shop, at the first thing that matters: the cart link still says "Cart (0)", so "Cart (1)" never appears. It checks the outcome: the link's count, then the row in the cart.
  5. This trick, breaking the feature on purpose and making sure your test notices, is called mutation testing when tools do it to your code automatically. You can do a quick manual version whenever you write a test: comment out the line that does the work, or break it like this, and watch the test go red. If it stays green, the test is checking the wrong thing.
AdvancedWhat to assert, in practice

What to assert, in practice:

  • The result, not the activity. "The order confirmation shows ORD-1001 and $68.99", not "the Place order button was clicked" or "a spinner appeared".
  • What the user can see, through the page: text, counts, URLs, enabled or disabled controls. Avoid reading internal state (localStorage, Redux stores, component props) unless that state is the feature.
  • Enough to catch the bug you care about, and no more. Asserting every word on the page makes a test break on every copy change. Pick the facts that prove the behaviour.
  • Exact values when they matter (toHaveText("$59.00")) and patterns when they don't (toHaveText(/Thank you/)).
  • Both sides of a change when it's cheap: after removing an item, the row is gone and the total changed.
  • No assertions inside if. A test that checks something only when a condition is true will quietly check nothing when it isn't.

#Writing the checkout tests, step by step

Added

Now the plan from "From a feature to test cases", turned into code. These are cases 1, 2, 3, 6, 7 and 9, the ones marked E2E. Case 8 belongs with the sign-in tests and case 10 needs network mocking (Chapter 9). Each test arranges its own state, does one thing and checks what the user sees.

tests/checkout.spec.ts
import { test, expect, type Page } from "@playwright/test";

// Plumbing shared by every test here: sign in and put products in the cart.
// (Chapter 7 turns this into a fixture.)
async function signInWithCart(page: Page, ...products: string[]) {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("rohit");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  for (const name of products) {
    await page.getByRole("listitem").filter({ hasText: name }).getByRole("button", { name: "Add to cart" }).click();
  }
  await expect(page.getByRole("link", { name: `Cart (${products.length})` })).toBeVisible();
}
async function fillDetails(page: Page) {
  await page.getByLabel("Email").fill("rohit@example.com");
  await page.getByLabel("Delivery address").fill("12 Long Street, Toronto");
  await page.getByLabel("I agree to the terms").check();
}

test("case 1: a signed-in user can buy a product and sees a confirmation", async ({ page }) => {
  await signInWithCart(page, "Wireless Mouse");
  await page.goto("/practice/checkout");
  await expect(page.getByLabel("Full name")).toHaveValue("Rohit");
  await fillDetails(page);

  await page.getByRole("button", { name: "Place order" }).click();

  await expect(page.getByRole("heading", { level: 1 })).toHaveText("Thank you, Rohit!");
  await expect(page.getByText("Your order ORD-1001 is confirmed.")).toBeVisible();
  await expect(page.getByText("Total paid on delivery: $29.50")).toBeVisible();
});

test("case 2: express delivery adds $9.99 to the total", async ({ page }) => {
  await signInWithCart(page, "Wireless Mouse", "Monitor Light Bar");
  await page.goto("/practice/checkout");
  await expect(page.getByTestId("order-total")).toHaveText("$78.50");

  await page.getByLabel("Express").check();

  await expect(page.getByTestId("order-total")).toHaveText("$88.49");
  await fillDetails(page);
  await page.getByRole("button", { name: "Place order" }).click();
  await expect(page.getByText("Total paid on delivery: $88.49")).toBeVisible();
});

test("case 3: an order can't be placed without accepting the terms", async ({ page }) => {
  await signInWithCart(page, "USB Microphone");
  await page.goto("/practice/checkout");
  await page.getByLabel("Email").fill("rohit@example.com");
  await page.getByLabel("Delivery address").fill("12 Long Street, Toronto");

  await page.getByRole("button", { name: "Place order" }).click();

  await expect(page.getByText("You must agree to the terms.")).toBeVisible();
  await expect(page.getByRole("alert")).toHaveText("Please fix 1 problem before placing your order.");
  await expect(page).toHaveURL("/practice/checkout");
});

test("case 6: the cart is empty after ordering", async ({ page }) => {
  await signInWithCart(page, "Standing Desk Mat");
  await page.goto("/practice/checkout");
  await fillDetails(page);
  await page.getByRole("button", { name: "Place order" }).click();
  await expect(page.getByRole("heading", { level: 1 })).toHaveText("Thank you, Rohit!");

  await page.getByRole("link", { name: "Cart (0)" }).click();

  await expect(page.getByText("Your cart is empty.")).toBeVisible();
});

test("case 7: checkout with an empty cart goes back to the cart", async ({ page }) => {
  await signInWithCart(page);

  await page.goto("/practice/checkout");

  await expect(page).toHaveURL("/practice/cart");
  await expect(page.getByText("Your cart is empty.")).toBeVisible();
});

test("case 9: clicking Place order twice places one order", async ({ page }) => {
  await signInWithCart(page, "Compact Keyboard");
  await page.goto("/practice/checkout");
  await fillDetails(page);
  const placeOrder = page.getByRole("button", { name: "Place order" });

  await placeOrder.click();

  await expect(page.getByRole("button", { name: "Placing order…" })).toBeDisabled();
  await expect(page.getByText("Your order ORD-1001 is confirmed.")).toBeVisible();
  expect(await page.evaluate(() => localStorage.getItem("shop-orders"))).toBe("1001");
});
npx playwright test
Running 6 tests using 1 worker

  ✓  1 [chromium] › tests/checkout.spec.ts:21:1 › case 1: a signed-in user can buy a product and sees a confirmation (2.9s)
  ✓  2 [chromium] › tests/checkout.spec.ts:34:1 › case 2: express delivery adds $9.99 to the total (2.9s)
  ✓  3 [chromium] › tests/checkout.spec.ts:47:1 › case 3: an order can't be placed without accepting the terms (1.5s)
  ✓  4 [chromium] › tests/checkout.spec.ts:60:1 › case 6: the cart is empty after ordering (2.9s)
  ✓  5 [chromium] › tests/checkout.spec.ts:72:1 › case 7: checkout with an empty cart goes back to the cart (955ms)
  ✓  6 [chromium] › tests/checkout.spec.ts:81:1 › case 9: clicking Place order twice places one order (2.8s)

  6 passed (14.3s)
What’s happening
  1. signInWithCart and fillDetails are the arrange plumbing: each test calls them, so each test can run alone, in any order. signInWithCart(page) with no products (case 7) is just "signed in, empty cart". Its last line waits for the cart link to show the right count, so a test never moves on before the cart is saved.
  2. Case 1 is the happy path. It also checks the prefilled name (case 5 from the plan, nearly free) and then the three facts that prove the order went through: the thank-you heading, the order number and the amount.
  3. Case 2 checks the money twice: the summary before and after choosing Express ($29.50 + $49.00 = $78.50, then + $9.99 = $88.49), and the confirmation's total, because a summary that's right and an order that's charged wrong is exactly the bug that matters.
  4. Case 3 is the one "errors block the order" test: the field error, the summary alert, and the URL proving no order was placed. Every other validation rule is left to unit tests, as planned.
  5. Case 6 crosses pages: after ordering, the header's cart link says "Cart (0)", and the cart page says it's empty. It catches a whole class of bug (state not cleared after an action) that no single-page test can.
  6. Case 9 needs care. A second real click can't land, because the button disables itself straight away, and Playwright would wait for it to be enabled again. So the test checks the reason a double order can't happen: right after the click, the button reads "Placing order…" and is disabled. It then checks the outcome: the counter in storage is 1001, one order. Reading localStorage is the exception to "assert what the user sees": it's the simplest honest way to count orders in an app with no server.
  7. The six run one after another in a single worker (one file, and this suite's config doesn't set fullyParallel), yet each gets ORD-1001, because each has its own context and so its own order counter. That's isolation paying off: no test can change another's order number, and turning on fullyParallel wouldn't change a result.
AdvancedWrite the plan into the test names

#Reviewing a test: a checklist

Added

Use this on your own tests before you commit them, and on other people's in code review. It's also a good structure for an interview question like "what makes a good E2E test?"

  1. Would it fail if the feature broke? Break the feature on purpose (comment out a line, or addInitScript as above) and watch it go red. If it stays green, the assertions are checking the wrong thing.
  2. Would it pass if the feature worked? No hidden dependence on another test, the time of day, test order, the screen size, or data someone else created.
  3. Does it say what it tests? The title is the behaviour; the body reads as arrange, act, assert.
  4. Does it find things like a user? Roles, labels and text first; test ids where there's nothing user-facing; no CSS paths or nth on lists whose order isn't the point (Chapter 4).
  5. Does it wait the right way? No waitForTimeout. Assertions are await expect(locator)…, not expect(await locator.something()) (Chapter 6).
  6. Is it the right level? Could a unit or API test catch the same bug faster? Then it probably belongs there.
  7. Is it one behaviour? If the title needs "and" twice, it might be two tests. (One behaviour can still need several assertions, like case 1.)
  8. Will it run in parallel? Its own data, its own user or a read-only shared one, no global state.
  9. When it fails, will the failure explain itself? A clear title, specific assertions (toHaveText("$59.00"), not toBeTruthy()), and traces on retry in the config.
  10. Is it fast enough? Plumbing (signing in, creating data) through saved state or the API, not the UI, once there's more than a handful of tests (Chapters 8 and 9).

#Your turn: plan and test the cart

Added
Your turn: plan the cart page

Using the four kinds of case (happy path, rules, edges, failures), list cases for the cart page and decide which are E2E. Try it before you open the answer.

Show answer

One reasonable plan (yours can differ; what matters is that every case has a "where" and a reason):

CaseExpectWhere
Happy path: two different products addedtwo rows, total is the sumE2E
Rule: + raises quantity and subtotalquantity 2, subtotal doubles, total updatesE2E (one test)
Rule: − to zero removes the rowrow gone, total updatesE2E
Edge: removing the last item"Your cart is empty." and a "Browse products" linkE2E
Edge: prices with cents ($74.99 × 3)$224.97, no rounding errorunit test of the total
Edge: the cart survives a reloadsame rows after page.reload()E2E (it's storage)
Failure: not signed insent to sign in, back to the cart afterE2E, with the sign-in tests
What’s happening
  1. The happy path checks the page shows what was added, with the right total.
  2. The two rules (+ and −) are the page's whole job, so each gets a short E2E test; the arithmetic for every price combination goes to a unit test.
  3. The edges are where carts really break: emptying it, money with cents, a reload. Only the money rounding is better as a unit test, because it's pure logic with many inputs.
  4. "Not signed in" is true of every page, so it's tested once, with sign-in, rather than on each page.
Your turn: write two of them

Write the "removing the last item" test and the "cart survives a reload" test. Each must arrange its own state.

Show answer
tests/cart.spec.ts
import { test, expect, type Page } from "@playwright/test";

async function signInWithCart(page: Page, ...products: string[]) {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("ana");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  for (const name of products) {
    await page.getByRole("listitem").filter({ hasText: name }).getByRole("button", { name: "Add to cart" }).click();
  }
  await page.getByRole("link", { name: `Cart (${products.length})` }).click();
}

test("removing the last item shows the empty cart", async ({ page }) => {
  await signInWithCart(page, "USB Microphone");

  await page.getByRole("button", { name: "Remove USB Microphone" }).click();

  await expect(page.getByText("Your cart is empty.")).toBeVisible();
  await expect(page.getByRole("link", { name: "Browse products" })).toBeVisible();
  await expect(page.getByRole("link", { name: "Cart (0)" })).toBeVisible();
});

test("the cart survives a reload", async ({ page }) => {
  await signInWithCart(page, "Compact Keyboard", "Monitor Light Bar");

  await page.reload();

  await expect(page.getByRole("row", { name: /Compact Keyboard/ })).toBeVisible();
  await expect(page.getByRole("row", { name: /Monitor Light Bar/ })).toBeVisible();
  await expect(page.getByTestId("cart-total")).toHaveText("$108.00");
});
npx playwright test
Running 2 tests using 1 worker

  ✓  1 [chromium] › tests/cart.spec.ts:14:1 › removing the last item shows the empty cart (1.6s)
  ✓  2 [chromium] › tests/cart.spec.ts:24:1 › the cart survives a reload (1.5s)

  2 passed (3.6s)
What’s happening
  1. Both tests use the same arrange helper, which signs in as Ana, adds the products, and opens the cart by clicking the header link, so it also proves the count was right.
  2. The first test removes the only item, then checks three facts: the empty message, the link back to the shop, and the header count of 0. Checking only the message would miss a header that still said "Cart (1)".
  3. The second test reloads the page. If the cart lived only in memory, the rows would vanish; because the shop keeps it in localStorage (in this test's context), both rows and the $108.00 total ($59.00 + $49.00) come back.
  4. Neither test depends on the other or on any earlier test: run either alone with npx playwright test -g "reload" and it passes.

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.