Playwright NotesRohit’s interview study guide
Chapter 09

Network: Mocking and API Testing

How to intercept the requests a page makes and answer them yourself with page.route (fake, change or block them), how to use that to test the error and edge cases a real backend won't produce on demand, how to record real traffic into a HAR file and replay it, how to test an API directly with the request fixture, and how to watch the requests, responses and console messages a page produces. Every test was run with Playwright 1.65.1 against the Practice Shop.

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

#Intercepting requests with page.route

Added

Every request a page makes (the HTML, scripts, images, fetch calls to your API) passes through Playwright on its way out, and page.route(pattern, handler) lets you stop the matching ones and decide what happens. The handler gets a route and must do exactly one of:

  • route.fulfill({...}): answer it yourself; the request never reaches the server. json, body, status, headers and contentType shape the fake response.
  • route.continue({...}): let it go to the server, optionally changed (url, method, headers, postData).
  • route.fetch() then route.fulfill({ response, … }): send it to the server, get the real response, then change it before the page sees it.
  • route.abort(): fail it, as if the network were down.
  • route.fallback(): pass it on to the next matching handler (handlers registered later are tried first).

The mental model: a mailroom between the page and the internet. Every outgoing letter goes through it. For the addresses you've told it about, the mailroom can write the reply itself, edit the letter or the reply, or throw the letter away. Everything else goes out untouched.

Here are the main moves against the shop's product list, GET /practice/api/products.json:

tests/route.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();
}

test("fulfil: answer with fake data", async ({ page }) => {
  await page.route("**/practice/api/products.json", (route) =>
    route.fulfill({ json: [
      { id: "t-1", name: "Test Teapot", category: "Kitchen", price: 12, stock: 3 },
      { id: "t-2", name: "Test Toaster", category: "Kitchen", price: 30, stock: 0 },
    ] }),
  );
  await signIn(page);

  await expect(page.getByRole("listitem")).toHaveText([/Test Teapot/, /Test Toaster/]);
  await expect(page.getByTestId("product-t-2").getByRole("button", { name: "Add to cart" })).toBeDisabled();
});

test("modify: change the real response", async ({ page }) => {
  await page.route("**/practice/api/products.json", async (route) => {
    const response = await route.fetch();
    const products = await response.json();
    for (const p of products) p.price = Math.round(p.price * 0.5 * 100) / 100; // a half-price sale
    await route.fulfill({ response, json: products });
  });
  await signIn(page);

  await expect(page.getByTestId("product-ms-01")).toContainText("$14.75");
  await expect(page.getByRole("listitem")).toHaveCount(8);
});

test("abort: the request fails", async ({ page }) => {
  await page.route("**/practice/api/products.json", (route) => route.abort());
  await signIn(page);

  await expect(page.getByRole("alert")).toHaveText("Couldn’t load products. Try again later.");
});
npx playwright test
Running 3 tests using 1 worker

  ✓  1 [chromium] › tests/route.spec.ts:10:1 › fulfil: answer with fake data (1.6s)
  ✓  2 [chromium] › tests/route.spec.ts:23:1 › modify: change the real response (1.5s)
  ✓  3 [chromium] › tests/route.spec.ts:36:1 › abort: the request fails (1.5s)

  3 passed (5.3s)
What’s happening
  1. Each test registers its route before signing in, because signing in lands on the shop page, which immediately requests the products. A route added after the request has gone out is too late.
  2. Fulfil: the handler answers with two made-up products; the request never reaches the server. json serialises the value and sets Content-Type: application/json. The page renders exactly the fake list, and the sold-out toaster's button is disabled, a state you can now test with any data you like.
  3. Modify: route.fetch() sends the request to the real server and returns the real response. The handler halves every price and fulfils with response (keeping its status and headers) plus the changed json. The mouse now shows $14.75 instead of $29.50, and all eight real products are still there.
  4. Abort: route.abort() fails the request like a dropped connection. The shop's fetch rejects, its catch runs, and it shows "Couldn’t load products. Try again later." in a role="alert" element, which is what the test checks.
  5. Routes belong to the test's page (or context, with context.route) and disappear when the test ends, so nothing leaks into other tests.
AdvancedGlob patterns: what matches what

The first argument is a glob (or a RegExp, or a function of the URL). The glob must match the whole URL, not part of it, which is why patterns start with **/. The rules, from the docs:

Pattern partMatches
*any characters except /
**any characters including /
{a,b}either a or b
?only a literal ? (since 1.52; before, it meant "any one character")
\escapes a special character

Since 1.52, ? and [] have no special meaning in globs; use a RegExp if you need them. This test shows * stopping at /:

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

test("which requests does **/api/*.json catch?", async ({ page }) => {
  const caught: string[] = [];
  await page.route("**/api/*.json", async (route) => {
    caught.push(new URL(route.request().url()).pathname);
    await route.continue();
  });

  await page.goto("/practice/");
  await page.localStorage.setItem("shop-user", JSON.stringify({ username: "rohit", name: "Rohit" }));
  await page.localStorage.setItem("shop-cart", JSON.stringify([{ id: "ms-01", name: "Wireless Mouse", price: 29.5, qty: 1 }]));
  await page.goto("/practice/shop");
  await expect(page.getByRole("listitem")).toHaveCount(8);
  await page.goto("/practice/checkout");
  await page.getByLabel("Promo code").fill("SAVE10");
  await page.getByRole("button", { name: "Apply" }).click();
  await expect(page.getByText("SAVE10 applied: 10% off.")).toBeVisible();

  console.log(caught);
});
npx playwright test
Running 1 test using 1 worker

[ '/practice/api/products.json' ]
  ✓  1 [chromium] › tests/globs.spec.ts:3:1 › which requests does **/api/*.json catch? (1.2s)

  1 passed (1.9s)
What’s happening
  1. The handler records each URL it catches, then lets it through unchanged with route.continue(), so the page works normally.
  2. The test seeds a signed-in user and a cart with page.localStorage (Chapter 8) so it can go straight to the shop and the checkout, where it applies the code SAVE10.
  3. The page made two API calls: /practice/api/products.json and /practice/api/promos/SAVE10.json. Only the first was caught. In **/api/*.json, the * can't cross the / in promos/SAVE10, so the promo request didn't match and went straight to the server.
  4. **/api/**/*.json or **/api/** would catch both. Getting a glob slightly wrong is the commonest reason a mock "does nothing": the request simply doesn't match, and the real server answers. When a mock seems ignored, log what the page requests (see "Watching what the page sends").

#Mocking an API for a UI test

Added

The best use of page.route is testing what the UI does when the backend misbehaves: an empty list, a server error, a slow response, an odd value. A real backend can't be made to do those on demand, at least not reliably or quickly, so these states usually go untested, and they're exactly where real bugs hide. With a mock, each is a three-line arrange step.

The mental model: a stunt double for the backend. The real backend plays the normal scenes (most of your tests); the stunt double does the dangerous ones (errors, timeouts, empty data) on cue, every time, the same way.

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

const PRODUCTS = "**/practice/api/products.json";

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();
}

test("a server error shows a message instead of products", async ({ page }) => {
  await page.route(PRODUCTS, (route) => route.fulfill({ status: 500, body: "Internal Server Error" }));
  await signIn(page);

  await expect(page.getByRole("alert")).toHaveText("Couldn’t load products. Try again later.");
  await expect(page.getByRole("listitem")).toHaveCount(0);
});

test("a slow response shows the loading message until the data arrives", async ({ page }) => {
  let release!: () => void;
  const held = new Promise<void>((resolve) => (release = resolve));
  await page.route(PRODUCTS, async (route) => {
    await held; // keep the request waiting until the test says so
    await route.continue();
  });
  await signIn(page);

  await expect(page.getByText("Loading products…")).toBeVisible();
  await expect(page.getByRole("listitem")).toHaveCount(0);

  release();

  await expect(page.getByRole("listitem")).toHaveCount(8);
  await expect(page.getByText("Loading products…")).toBeHidden();
});

test("an empty catalogue shows no products", async ({ page }) => {
  await page.route(PRODUCTS, (route) => route.fulfill({ json: [] }));
  await signIn(page);

  await expect(page.getByRole("listitem")).toHaveCount(0);
  // What the shop really says today: a search message with nothing searched. See below.
  await expect(page.getByText("No products match “”.")).toBeVisible();
});
npx playwright test
Running 3 tests using 1 worker

  ✓  1 [chromium] › tests/products-mocks.spec.ts:12:1 › a server error shows a message instead of products (1.6s)
  ✓  2 [chromium] › tests/products-mocks.spec.ts:20:1 › a slow response shows the loading message until the data arrives (1.8s)
  ✓  3 [chromium] › tests/products-mocks.spec.ts:38:1 › an empty catalogue shows no products (1.5s)

  3 passed (5.6s)
What’s happening
  1. Server error: the route fulfils with status 500. The shop checks res.ok, throws, and shows its alert; the list stays empty. Without a mock, you'd need a way to make the real server fail on cue, which most teams don't have.
  2. Slow response, without guessing a delay: the handler waits on a promise that only the test can resolve (release()). While it's held, the test checks the loading message and the empty list; then it releases the request, route.continue() sends it to the real server, and the products appear and the message goes. No setTimeout, no race: the test controls exactly when the response arrives.
  3. Empty catalogue: the route returns []. No products are listed, but the message is "No products match “”.": the shop reuses its search message, with an empty search term. The mock found a real (small) bug: nobody had ever seen this state, because the real catalogue is never empty.
  4. That third test pins down today's text so the page matches what really happens; on a real team you'd file the bug, and when it's fixed (say, "No products yet."), the test changes with it. Finding states like this is the main reason to mock.
  5. All three tests use the real shop page, real JavaScript and real rendering; only one response is faked. That's the sweet spot: everything you own is real, only the dependency's behaviour is chosen.
AdvancedMocking the promo-code API

The checkout checks promo codes with GET /practice/api/promos/<CODE>.json: 200 with { code, percent } applies it, 404 means "That code isn’t valid.", and any other failure means "Couldn’t check the code. Try again." Only the first two happen against the real server, and only for codes that exist. Mocks cover the rest:

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

async function openCheckout(page: Page) {
  await page.goto("/practice/");
  await page.localStorage.setItem("shop-user", JSON.stringify({ username: "rohit", name: "Rohit" }));
  await page.localStorage.setItem("shop-cart", JSON.stringify([{ id: "au-01", name: "Noise-Cancelling Headphones", price: 199, qty: 1 }]));
  await page.goto("/practice/checkout");
}
async function apply(page: Page, code: string) {
  await page.getByLabel("Promo code").fill(code);
  await page.getByRole("button", { name: "Apply" }).click();
}

test("an unknown code is rejected (real 404)", async ({ page }) => {
  await openCheckout(page);
  await apply(page, "NOPE");
  await expect(page.getByText("That code isn’t valid.")).toBeVisible();
  await expect(page.getByTestId("order-total")).toHaveText("$199.00");
});

test("a server error asks you to try again", async ({ page }) => {
  await page.route("**/practice/api/promos/*.json", (route) => route.fulfill({ status: 500 }));
  await openCheckout(page);
  await apply(page, "SAVE10");
  await expect(page.getByText("Couldn’t check the code. Try again.")).toBeVisible();
  await expect(page.getByTestId("order-total")).toHaveText("$199.00");
});

test("a network failure asks you to try again", async ({ page }) => {
  await page.route("**/practice/api/promos/*.json", (route) => route.abort("internetdisconnected"));
  await openCheckout(page);
  await apply(page, "SAVE10");
  await expect(page.getByText("Couldn’t check the code. Try again.")).toBeVisible();
});

test("a code the server doesn't have yet can be tested before it exists", async ({ page }) => {
  await page.route("**/practice/api/promos/SPRING25.json", (route) => route.fulfill({ json: { code: "SPRING25", percent: 25 } }));
  await openCheckout(page);
  await apply(page, "spring25");
  await expect(page.getByText("SPRING25 applied: 25% off.")).toBeVisible();
  await expect(page.getByText("Discount (SPRING25, 25%)")).toBeVisible();
  await expect(page.getByTestId("order-total")).toHaveText("$149.25");
});
npx playwright test
Running 4 tests using 1 worker

  ✓  1 [chromium] › tests/promo-mocks.spec.ts:14:1 › an unknown code is rejected (real 404) (254ms)
  ✓  2 [chromium] › tests/promo-mocks.spec.ts:21:1 › a server error asks you to try again (190ms)
  ✓  3 [chromium] › tests/promo-mocks.spec.ts:29:1 › a network failure asks you to try again (191ms)
  ✓  4 [chromium] › tests/promo-mocks.spec.ts:36:1 › a code the server doesn't have yet can be tested before it exists (259ms)

  4 passed (1.4s)
What’s happening
  1. openCheckout seeds a signed-in rohit with the $199 headphones in the cart through page.localStorage, then opens the checkout. apply types a code and clicks Apply.
  2. The unknown code needs no mock: the real server returns 404 for NOPE.json, and the shop says "That code isn’t valid." The total stays $199.00. Mock only what the real system can't do.
  3. The server error fulfils every promo request with a bare 500. The shop's !res.ok branch throws, its catch shows "Couldn’t check the code. Try again.", and no discount is applied.
  4. The network failure uses route.abort("internetdisconnected"), one of the error codes abort accepts. fetch rejects instead of returning a response, which reaches the same catch from a different path; both paths are worth a test, because apps often handle one and forget the other.
  5. The future code: the mock serves SPRING25 at 25%, a code the backend doesn't have yet, so the front end can be tested before the backend ships it. The shop upper-cases the input (spring25 → SPRING25.json), and $199 × 0.75 = $149.25.

#Recording and replaying with HAR

Added

Writing mocks by hand is fine for one endpoint. For a page that makes twenty calls, record them: a HAR file (HTTP Archive, a standard JSON format browsers' devtools also export) holds every request and response. page.routeFromHAR(file, { update: true }) records the real traffic into it; without update, it replays the file, answering matching requests from it instead of the network.

The mental model: a tape recorder. Record a real conversation with the backend once, then play the tape in later runs: the same answers, every time, with no backend needed. You can also edit the tape to create a scenario.

Here a test records the shop's API calls (the url option limits it to **/api/**; the page, scripts and styles still come from the server):

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

test("record the API calls", async ({ page }) => {
  await page.routeFromHAR("hars/shop.har", { url: "**/api/**", update: true });
  await page.goto("/practice/");
  await page.localStorage.setItem("shop-user", JSON.stringify({ username: "rohit", name: "Rohit" }));
  await page.goto("/practice/shop");
  await expect(page.getByRole("listitem")).toHaveCount(8);
});
npx playwright test tests/record.spec.ts
Running 1 test using 1 worker

  ✓  1 [chromium] › tests/record.spec.ts:3:1 › record the API calls (901ms)

  1 passed (1.4s)
What’s happening
  1. update: true means "don't serve from the file; send requests to the network and write what happens into hars/shop.har". The file is written when the test's context closes.
  2. url: "**/api/**" limits recording (and later replay) to the API. Without it, every request (HTML, CSS, JavaScript) would be recorded and later served from the file too.
  3. The test itself is an ordinary test: sign in through storage, open the shop, see eight products. It passes against the real server, and its side effect is the HAR file.
AdvancedWhat a HAR file holds

A short script prints a summary of the recorded file (the full file also has every header, timings and dates, which change on each run):

show-har.mjs
import { readdirSync, readFileSync } from "node:fs";

console.log("files:", readdirSync("hars"));
const har = JSON.parse(readFileSync("hars/shop.har", "utf8"));
console.log("creator:", har.log.creator.name, har.log.creator.version);
for (const { request, response } of har.log.entries) {
  console.log(request.method, request.url, "→", response.status, response.content.mimeType);
  console.log("  content-type header:", response.headers.find((h) => h.name.toLowerCase() === "content-type").value);
  console.log("  body saved in:", response.content._file);
  const body = JSON.parse(readFileSync(`hars/${response.content._file}`, "utf8"));
  console.log("  body:", body.length, "products, first:", body[0].name, body[0].price);
}
node show-har.mjs
files: [ '3c22b1441fe934c4669b8d2fcc42d6df7fae4c3e.json', 'shop.har' ]
creator: Playwright 1.65.1
GET https://rohit-playwright.pages.dev/practice/api/products.json → 200 application/json
  content-type header: application/json
  body saved in: 3c22b1441fe934c4669b8d2fcc42d6df7fae4c3e.json
  body: 8 products, first: Mechanical Keyboard 89
What’s happening
  1. The folder has two files: shop.har and a JSON file named by the SHA-1 hash of the body. For a .har file name, Playwright keeps response bodies in separate files next to it (the updateContent option, 1.32+, chooses "embed" or "attach"); for a name ending in .zip, it writes everything into one archive.
  2. The HAR's log.creator says it was written by Playwright 1.65.1.
  3. There's one entry: GET …/practice/api/products.json → 200 application/json. Only the API call matched **/api/**; the page and its scripts weren't recorded.
  4. Each entry keeps the request (method, URL, every header the browser sent) and the response (status, every header, such as the Content-Type printed here, and the body). The script prints only stable fields: the full entry also records dates, timings and the server's own headers, which differ between runs and between the live site and a local copy. The body file holds the eight real products, starting with the Mechanical Keyboard at 89.
  5. The default updateMode is "minimal": only what's needed to replay. "full" records more (timings, cookies, security details), useful when the HAR is for people to read, not just to replay.
AdvancedReplaying, and editing the tape

To show that replay really serves the file and not the server, a script edits the recorded body (the mouse becomes $1.00), and a test replays it:

edit-har.mjs
import { readFileSync, writeFileSync } from "node:fs";

const har = JSON.parse(readFileSync("hars/shop.har", "utf8"));
const file = `hars/${har.log.entries[0].response.content._file}`;
const products = JSON.parse(readFileSync(file, "utf8"));
products.find((p) => p.id === "ms-01").price = 1;
writeFileSync(file, JSON.stringify(products));
console.log("edited", file.replace(/[0-9a-f]{40}/, "<hash>"));
node edit-har.mjs
edited hars/<hash>.json
tests/replay.spec.ts
import { test, expect } from "@playwright/test";

test("replay the recorded catalogue", async ({ page }) => {
  await page.routeFromHAR("hars/shop.har", { url: "**/api/**" });
  await page.goto("/practice/");
  await page.localStorage.setItem("shop-user", JSON.stringify({ username: "rohit", name: "Rohit" }));
  await page.goto("/practice/shop");

  await expect(page.getByTestId("product-ms-01")).toContainText("$1.00");
  await expect(page.getByRole("listitem")).toHaveCount(8);
});
npx playwright test tests/replay.spec.ts
Running 1 test using 1 worker

  ✓  1 [chromium] › tests/replay.spec.ts:3:1 › replay the recorded catalogue (944ms)

  1 passed (1.5s)
What’s happening
  1. The edit script finds the products body through the entry's _file, sets the Wireless Mouse's price to 1 and saves it. (The docs suggest exactly this: edit the recorded files to make the scenario you want, and commit them.)
  2. The replay test calls routeFromHAR without update, so matching requests are answered from the file. The shop shows the mouse at $1.00, a price the real server never returns: the response came from the tape.
  3. Matching is strict: per the docs, the URL and method must match exactly (and the body, for POST requests). A request the HAR doesn't have is aborted by default (notFound: "abort"), or sent to the network with notFound: "fallback".
  4. Because the recorded URLs include the host, a HAR recorded against one environment only replays against the same host. Record per environment, or keep url tight and the host stable.

#API testing with the request fixture

Added

Not every test needs a browser. The request fixture is an HTTP client (an APIRequestContext) that uses the config's baseURL and extraHTTPHeaders, keeps its own cookies, and returns responses you can check: status(), headers(), json(), text(), and expect(response).toBeOK() for "status 200–299". It runs in milliseconds, so it's the right tool for checking an API's contract directly, and for setting up data quickly before a UI test.

The mental model: the same test runner, with the browser taken out. Fixtures, projects, retries, reports and traces all work; tests just talk HTTP instead of clicking.

The Practice Shop's API is two read-only JSON endpoints (it's a static site), so these tests check exactly what its front end depends on:

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

test("the products endpoint returns the catalogue as JSON", async ({ request }) => {
  const res = await request.get("/practice/api/products.json");

  await expect(res).toBeOK();
  expect(res.status()).toBe(200);
  expect(res.headers()["content-type"]).toBe("application/json");

  const products = await res.json();
  expect(products).toHaveLength(8);
  for (const p of products) {
    expect(p).toEqual({
      id: expect.stringMatching(/^[a-z]{2}-\d{2}$/),
      name: expect.any(String),
      category: expect.any(String),
      price: expect.any(Number),
      stock: expect.any(Number),
    });
  }
  expect(products.filter((p: { stock: number }) => p.stock === 0).map((p: { name: string }) => p.name)).toEqual(["Vertical Mouse"]);
});

test("a known promo code returns its discount", async ({ request }) => {
  const res = await request.get("/practice/api/promos/SAVE10.json");
  await expect(res).toBeOK();
  expect(await res.json()).toEqual({ code: "SAVE10", percent: 10 });
});

test("an unknown promo code is a 404", async ({ request }) => {
  const res = await request.get("/practice/api/promos/NOPE.json");
  expect(res.status()).toBe(404);
  await expect(res).not.toBeOK();
});
npx playwright test
Running 3 tests using 1 worker

  ✓  1 [chromium] › tests/shop-api.spec.ts:3:1 › the products endpoint returns the catalogue as JSON (24ms)
  ✓  2 [chromium] › tests/shop-api.spec.ts:24:1 › a known promo code returns its discount (5ms)
  ✓  3 [chromium] › tests/shop-api.spec.ts:30:1 › an unknown promo code is a 404 (3ms)

  3 passed (373ms)
What’s happening
  1. request.get("/practice/api/products.json") resolves against baseURL and returns an APIResponse. No browser page is opened for these tests, which is why each takes a tiny fraction of a UI test's time.
  2. await expect(res).toBeOK() checks the status is 2xx; on failure its message includes the response, which is more useful than expect(res.ok()).toBe(true). The test also checks the exact status and the Content-Type header (header names come back lower-cased).
  3. The body is checked as a contract: eight products, each with exactly these five fields of these types, ids shaped like ms-01. toEqual with expect.any(...) and expect.stringMatching(...) checks shape without hard-coding every value, so a price change doesn't break it but a renamed field does.
  4. The last assertion pins down one business fact the UI tests rely on: exactly one product is sold out, the Vertical Mouse.
  5. The promo tests check the endpoint the checkout uses: SAVE10 returns { code: "SAVE10", percent: 10 }, and an unknown code returns 404, the status the checkout turns into "That code isn’t valid." not.toBeOK() reads naturally for "this must fail".
AdvancedOn a real API: create, read, update, delete

The shop has no endpoints that change anything, so here a 40-line orders API stands in for a real backend (port 4214, started by webServer). The tests check the CRUD cycle and the validation, the way you'd test your own API. Note failOnStatusCode is left off, so a 400 is a response to check, not an exception:

api.mjs
import { createServer } from "node:http";

const orders = new Map();
let next = 1001;
const json = (res, status, body) => res.writeHead(status, { "content-type": "application/json" }).end(body === undefined ? "" : JSON.stringify(body));
const readBody = async (req) => {
  let raw = "";
  for await (const chunk of req) raw += chunk;
  return raw ? JSON.parse(raw) : {};
};

createServer(async (req, res) => {
  const url = new URL(req.url, "http://localhost");
  const id = url.pathname.match(/^\/api\/orders\/([\w-]+)$/)?.[1];
  if (req.headers.authorization !== "Bearer test-token" && url.pathname.startsWith("/api/")) return json(res, 401, { error: "unauthorised" });
  if (req.method === "POST" && url.pathname === "/api/orders") {
    const { items } = await readBody(req);
    if (!Array.isArray(items) || items.length === 0) return json(res, 400, { error: "items must be a non-empty list" });
    const order = { id: `ORD-${next++}`, items, status: "placed" };
    orders.set(order.id, order);
    return json(res, 201, order);
  }
  if (id && !orders.has(id)) return json(res, 404, { error: "no such order" });
  if (req.method === "GET" && id) return json(res, 200, orders.get(id));
  if (req.method === "PATCH" && id) return json(res, 200, Object.assign(orders.get(id), await readBody(req)));
  if (req.method === "DELETE" && id) return orders.delete(id), json(res, 204);
  if (req.method === "GET" && url.pathname === "/") {
    const rows = [...orders.values()].map((o) => `<li>${o.id}: ${o.items.join(", ")} (${o.status})</li>`).join("");
    return res.writeHead(200, { "content-type": "text/html" }).end(`<h1>Orders</h1><ul aria-label="Orders">${rows}</ul>`);
  }
  json(res, 404, { error: "not found" });
}).listen(4214, "127.0.0.1");
playwright.config.ts
import { defineConfig } from "@playwright/test";

export default defineConfig({
  testDir: "./tests",
  workers: 1,
  use: {
    baseURL: "http://127.0.0.1:4214",
    extraHTTPHeaders: { authorization: "Bearer test-token" },
  },
  webServer: { command: "node api.mjs", url: "http://127.0.0.1:4214" },
});
tests/orders-api.spec.ts
import { test, expect } from "@playwright/test";

test("an order can be created, read, updated and deleted", async ({ request }) => {
  const created = await request.post("/api/orders", { data: { items: ["kb-01", "ms-01"] } });
  expect(created.status()).toBe(201);
  const order = await created.json();
  expect(order).toEqual({ id: expect.stringMatching(/^ORD-\d+$/), items: ["kb-01", "ms-01"], status: "placed" });

  const read = await request.get(`/api/orders/${order.id}`);
  expect(await read.json()).toEqual(order);

  const updated = await request.patch(`/api/orders/${order.id}`, { data: { status: "shipped" } });
  expect((await updated.json()).status).toBe("shipped");

  expect((await request.delete(`/api/orders/${order.id}`)).status()).toBe(204);
  expect((await request.get(`/api/orders/${order.id}`)).status()).toBe(404);
});

test("an order with no items is rejected with a 400", async ({ request }) => {
  const res = await request.post("/api/orders", { data: { items: [] } });
  expect(res.status()).toBe(400);
  expect(await res.json()).toEqual({ error: "items must be a non-empty list" });
});

test("a request without the token is a 401", async ({ playwright }) => {
  // In the test runner, newContext() starts from the config's `use` (token included): replace the headers.
  const anonymous = await playwright.request.newContext({ extraHTTPHeaders: {} });
  const res = await anonymous.get("/api/orders/ORD-1001");
  expect(res.status()).toBe(401);
  await anonymous.dispose();
});

test("API setup, UI check: an order made through the API shows on the page", async ({ request, page }) => {
  const order = await (await request.post("/api/orders", { data: { items: ["au-02"] } })).json();

  await page.goto("/");

  await expect(page.getByRole("list", { name: "Orders" })).toContainText(`${order.id}: au-02 (placed)`);
  await request.delete(`/api/orders/${order.id}`);
});
npx playwright test
Running 4 tests using 1 worker

  ✓  1 tests/orders-api.spec.ts:3:1 › an order can be created, read, updated and deleted (54ms)
  ✓  2 tests/orders-api.spec.ts:19:1 › an order with no items is rejected with a 400 (5ms)
  ✓  3 tests/orders-api.spec.ts:25:1 › a request without the token is a 401 (4ms)
  ✓  4 tests/orders-api.spec.ts:33:1 › API setup, UI check: an order made through the API shows on the page (109ms)

  4 passed (878ms)
What’s happening
  1. extraHTTPHeaders in the config adds authorization: Bearer test-token to every request the request fixture makes, the usual way to authenticate API tests (read the token from an environment variable in real life, never commit it).
  2. The CRUD test follows one order through its life: POST returns 201 and the new order (its id checked by pattern, not value), GET returns the same order, PATCH changes its status to "shipped", DELETE returns 204, and a final GET returns 404. data sends a JSON body with the right Content-Type.
  3. The validation test posts an empty item list and checks both the 400 and the error body. Rules like this are cheap to cover exhaustively at the API level, which is where Chapter 3 said they belong.
  4. The 401 test needs a client without the token, so it builds one with playwright.request.newContext() and disposes of it afterwards. A surprise found while writing this page: inside the test runner, newContext() starts from the config's use options, so the first draft (with no options) still sent the token and got a 404 instead of a 401. Passing extraHTTPHeaders: {} replaces the inherited headers; baseURL is still inherited, so /api/orders/ORD-1001 resolves.
  5. API setup, UI check: the last test creates an order through the API in milliseconds, then opens the page in a browser and checks it's listed. That's the pattern for real apps: make the data through the API, test the UI that shows or uses it, and clean up through the API.
  6. On the Practice Shop the same mix isn't possible (there's nothing to create), so its UI tests seed state with page.localStorage instead (Chapter 8). On a real product, seeding through your own API is better: it doesn't depend on the front end's internal storage format.

#Watching what the page sends

Added

Sometimes the thing to check is a request: that clicking Apply sends the right code, that a form posts the right body, that analytics fire once, or that the page logged no errors. Playwright gives you several ways to watch without changing anything:

  • page.waitForRequest(pattern) / page.waitForResponse(pattern): a promise that resolves with the next matching request or response. Start waiting before the action that triggers it, then await it after.
  • page.on("request" | "response" | "console" | "pageerror", handler): an event for every one, as it happens.
  • page.requests(), page.consoleMessages(), page.pageErrors() (all 1.56+): the most recent ones the page has seen (up to 100 requests and 200 messages or errors), read after the fact, no listener needed.

The mental model: a wiretap, not a mailroom. page.route can change traffic; these only listen.

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

test.beforeEach(async ({ page }) => {
  await page.goto("/practice/");
  await page.localStorage.setItem("shop-user", JSON.stringify({ username: "rohit", name: "Rohit" }));
  await page.localStorage.setItem("shop-cart", JSON.stringify([{ id: "ms-01", name: "Wireless Mouse", price: 29.5, qty: 1 }]));
});

test("Apply sends the code in upper case", async ({ page }) => {
  await page.goto("/practice/checkout");
  await page.getByLabel("Promo code").fill("save10");

  const responsePromise = page.waitForResponse("**/practice/api/promos/*.json");
  await page.getByRole("button", { name: "Apply" }).click();
  const response = await responsePromise;

  expect(new URL(response.url()).pathname).toBe("/practice/api/promos/SAVE10.json");
  expect(response.request().method()).toBe("GET");
  expect(response.status()).toBe(200);
  expect(await response.json()).toEqual({ code: "SAVE10", percent: 10 });
  await expect(page.getByText("SAVE10 applied: 10% off.")).toBeVisible();
});

test("page.requests() lists what the page fetched", async ({ page }) => {
  await page.goto("/practice/shop");
  await expect(page.getByRole("listitem")).toHaveCount(8);

  const requests = await page.requests();
  for (const r of requests) console.log(r.method(), r.resourceType().padEnd(10), new URL(r.url()).pathname);
});

test("console errors are collected for you", async ({ page }) => {
  await page.route("**/practice/api/products.json", (route) => route.fulfill({ status: 500 }));
  await page.goto("/practice/shop");
  await expect(page.getByRole("alert")).toHaveText("Couldn’t load products. Try again later.");

  const errors = (await page.consoleMessages()).filter((m) => m.type() === "error");
  for (const m of errors) console.log(m.type(), "|", m.text());
  expect(errors).toHaveLength(1);
  expect(await page.pageErrors()).toEqual([]);
});
npx playwright test
Running 3 tests using 1 worker

  ✓  1 [chromium] › tests/watch.spec.ts:9:1 › Apply sends the code in upper case (245ms)
GET document   /practice/
GET stylesheet /practice/practice.css
GET script     /practice/practice.js
GET document   /practice/shop
GET stylesheet /practice/practice.css
GET script     /practice/practice.js
GET fetch      /practice/api/products.json
  ✓  2 [chromium] › tests/watch.spec.ts:24:1 › page.requests() lists what the page fetched (892ms)
error | Failed to load resource: the server responded with a status of 500 (Internal Server Error)
  ✓  3 [chromium] › tests/watch.spec.ts:32:1 › console errors are collected for you (918ms)

  3 passed (2.6s)
What’s happening
  1. The beforeEach seeds a signed-in rohit with a mouse in the cart (Chapter 8), so each test starts where it needs to be.
  2. waitForResponse: the promise is created before the click, then awaited after. Created after, the response might already have arrived and the wait would time out. The response shows the shop upper-cased "save10" into /practice/api/promos/SAVE10.json, sent a GET, and got 200 with the SAVE10 body. The UI check comes last: the request was right and the user saw the result.
  3. page.requests() (1.56+) returned everything this page fetched, across both navigations: the sign-in page the beforeEach opened (document, stylesheet, script), then the shop page (the same three) and its fetch of the products JSON. Seven requests, in order. The list keeps only the most recent 100, and the docs warn that details of older ones may be collected to save memory, so read it promptly (or use page.on("request") when you need everything).
  4. page.consoleMessages() (1.56+): with the products request failing with 500, Chromium itself logged one console error, "Failed to load resource: the server responded with a status of 500 (Internal Server Error)". The shop logged nothing (it handled the error and showed its alert), and page.pageErrors() is empty: no uncaught exceptions.
  5. That console line is browser-specific wording: Firefox and WebKit log failed loads differently (or not at all), so match on type() === "error", not on the exact text, if a suite runs on several browsers.
  6. A common use of the last two is an auto fixture that fails any test with unexpected console errors or page errors (Chapter 7 builds one with page.on("pageerror")). The 1.56 methods make the check a one-liner in the fixture's teardown.
AdvancedStart the wait before the action

#Your turn: mock and test the shop's APIs

Added
Your turn: make the catalogue fail, then recover

Write a test where the first products request fails with a 500 and the shop shows its error, and then, after a reload, the real catalogue loads. Use the times option of page.route so the mock only answers once.

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

test("after a failed load, a reload shows the products", async ({ page }) => {
  await page.route("**/practice/api/products.json", (route) => route.fulfill({ status: 500 }), { times: 1 });
  await page.goto("/practice/");
  await page.localStorage.setItem("shop-user", JSON.stringify({ username: "ana", name: "Ana" }));

  await page.goto("/practice/shop");
  await expect(page.getByRole("alert")).toHaveText("Couldn’t load products. Try again later.");

  await page.reload();

  await expect(page.getByRole("listitem")).toHaveCount(8);
  await expect(page.getByRole("alert")).toHaveCount(0);
});
npx playwright test
Running 1 test using 1 worker

  ✓  1 [chromium] › tests/recover.spec.ts:3:1 › after a failed load, a reload shows the products (1.8s)

  1 passed (2.3s)
What’s happening
  1. { times: 1 } makes the route handle only the first matching request; after that it removes itself and requests go to the real server.
  2. The first visit to the shop gets the 500, so the alert appears.
  3. page.reload() requests the products again; the route is used up, so the real catalogue arrives and eight products show.
  4. The last check makes sure the error is gone after recovery (no role="alert" left), which a test checking only the products would miss.
Your turn: WELCOME5, at both levels

Write an API test (no browser) that checks GET /practice/api/promos/WELCOME5.json returns 200, JSON, and { code: "WELCOME5", percent: 5 }. Then write a UI test that types "welcome5" in lower case at the checkout and proves, by watching the network, that the shop requested WELCOME5.json, and that the summary shows the discount.

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

test("API: WELCOME5 gives 5% off", async ({ request }) => {
  const res = await request.get("/practice/api/promos/WELCOME5.json");
  await expect(res).toBeOK();
  expect(res.headers()["content-type"]).toBe("application/json");
  expect(await res.json()).toEqual({ code: "WELCOME5", percent: 5 });
});

test("UI: a lower-case code is sent in upper case and applied", async ({ page }) => {
  await page.goto("/practice/");
  await page.localStorage.setItem("shop-user", JSON.stringify({ username: "ana", name: "Ana" }));
  await page.localStorage.setItem("shop-cart", JSON.stringify([{ id: "kb-01", name: "Mechanical Keyboard", price: 89, qty: 1 }]));
  await page.goto("/practice/checkout");

  await page.getByLabel("Promo code").fill("welcome5");
  const requestPromise = page.waitForRequest("**/practice/api/promos/*.json");
  await page.getByRole("button", { name: "Apply" }).click();
  const request = await requestPromise;

  expect(new URL(request.url()).pathname).toBe("/practice/api/promos/WELCOME5.json");
  await expect(page.getByText("WELCOME5 applied: 5% off.")).toBeVisible();
  await expect(page.getByTestId("order-total")).toHaveText("$84.55");
});
npx playwright test
Running 2 tests using 1 worker

  ✓  1 [chromium] › tests/welcome5.spec.ts:3:1 › API: WELCOME5 gives 5% off (25ms)
  ✓  2 [chromium] › tests/welcome5.spec.ts:10:1 › UI: a lower-case code is sent in upper case and applied (296ms)

  2 passed (914ms)
What’s happening
  1. The API test checks status, content type and the exact body: everything the checkout reads from this endpoint, in milliseconds.
  2. The UI test seeds ana with an $89 keyboard, types "welcome5", and starts waitForRequest before clicking Apply, so the request can't slip past.
  3. The request's path is /practice/api/promos/WELCOME5.json: the front end upper-cased the code (code.trim().toUpperCase() in the shop's script) before asking the server.
  4. The summary shows the result: $89.00 − 5% ($4.45) = $84.55. The two tests check different halves of one feature (the server's answer, and the UI's use of it), which is how API and UI tests should split the work.

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.