Playwright NotesRohit’s interview study guide
Chapter 10

Visual and Accessibility Testing

Checking what the page looks like (screenshot comparison), what its structure is (aria snapshots) and whether people using assistive technology can use it (axe), with what each catches, what it can't, and why visual tests flake. Every test was run with Playwright 1.65.1 against the Practice Shop.

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

#Screenshot comparison with toHaveScreenshot

Added

Every assertion so far checked a fact: this text, this count, this URL. None of them notices that the price is now white on white, that the Add to cart button slid under the footer, or that a CSS refactor made every card 40 pixels taller. A user sees those at once; a toHaveText test passes straight through them. Visual comparison fills that gap: take a screenshot, compare it pixel by pixel with an approved one, and fail if they differ.

await expect(page).toHaveScreenshot() (or expect(locator) for one element) does three things. It waits until the page is stable: it takes screenshots until two in a row match, so a half-loaded page isn't captured. It compares that screenshot with the baseline (the "expected" image saved next to the test). And if there's no baseline yet, it writes one and fails, so a new visual test can never pass silently on its first run.

The mental model: a "spot the difference" puzzle with an answer sheet. The baseline is the approved picture, committed to git and reviewed like code. Every run draws the picture again and circles every difference. The hard part isn't drawing; it's deciding which differences matter, which is what thresholds and masks are for.

BugtoHaveText / toBeVisibletoHaveScreenshot
Wrong price textcatches itcatches it (as changed pixels)
Price rendered in the wrong colour or weightmisses itcatches it
Button pushed off screen or under another elementsometimes (click fails)catches it
Layout broken at one viewport sizemisses itcatches it (one screenshot per size)
A different user's name in the headercatches it if assertedfails, which is noise: mask it

Here is the first run of a brand-new visual test, then the second run:

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

test("the sign-in page looks right", async ({ page }) => {
  await page.goto("/practice/");
  await expect(page).toHaveScreenshot();
});

test("the product list looks right", 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 expect(page.getByRole("listitem")).toHaveCount(8);

  await expect(page.getByRole("list", { name: "Products" })).toHaveScreenshot("products.png");
});
npx playwright test
Running 2 tests using 1 worker

  ✘  1 [chromium] › tests/visual.spec.ts:3:1 › the sign-in page looks right (365ms)
  ✘  2 [chromium] › tests/visual.spec.ts:8:1 › the product list looks right (1.8s)


  1) [chromium] › tests/visual.spec.ts:3:1 › the sign-in page looks right ──────────────────────────

    Error: A snapshot doesn't exist at <project>/tests/visual.spec.ts-snapshots/the-sign-in-page-looks-right-1-chromium-darwin.png, writing actual.

      3 | test("the sign-in page looks right", async ({ page }) => {
      4 |   await page.goto("/practice/");
    > 5 |   await expect(page).toHaveScreenshot();
        |   ^
      6 | });
      7 |
      8 | test("the product list looks right", async ({ page }) => {
        at <project>/tests/visual.spec.ts:5:3

    attachment #1: the-sign-in-page-looks-right-1 (image/png) ──────────────────────────────────────
    Expected: tests/visual.spec.ts-snapshots/the-sign-in-page-looks-right-1-chromium-darwin.png
    Received: test-results/visual-the-sign-in-page-looks-right-chromium/the-sign-in-page-looks-right-1-actual.png
    ────────────────────────────────────────────────────────────────────────────────────────────────

    Error Context: test-results/visual-the-sign-in-page-looks-right-chromium/error-context.md

  2) [chromium] › tests/visual.spec.ts:8:1 › the product list looks right ──────────────────────────

    Error: A snapshot doesn't exist at <project>/tests/visual.spec.ts-snapshots/products-chromium-darwin.png, writing actual.

      13 |   await expect(page.getByRole("listitem")).toHaveCount(8);
      14 |
    > 15 |   await expect(page.getByRole("list", { name: "Products" })).toHaveScreenshot("products.png");
         |   ^
      16 | });
      17 |
        at <project>/tests/visual.spec.ts:15:3

    attachment #1: products (image/png) ────────────────────────────────────────────────────────────
    Expected: tests/visual.spec.ts-snapshots/products-chromium-darwin.png
    Received: test-results/visual-the-product-list-looks-right-chromium/products-actual.png
    ────────────────────────────────────────────────────────────────────────────────────────────────

    Error Context: test-results/visual-the-product-list-looks-right-chromium/error-context.md

  2 failed
    [chromium] › tests/visual.spec.ts:3:1 › the sign-in page looks right ───────────────────────────
    [chromium] › tests/visual.spec.ts:8:1 › the product list looks right ───────────────────────────
npx playwright test
Running 2 tests using 1 worker

  ✓  1 [chromium] › tests/visual.spec.ts:3:1 › the sign-in page looks right (155ms)
  ✓  2 [chromium] › tests/visual.spec.ts:8:1 › the product list looks right (1.6s)

  2 passed (2.2s)
What’s happening
  1. First run: no baseline exists. Each toHaveScreenshot takes its screenshot, finds no file to compare with, writes the screenshot as the new baseline ("writing actual") and fails. That failure is deliberate (the updateSnapshots: "default" mode): a CI run must never go green just because the baseline was missing.
  2. The error says exactly where the baseline went: tests/visual.spec.ts-snapshots/, next to the test file. The first test has no name argument, so Playwright made one from the title (the-sign-in-page-looks-right-1); the second is named products.png. Both got -chromium-darwin added: the project name and the operating system the run happened on (macOS is darwin).
  3. Second run: the baselines exist, the new screenshots match them pixel for pixel, and both tests pass. From now on, any visible change to the sign-in page or the product list fails these tests until someone approves it.
  4. The product test waits for all 8 products before the screenshot (toHaveCount(8)). toHaveScreenshot waits for the page to stop changing, but the shop shows "Loading products…" for about 0.7 s, which is perfectly stable, so without that line the baseline could be a picture of the spinner.
  5. expect(locator).toHaveScreenshot() captures just that element: the product grid, not the header. Smaller screenshots fail for fewer unrelated reasons, which is the single best way to keep visual tests useful.
AdvancedWhat a failing comparison looks like

To see a real failure, the next suite takes a baseline, then runs the same page with one CSS rule changed, the kind of change a refactor makes by accident. Two tests in one file that use the same name (products.png) share one baseline, so the second test compares the changed page with the first test's picture. The first run creates the baseline for the @baseline test only; the second run is the normal run.

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

async function openShop(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();
  await expect(page.getByRole("listitem")).toHaveCount(8);
}
const products = (page: Page) => page.getByRole("list", { name: "Products" });
const unbold = ".product .price { font-weight: 400; }"; // the "accidental" change

test("the product list @baseline", async ({ page }) => {
  await openShop(page);
  await expect(products(page)).toHaveScreenshot("products.png");
});

test("after a CSS change: prices lose their bold", async ({ page }) => {
  await openShop(page);
  await page.addStyleTag({ content: unbold });
  await expect(products(page)).toHaveScreenshot("products.png");
});

test("the same change, allowing 100 different pixels", async ({ page }) => {
  await openShop(page);
  await page.addStyleTag({ content: unbold });
  await expect(products(page)).toHaveScreenshot("products.png", { maxDiffPixels: 100 });
});

test("the same change, allowing 5% different pixels", async ({ page }) => {
  await openShop(page);
  await page.addStyleTag({ content: unbold });
  await expect(products(page)).toHaveScreenshot("products.png", { maxDiffPixelRatio: 0.05 });
});
npx playwright test --update-snapshots --grep @baseline
Running 1 test using 1 worker

A snapshot doesn't exist at <project>/tests/products.spec.ts-snapshots/products-chromium-darwin.png, writing actual.
  ✓  1 [chromium] › tests/products.spec.ts:13:1 › the product list @baseline (1.8s)

  1 passed (2.5s)
npx playwright test
Running 4 tests using 1 worker

  ✓  1 [chromium] › tests/products.spec.ts:13:1 › the product list @baseline (1.6s)
  ✘  2 [chromium] › tests/products.spec.ts:18:1 › after a CSS change: prices lose their bold (1.9s)
  ✘  3 [chromium] › tests/products.spec.ts:24:1 › the same change, allowing 100 different pixels (2.2s)
  ✓  4 [chromium] › tests/products.spec.ts:30:1 › the same change, allowing 5% different pixels (1.6s)


  1) [chromium] › tests/products.spec.ts:18:1 › after a CSS change: prices lose their bold ─────────

    Error: expect(locator).toHaveScreenshot(expected) failed

    Locator: getByRole('list', { name: 'Products' })
      1992 pixels (ratio 0.01 of all image pixels) are different.

      Snapshot: products.png

    Call log:
      - Expect "toHaveScreenshot(products.png)" getByRole('list', { name: 'Products' }) with timeout 5000ms
        - verifying given screenshot expectation
      - waiting for getByRole('list', { name: 'Products' })
        - locator resolved to <ul class="products" data-products="" aria-label="Products">…</ul>
      - taking element screenshot
        - disabled all CSS animations
      - waiting for fonts to load...
      - fonts loaded
      - attempting scroll into view action
        - waiting for element to be stable
      - 1992 pixels (ratio 0.01 of all image pixels) are different.
      - waiting 100ms before taking screenshot
      - waiting for getByRole('list', { name: 'Products' })
        - locator resolved to <ul class="products" data-products="" aria-label="Products">…</ul>
      - taking element screenshot
        - disabled all CSS animations
      - waiting for fonts to load...
      - fonts loaded
      - attempting scroll into view action
        - waiting for element to be stable
      - captured a stable screenshot
      - 1992 pixels (ratio 0.01 of all image pixels) are different.


      19 |   await openShop(page);
      20 |   await page.addStyleTag({ content: unbold });
    > 21 |   await expect(products(page)).toHaveScreenshot("products.png");
         |                                ^
      22 | });
      23 |
      24 | test("the same change, allowing 100 different pixels", async ({ page }) => {
        at <project>/tests/products.spec.ts:21:32

    attachment #1: products (image/png) ────────────────────────────────────────────────────────────
    Expected: tests/products.spec.ts-snapshots/products-chromium-darwin.png
    Received: test-results/products-after-a-CSS-change-prices-lose-their-bold-chromium/products-actual.png
    Diff:     test-results/products-after-a-CSS-change-prices-lose-their-bold-chromium/products-diff.png
    ────────────────────────────────────────────────────────────────────────────────────────────────

    Error Context: test-results/products-after-a-CSS-change-prices-lose-their-bold-chromium/error-context.md

  2) [chromium] › tests/products.spec.ts:24:1 › the same change, allowing 100 different pixels ─────

    Error: expect(locator).toHaveScreenshot(expected) failed

    Locator: getByRole('list', { name: 'Products' })
      1992 pixels (ratio 0.01 of all image pixels) are different.

      Snapshot: products.png

    Call log:
      - Expect "toHaveScreenshot(products.png)" getByRole('list', { name: 'Products' }) with timeout 5000ms
        - verifying given screenshot expectation
      - waiting for getByRole('list', { name: 'Products' })
        - locator resolved to <ul class="products" data-products="" aria-label="Products">…</ul>
      - taking element screenshot
        - disabled all CSS animations
      - waiting for fonts to load...
      - fonts loaded
      - attempting scroll into view action
        - waiting for element to be stable
      - 1992 pixels (ratio 0.01 of all image pixels) are different.
      - waiting 100ms before taking screenshot
      - waiting for getByRole('list', { name: 'Products' })
        - locator resolved to <ul class="products" data-products="" aria-label="Products">…</ul>
      - taking element screenshot
        - disabled all CSS animations
      - waiting for fonts to load...
      - fonts loaded
      - attempting scroll into view action
        - waiting for element to be stable
      - captured a stable screenshot
      - 1992 pixels (ratio 0.01 of all image pixels) are different.


      25 |   await openShop(page);
      26 |   await page.addStyleTag({ content: unbold });
    > 27 |   await expect(products(page)).toHaveScreenshot("products.png", { maxDiffPixels: 100 });
         |                                ^
      28 | });
      29 |
      30 | test("the same change, allowing 5% different pixels", async ({ page }) => {
        at <project>/tests/products.spec.ts:27:32

    attachment #1: products (image/png) ────────────────────────────────────────────────────────────
    Expected: tests/products.spec.ts-snapshots/products-chromium-darwin.png
    Received: test-results/products-the-same-change-allowing-100-different-pixels-chromium/products-actual.png
    Diff:     test-results/products-the-same-change-allowing-100-different-pixels-chromium/products-diff.png
    ────────────────────────────────────────────────────────────────────────────────────────────────

    Error Context: test-results/products-the-same-change-allowing-100-different-pixels-chromium/error-context.md

  2 failed
    [chromium] › tests/products.spec.ts:18:1 › after a CSS change: prices lose their bold ──────────
    [chromium] › tests/products.spec.ts:24:1 › the same change, allowing 100 different pixels ──────
  2 passed (9.5s)
list-files.mjs
// Prints every file under the given folders, sorted, so the page can show what a run really wrote.
import { readdirSync } from "node:fs";
import { join } from "node:path";
const walk = (d) => readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(join(d, e.name)) : [join(d, e.name)]));
for (const dir of process.argv.slice(2)) for (const f of walk(dir).sort()) console.log(f);
node list-files.mjs tests test-results
tests/products.spec.ts
tests/products.spec.ts-snapshots/products-chromium-darwin.png
test-results/.last-run.json
test-results/products-after-a-CSS-change-prices-lose-their-bold-chromium/error-context.md
test-results/products-after-a-CSS-change-prices-lose-their-bold-chromium/products-actual.png
test-results/products-after-a-CSS-change-prices-lose-their-bold-chromium/products-diff.png
test-results/products-after-a-CSS-change-prices-lose-their-bold-chromium/products-expected.png
test-results/products-the-same-change-allowing-100-different-pixels-chromium/error-context.md
test-results/products-the-same-change-allowing-100-different-pixels-chromium/products-actual.png
test-results/products-the-same-change-allowing-100-different-pixels-chromium/products-diff.png
test-results/products-the-same-change-allowing-100-different-pixels-chromium/products-expected.png
What’s happening
  1. --update-snapshots --grep @baseline runs only the first test and writes its baseline (the run still prints "A snapshot doesn't exist … writing actual", but passes, because writing it was requested). --update-snapshots is how you approve a change: run it after an intentional redesign, look at the new images in the diff of your pull request, and commit them.
  2. The second test adds one CSS rule, font-weight: 400 on the prices, and fails: 1992 pixels differ, which rounds to a ratio of 0.01 (1%) of the image. Notice the call log: it took a screenshot, compared, waited 100 ms, took another, got "a stable screenshot", and only then gave up. Playwright never fails on a frame caught mid-change.
  3. The failure writes three images into the test's folder in test-results/: products-expected.png (a copy of the baseline), products-actual.png (what the page looks like now) and products-diff.png (the changed pixels highlighted). The HTML report shows them side by side with a slider; on CI you download them as an artifact.
  4. maxDiffPixels: 100 still fails: 1992 is more than 100. A small pixel budget like this absorbs anti-aliasing noise (a few dozen pixels along text edges) and still catches a real change.
  5. maxDiffPixelRatio: 0.05 (5%) passes: 1% of the image changed, under the limit. That's the danger of ratio thresholds on big screenshots: every price on the page changed weight and the test didn't notice. Keep tolerances small, and prefer small element screenshots to big page screenshots with a big tolerance.
  6. The file list shows the one baseline (tests/products.spec.ts-snapshots/products-chromium-darwin.png), the three images for each failed test, an error-context.md per failure (Chapter 11), and .last-run.json, which --last-failed reads.
AdvancedThe options you'll use, and their defaults

From the 1.65 API docs, for toHaveScreenshot (set them per call, or for every test under expect: { toHaveScreenshot: { … } } in the config):

OptionWhat it doesDefault
maxDiffPixelshow many pixels may differunset (none)
maxDiffPixelRatiowhat fraction of pixels may differ, 0 to 1unset (none)
thresholdhow different one pixel's colour must be to count as changed (YIQ colour space), 0 strict to 1 lax0.2
masklocators to paint over with a solid box before comparingnone
maskColorthe box colour#FF00FF (pink)
animations"disabled" stops CSS animations and transitions; finite ones jump to their end"disabled"
caret"hide" hides the blinking text cursor"hide"
fullPagethe whole scrollable page instead of the viewportfalse
stylePatha CSS file applied only while capturing (hide volatile parts)none
scale"css" (one pixel per CSS pixel) or "device""css"

threshold and maxDiffPixels answer different questions: threshold decides whether one pixel changed (a slightly different shade of green doesn't count), maxDiffPixels decides how many changed pixels are allowed. Leave threshold at its default unless you have a reason.

AdvancedMasking what's supposed to change

Some parts of a screen differ on every run, or for every user, and aren't what the test is about: the signed-in name, a date, an ad, a live counter. mask paints a solid box over them before comparing. Here the header's baseline is taken as Rohit, and the same header is then checked as Ana, first with a plain mask and then with a mask over a box of fixed size:

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

async function signInAs(page: Page, username: string) {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill(username);
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page.getByRole("listitem")).toHaveCount(8);
}
const masked = (page: Page) => ({ mask: [page.getByText(/^Signed in as/)] });
// Test-only CSS, applied after the functional checks: the name's box gets the same width for every user.
const fixNameWidth = (page: Page) => page.addStyleTag({ content: ".who { display: inline-block; min-width: 12em; }" });

test("header as rohit, masked @baseline", async ({ page }) => {
  await signInAs(page, "rohit");
  await expect(page.getByRole("banner")).toHaveScreenshot("header.png", masked(page));
});

test("header as ana, masked", async ({ page }) => {
  await signInAs(page, "ana");
  await expect(page.getByRole("banner")).toHaveScreenshot("header.png", masked(page));
});

test("header as rohit, fixed-width name, masked @baseline", async ({ page }) => {
  await signInAs(page, "rohit");
  await fixNameWidth(page);
  await expect(page.getByRole("banner")).toHaveScreenshot("header-fixed.png", masked(page));
});

test("header as ana, fixed-width name, masked", async ({ page }) => {
  await signInAs(page, "ana");
  await fixNameWidth(page);
  await expect(page.getByRole("banner")).toHaveScreenshot("header-fixed.png", masked(page));
});
npx playwright test --update-snapshots --grep @baseline
Running 2 tests using 1 worker

A snapshot doesn't exist at <project>/tests/header.spec.ts-snapshots/header-chromium-darwin.png, writing actual.
  ✓  1 [chromium] › tests/header.spec.ts:14:1 › header as rohit, masked @baseline (1.8s)
A snapshot doesn't exist at <project>/tests/header.spec.ts-snapshots/header-fixed-chromium-darwin.png, writing actual.
  ✓  2 [chromium] › tests/header.spec.ts:24:1 › header as rohit, fixed-width name, masked @baseline (1.7s)

  2 passed (4.1s)
npx playwright test
Running 4 tests using 1 worker

  ✓  1 [chromium] › tests/header.spec.ts:14:1 › header as rohit, masked @baseline (1.6s)
  ✘  2 [chromium] › tests/header.spec.ts:19:1 › header as ana, masked (1.9s)
  ✓  3 [chromium] › tests/header.spec.ts:24:1 › header as rohit, fixed-width name, masked @baseline (1.6s)
  ✓  4 [chromium] › tests/header.spec.ts:30:1 › header as ana, fixed-width name, masked (1.5s)


  1) [chromium] › tests/header.spec.ts:19:1 › header as ana, masked ────────────────────────────────

    Error: expect(locator).toHaveScreenshot(expected) failed

    Locator: getByRole('banner')
      126 pixels (ratio 0.01 of all image pixels) are different.

      Snapshot: header.png

    Call log:
      - Expect "toHaveScreenshot(header.png)" getByRole('banner') with timeout 5000ms
        - verifying given screenshot expectation
      - waiting for getByRole('banner')
        - locator resolved to <header class="bar">…</header>
      - taking element screenshot
        - disabled all CSS animations
      - waiting for fonts to load...
      - fonts loaded
      - attempting scroll into view action
        - waiting for element to be stable
      - 126 pixels (ratio 0.01 of all image pixels) are different.
      - waiting 100ms before taking screenshot
      - waiting for getByRole('banner')
        - locator resolved to <header class="bar">…</header>
      - taking element screenshot
        - disabled all CSS animations
      - waiting for fonts to load...
      - fonts loaded
      - attempting scroll into view action
        - waiting for element to be stable
      - captured a stable screenshot
      - 126 pixels (ratio 0.01 of all image pixels) are different.


      19 | test("header as ana, masked", async ({ page }) => {
      20 |   await signInAs(page, "ana");
    > 21 |   await expect(page.getByRole("banner")).toHaveScreenshot("header.png", masked(page));
         |                                          ^
      22 | });
      23 |
      24 | test("header as rohit, fixed-width name, masked @baseline", async ({ page }) => {
        at <project>/tests/header.spec.ts:21:42

    attachment #1: header (image/png) ──────────────────────────────────────────────────────────────
    Expected: tests/header.spec.ts-snapshots/header-chromium-darwin.png
    Received: test-results/header-header-as-ana-masked-chromium/header-actual.png
    Diff:     test-results/header-header-as-ana-masked-chromium/header-diff.png
    ────────────────────────────────────────────────────────────────────────────────────────────────

    Error Context: test-results/header-header-as-ana-masked-chromium/error-context.md

  1 failed
    [chromium] › tests/header.spec.ts:19:1 › header as ana, masked ─────────────────────────────────
  3 passed (7.9s)
What’s happening
  1. The two @baseline tests record Rohit's header twice: once as it is, once with the name's box given a fixed width. In both, a pink box covers "Signed in as rohit".
  2. Ana with the plain mask fails: 126 pixels differ. The mask covered her name, but "Signed in as ana" is shorter than "Signed in as rohit", so the box is narrower and starts further right; the strip where Rohit's box was and Ana's isn't is what differs. A mask hides the content, not its size.
  3. Ana with the fixed-width name passes: min-width: 12em makes the name's box the same size for both users, so the pink box lands in exactly the same place and everything else (brand, Account link, cart count, Log out) is identical.
  4. The CSS is added only after the functional part of the test, and only for the capture. The cleaner home for it is a stylesheet passed as stylePath (applied only while the screenshot is taken); addStyleTag is used here so the whole example fits on the page.
  5. Mask by locator, not by coordinates, so the box follows the element if the layout moves, and mask as little as possible: a mask over half the page is a test of the other half. Block-level elements (a whole paragraph, like the delivery estimate in the next topic) don't have this problem, because their box is full width whatever the text.
AdvancedOne baseline per browser and per operating system

Browsers render text and shapes differently, and so do operating systems (fonts, anti-aliasing, font hinting). So Playwright never compares a Firefox screenshot with a Chromium baseline: the file name carries the project and the platform. Here's one test in three browsers, after a --update-snapshots run:

playwright.config.ts
import { defineConfig, devices } from "@playwright/test";

export default defineConfig({
  testDir: "./tests",
  use: { baseURL: "https://rohit-playwright.pages.dev" },
  projects: [
    { name: "chromium", use: { ...devices["Desktop Chrome"] } },
    { name: "firefox", use: { ...devices["Desktop Firefox"] } },
    { name: "webkit", use: { ...devices["Desktop Safari"] } },
  ],
});
tests/signin.spec.ts
import { test, expect } from "@playwright/test";

test("sign-in page", async ({ page }) => {
  await page.goto("/practice/");
  await expect(page.getByRole("heading", { name: "Sign in" })).toBeVisible();
  await expect(page).toHaveScreenshot("signin.png");
});
npx playwright test --update-snapshots
Running 3 tests using 3 workers

A snapshot doesn't exist at <project>/tests/signin.spec.ts-snapshots/signin-chromium-darwin.png, writing actual.
  ✓  2 [chromium] › tests/signin.spec.ts:3:1 › sign-in page (491ms)
A snapshot doesn't exist at <project>/tests/signin.spec.ts-snapshots/signin-webkit-darwin.png, writing actual.
  ✓  1 [webkit] › tests/signin.spec.ts:3:1 › sign-in page (1.1s)
A snapshot doesn't exist at <project>/tests/signin.spec.ts-snapshots/signin-firefox-darwin.png, writing actual.
  ✓  3 [firefox] › tests/signin.spec.ts:3:1 › sign-in page (1.8s)

  3 passed (4.2s)
list-files.mjs
// Prints every file under the given folders, sorted, so the page can show what a run really wrote.
import { readdirSync } from "node:fs";
import { join } from "node:path";
const walk = (d) => readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(join(d, e.name)) : [join(d, e.name)]));
for (const dir of process.argv.slice(2)) for (const f of walk(dir).sort()) console.log(f);
node list-files.mjs tests
tests/signin.spec.ts
tests/signin.spec.ts-snapshots/signin-chromium-darwin.png
tests/signin.spec.ts-snapshots/signin-firefox-darwin.png
tests/signin.spec.ts-snapshots/signin-webkit-darwin.png
What’s happening
  1. Three projects, one test, so three runs and three baselines: signin-chromium-darwin.png, signin-firefox-darwin.png and signin-webkit-darwin.png. The default name pattern is roughly {name}-{projectName}-{platform}{ext} inside <test file>-snapshots/.
  2. darwin is process.platform on a Mac. On a Linux CI runner the same test looks for signin-chromium-linux.png, which doesn't exist, so the first CI run fails with "A snapshot doesn't exist". Baselines made on your Mac are no use to a Linux CI machine.
  3. The usual fix is to make and update baselines in the same environment CI uses: run the update inside the official Docker image (Chapter 12) on your Mac, or have a CI job run --update-snapshots and commit or upload the result. The docs put it plainly: run the tests in the same environment the baselines were made in.
  4. The name pattern is configurable with snapshotPathTemplate in the config (tokens such as {testFilePath}, {arg}, {projectName}, {platform}, {ext}). Teams that only ever compare on Linux sometimes drop {platform} so there's one baseline per browser.

#Why visual tests flake and how to steady them

Added

A screenshot captures everything that affects pixels, not just your code: the fonts the machine has, how the GPU or software renderer draws edges, today's date, the time zone, the data the API returned, whether an animation was half-way through, where the mouse was resting. Any of those can differ between two runs of the same commit, and a visual test fails just the same as for a real bug. A team that sees three false alarms stops reading the fourth.

The mental model: a passport photo. The booth controls everything that isn't your face: plain background, fixed lighting, neutral expression, no hat. A good visual test does the same: freeze everything except what you're testing.

CauseWhat you seeSteady it with
Fonts and OS renderingevery text edge differs on CIbaselines made in the CI's Docker image; one platform for visual tests
Time and dates"Estimated delivery" differs each daypage.clock.setFixedTime(…), a fixed timezoneId, or mask
Animations and transitionsa frame caught mid-moveanimations: "disabled" (the default for toHaveScreenshot)
The blinking careta cursor in a focused fieldcaret: "hide" (the default)
Data that changesnew products, other users' namesfixed test data or a mocked API (Chapter 9), mask
Hover and focusa highlighted buttonmove the mouse away (page.mouse.move(-1, -1)), blur
Loading statesa spinner in the baselinewait for the real content first (toHaveCount, toBeVisible)

The Practice Shop's order confirmation shows "Estimated delivery", computed from today's date plus four days, in the browser's time zone. That's a visual test that would pass today and fail tomorrow. This suite proves it, then steadies it two ways:

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

test.use({ timezoneId: "America/Toronto" }); // the date must not depend on where the test runs

async function placeOrderOn(page: Page, when: string) {
  await page.clock.setFixedTime(when); // Date.now() always returns this; timers keep running
  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.goto("/practice/checkout");
  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();
  await page.getByRole("button", { name: "Place order" }).click();
  await expect(page.getByRole("heading", { name: "Thank you, Rohit!" })).toBeVisible();
}
const confirmation = (page: Page) => page.getByRole("main");

test("confirmation, ordered on 24 November @baseline", async ({ page }) => {
  await placeOrderOn(page, "2026-11-24T10:00:00-05:00");
  await expect(page.getByTestId("delivery-estimate")).toHaveText("Estimated delivery: Saturday, November 28");
  await expect(confirmation(page)).toHaveScreenshot("confirmation.png");
});

test("the same order placed a day later", async ({ page }) => {
  await placeOrderOn(page, "2026-11-25T10:00:00-05:00");
  await expect(confirmation(page)).toHaveScreenshot("confirmation.png");
});

test("a day later, with the date masked", async ({ page }) => {
  await placeOrderOn(page, "2026-11-25T10:00:00-05:00");
  await expect(confirmation(page)).toHaveScreenshot("confirmation-masked.png", { mask: [page.getByTestId("delivery-estimate")] });
});

test("the masked baseline @baseline", async ({ page }) => {
  await placeOrderOn(page, "2026-11-24T10:00:00-05:00");
  await expect(confirmation(page)).toHaveScreenshot("confirmation-masked.png", { mask: [page.getByTestId("delivery-estimate")] });
});
npx playwright test --update-snapshots --grep @baseline
Running 2 tests using 1 worker

A snapshot doesn't exist at <project>/tests/confirmation.spec.ts-snapshots/confirmation-chromium-darwin.png, writing actual.
  ✓  1 [chromium] › tests/confirmation.spec.ts:21:1 › confirmation, ordered on 24 November @baseline (3.2s)
A snapshot doesn't exist at <project>/tests/confirmation.spec.ts-snapshots/confirmation-masked-chromium-darwin.png, writing actual.
  ✓  2 [chromium] › tests/confirmation.spec.ts:37:1 › the masked baseline @baseline (3.2s)

  2 passed (6.9s)
npx playwright test
Running 4 tests using 1 worker

  ✓  1 [chromium] › tests/confirmation.spec.ts:21:1 › confirmation, ordered on 24 November @baseline (3.0s)
  ✘  2 [chromium] › tests/confirmation.spec.ts:27:1 › the same order placed a day later (3.3s)
  ✓  3 [chromium] › tests/confirmation.spec.ts:32:1 › a day later, with the date masked (3.1s)
  ✓  4 [chromium] › tests/confirmation.spec.ts:37:1 › the masked baseline @baseline (3.0s)


  1) [chromium] › tests/confirmation.spec.ts:27:1 › the same order placed a day later ──────────────

    Error: expect(locator).toHaveScreenshot(expected) failed

    Locator: getByRole('main')
      1135 pixels (ratio 0.01 of all image pixels) are different.

      Snapshot: confirmation.png

    Call log:
      - Expect "toHaveScreenshot(confirmation.png)" getByRole('main') with timeout 5000ms
        - verifying given screenshot expectation
      - waiting for getByRole('main')
        - locator resolved to <main>…</main>
      - taking element screenshot
        - disabled all CSS animations
      - waiting for fonts to load...
      - fonts loaded
      - attempting scroll into view action
        - waiting for element to be stable
      - 1135 pixels (ratio 0.01 of all image pixels) are different.
      - waiting 100ms before taking screenshot
      - waiting for getByRole('main')
        - locator resolved to <main>…</main>
      - taking element screenshot
        - disabled all CSS animations
      - waiting for fonts to load...
      - fonts loaded
      - attempting scroll into view action
        - waiting for element to be stable
      - captured a stable screenshot
      - 1135 pixels (ratio 0.01 of all image pixels) are different.


      27 | test("the same order placed a day later", async ({ page }) => {
      28 |   await placeOrderOn(page, "2026-11-25T10:00:00-05:00");
    > 29 |   await expect(confirmation(page)).toHaveScreenshot("confirmation.png");
         |                                    ^
      30 | });
      31 |
      32 | test("a day later, with the date masked", async ({ page }) => {
        at <project>/tests/confirmation.spec.ts:29:36

    attachment #1: confirmation (image/png) ────────────────────────────────────────────────────────
    Expected: tests/confirmation.spec.ts-snapshots/confirmation-chromium-darwin.png
    Received: test-results/confirmation-the-same-order-placed-a-day-later-chromium/confirmation-actual.png
    Diff:     test-results/confirmation-the-same-order-placed-a-day-later-chromium/confirmation-diff.png
    ────────────────────────────────────────────────────────────────────────────────────────────────

    Error Context: test-results/confirmation-the-same-order-placed-a-day-later-chromium/error-context.md

  1 failed
    [chromium] › tests/confirmation.spec.ts:27:1 › the same order placed a day later ───────────────
  3 passed (13.2s)
What’s happening
  1. page.clock.setFixedTime("2026-11-24T10:00:00-05:00") makes Date.now() and new Date() in the page always return that moment, while timers (the shop's 500 ms sign-in, 1.2 s "placing order") keep running normally. It must come before the page loads, so the shop's own code sees the fake time from its first line.
  2. test.use({ timezoneId: "America/Toronto" }) fixes the browser's time zone. Without it, the shop formats the date in whatever zone the machine is in, and a CI runner in UTC could show a different day from a laptop in Toronto for the same instant.
  3. The @baseline run records two baselines on 24 November: the full confirmation ("Saturday, November 28") and the masked one. The first test also asserts the text, so the baseline is known to be right, not just recorded.
  4. "The same order placed a day later" fails: it's the identical page except the date now reads Sunday, November 29, and that one line is enough to change pixels. This is exactly what an unsteady visual test does on a real calendar, except here the clock made it happen on demand.
  5. The masked test, also a day later, passes: the estimate is under the pink box in both the baseline and the new screenshot. So you have two honest choices: fix the time when the date is part of what you're checking, or mask it when it isn't.
  6. Order matters inside the clock API (it must be set up before other clock calls and before the page loads); the clock gets its own topic in Chapter 11, including the version that also fakes timers.
AdvancedAnimations are already off in toHaveScreenshot

Animations: why toHaveScreenshot doesn't need you to turn them off

toHaveScreenshot disables CSS animations by default (the call log above says "disabled all CSS animations"). Plain page.screenshot(), used for attaching pictures to reports, doesn't. This test adds a spinning heading and compares raw screenshots:

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

test("animations make two screenshots differ, unless disabled", async ({ page }) => {
  await page.goto("/practice/");
  await page.addStyleTag({ content: "@keyframes spin { to { transform: rotate(360deg); } } h1 { display: inline-block; animation: spin 2s linear infinite; }" });

  const first = await page.screenshot();
  await page.waitForTimeout(200); // only to let the animation move; never do this in a real test
  const second = await page.screenshot();
  const stillA = await page.screenshot({ animations: "disabled" });
  await page.waitForTimeout(200);
  const stillB = await page.screenshot({ animations: "disabled" });

  console.log(`page.screenshot() twice, 200 ms apart: ${first.equals(second) ? "identical" : "different"}`);
  console.log(`with animations: "disabled": ${stillA.equals(stillB) ? "identical" : "different"}`);
  expect(first.equals(second)).toBe(false);
  expect(stillA.equals(stillB)).toBe(true);
});
npx playwright test
Running 1 test using 1 worker

page.screenshot() twice, 200 ms apart: different
with animations: "disabled": identical
  ✓  1 [chromium] › tests/animations.spec.ts:3:1 › animations make two screenshots differ, unless disabled (651ms)

  1 passed (1.2s)
What’s happening
  1. The injected CSS spins the "Sign in" heading forever, like a loading indicator or a marketing banner would.
  2. Two plain page.screenshot() calls 200 ms apart catch the heading at different angles, so the images differ. A visual test built on that would fail at random.
  3. With animations: "disabled", Playwright resets infinite animations to their starting state while it captures (and jumps finite ones to their end), so both images are identical.
  4. toHaveScreenshot does this by default, which is why the shop's visual tests above never needed the option. You'd only pass animations: "allow" when the animation itself is what you're testing, and even then a screenshot is rarely the right tool.

#Aria snapshots

Added

Between "check one fact" and "compare every pixel" there's a useful middle: compare the page's structure as assistive technology sees it. An aria snapshot is the accessibility tree written as YAML: each line is a role and an accessible name (- button "Add to cart" [disabled]), indented to show nesting. toMatchAriaSnapshot compares part of the page with a YAML template.

It catches what screenshots catch about content and structure (a heading changed, a button disappeared, a product lost its "Sold out" label, a button is no longer disabled) without any of the pixel noise: fonts, colours and the OS don't appear in the tree at all. And it catches what single assertions miss, because one template checks a whole block at once. The template is also partial by default: list only what matters, in order, and extra elements are allowed.

The mental model: the floor plan, not the photo. A photo of a room changes with the light; the floor plan says there's a door here, two windows there, and doesn't care what colour the walls are.

This test pins down the sold-out product's card, then runs the same check against a shop whose API (mocked with page.route, Chapter 9) wrongly says everything is in stock:

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

async function openShop(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();
}
const verticalMouse = (page: Page) => page.getByRole("listitem").filter({ hasText: "Vertical Mouse" });
const soldOutCard = `
  - listitem:
    - heading "Vertical Mouse" [level=2]
    - paragraph: Sold out
    - button "Add to cart" [disabled]
`;

test("the sold-out product is marked and can't be added", async ({ page }) => {
  await openShop(page);
  await expect(verticalMouse(page)).toMatchAriaSnapshot(soldOutCard);
});

test("the same check, when the API says everything is in stock", async ({ page }) => {
  await page.route("**/api/products.json", async (route) => {
    const products = await (await route.fetch()).json();
    for (const p of products) p.stock = 5; // the bug: stock never reaches 0
    await route.fulfill({ json: products });
  });
  await openShop(page);
  await expect(verticalMouse(page)).toMatchAriaSnapshot(soldOutCard, { timeout: 2000 });
});
npx playwright test
Running 2 tests using 1 worker

  ✓  1 [chromium] › tests/sold-out.spec.ts:17:1 › the sold-out product is marked and can't be added (1.5s)
  ✘  2 [chromium] › tests/sold-out.spec.ts:22:1 › the same check, when the API says everything is in stock (2.2s)


  1) [chromium] › tests/sold-out.spec.ts:22:1 › the same check, when the API says everything is in stock 

    Error: expect(locator).toMatchAriaSnapshot(expected) failed

    Locator: getByRole('listitem').filter({ hasText: 'Vertical Mouse' })
    Timeout: 2000ms
    - Expected  - 2
    + Received  + 3

      - listitem:
        - heading "Vertical Mouse" [level=2]
    -   - paragraph: Sold out
    +   - paragraph: Mice
    +   - paragraph: $45.00
    -   - button "Add to cart" [disabled]
    +   - button "Add to cart"

    Call log:
      - Expect "toMatchAriaSnapshot" getByRole('listitem').filter({ hasText: 'Vertical Mouse' }) with timeout 2000ms
      - waiting for getByRole('listitem').filter({ hasText: 'Vertical Mouse' })
        7 × locator resolved to <li class="product" data-testid="product-ms-02">…</li>
          - unexpected value "- listitem:
      - heading "Vertical Mouse" [level=2]
      - paragraph: Mice
      - paragraph: $45.00
      - button "Add to cart""


      27 |   });
      28 |   await openShop(page);
    > 29 |   await expect(verticalMouse(page)).toMatchAriaSnapshot(soldOutCard, { timeout: 2000 });
         |                                     ^
      30 | });
      31 |
        at <project>/tests/sold-out.spec.ts:29:37

    Error Context: test-results/sold-out-the-same-check-wh-1f2b2-says-everything-is-in-stock-chromium/error-context.md

  1 failed
    [chromium] › tests/sold-out.spec.ts:22:1 › the same check, when the API says everything is in stock 
  1 passed (4.3s)
What’s happening
  1. The template says: a list item containing a level-2 heading "Vertical Mouse", a paragraph "Sold out", and a disabled "Add to cart" button, in that order. It doesn't mention the category or the price paragraphs; partial matching lets the real card have them.
  2. On the real shop the card matches, so the first test passes. One assertion has checked the name, the label and the disabled state together.
  3. In the second test the mocked API sets every stock to 5, so the shop renders the Vertical Mouse like any other product. The assertion retries like every web-first assertion, then fails after 2 seconds.
  4. The diff is the useful part: - paragraph: Sold out and - button "Add to cart" [disabled] are expected but missing; the received card has the category, the price and an enabled button. You can read the bug straight off the failure: the product is buyable.
  5. A screenshot would also have failed here, but with a count of changed pixels and an image to look at. A single toBeDisabled() would have caught the button but not the missing label. The aria snapshot names both, in words.
AdvancedGetting the YAML: ariaSnapshot() and stored snapshot files

You rarely write templates from scratch. locator.ariaSnapshot() returns the YAML for any part of the page, and page.ariaSnapshot() (1.59+) for the whole page. And instead of an inline template, toMatchAriaSnapshot({ name }) stores the snapshot in a .aria.yml file that --update-snapshots writes for you, just like a screenshot baseline. expect(page).toMatchAriaSnapshot() (1.60+) checks the whole page.

tests/structure.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();
  await expect(page.getByRole("listitem")).toHaveCount(8);
}

test("print the header's aria snapshot", async ({ page }) => {
  await signIn(page);
  console.log(await page.getByRole("banner").ariaSnapshot());
});

test("the checkout form's structure", async ({ page }) => {
  await signIn(page);
  await page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).click();
  await page.goto("/practice/checkout");
  await expect(page.getByRole("main")).toMatchAriaSnapshot({ name: "checkout.aria.yml" });
});
npx playwright test --update-snapshots
Running 2 tests using 1 worker

- banner:
  - link "Practice Shop":
    - /url: /practice/shop
  - text: Signed in as rohit
  - link "Account":
    - /url: /practice/account
  - link "Cart (0)":
    - /url: /practice/cart
  - button "Log out"
  ✓  1 [chromium] › tests/structure.spec.ts:11:1 › print the header's aria snapshot (1.5s)
A snapshot is generated at tests/structure.spec.ts-snapshots/checkout.aria.yml.
  ✓  2 [chromium] › tests/structure.spec.ts:16:1 › the checkout form's structure (6.5s)

  2 passed (8.6s)
show-file.mjs
// Prints a file, so the page shows exactly what --update-snapshots wrote.
import { readFileSync } from "node:fs";
console.log(readFileSync(process.argv[2], "utf8").trimEnd());
node show-file.mjs tests/structure.spec.ts-snapshots/checkout.aria.yml
- main:
  - heading "Checkout" [level=1]
  - text: Full name
  - textbox "Full name": Rohit
  - text: Email
  - textbox "Email"
  - text: Delivery address
  - textbox "Delivery address"
  - text: Promo code
  - textbox "Promo code"
  - button "Apply"
  - paragraph
  - group "Delivery":
    - text: ""
    - radio "Standard (3–5 days, free)" [checked]
    - text: Standard (3–5 days, free)
    - radio /Express \(next day, \$\d+\.\d+\)/
    - text: /Express \(next day, \$\d+\.\d+\)/
  - checkbox "I agree to the terms"
  - text: I agree to the terms
  - paragraph: "Payment: you pay on delivery. This practice shop never asks for card details."
  - button "Place order"
  - complementary "Order summary":
    - heading "Order summary" [level=2]
    - text: /Wireless Mouse × 1 \$\d+\.\d+ Delivery Free Total \$\d+\.\d+/
What’s happening
  1. The first test prints the header's tree: the brand link with its /url, the "Signed in as rohit" text, the Account and Cart links and the Log out button. That's how you find out what roles and names a page really exposes, and it's the quickest way to start a template: print, copy, delete what you don't care about.
  2. The second test has no template yet. With --update-snapshots, Playwright writes the current structure of main to tests/structure.spec.ts-snapshots/checkout.aria.yml ("A snapshot is generated at …") and passes. (Without the flag, a missing snapshot is written and the test fails, like a missing screenshot baseline.)
  3. Look at the stored file: Playwright generalised the numbers into regular expressions. The price in the summary became \$\d+\.\d+ and the express fee inside "Express (next day, $9.99)" too, so a price change won't break a structure test. Names in quotes match exactly; names in /slashes/ are regexes.
  4. The file is a reviewable artifact: commit it, and when a pull request changes the checkout form, the diff of checkout.aria.yml shows the change in words ("a Promo code textbox appeared") rather than as an image.
  5. Notice what the tree leaves out: no classes, no colours, no layout. Two very different-looking pages can have the same aria snapshot, so it complements a screenshot rather than replacing it.
AdvancedThe template syntax in one table

From the 1.65 aria snapshot docs:

TemplateMatches
- buttonany button, any name
- button "Place order"a button named exactly "Place order" (case-sensitive, whitespace normalised)
- heading /Thank you, .+!/a heading whose name matches the regex
- heading "Products" [level=1]with an attribute; others are checked, disabled, expanded, pressed, selected
- link "Account": then - /url: /practice/accounta link and its destination
- paragraph: Sold outan element and its text content
- text: Signed in as rohita plain text node
- list: then - /children: equalthe list must have exactly these children, no extras (contain is the default; deep-equal applies it at every level)

Order matters: siblings must appear in the order written.

#Accessibility checks with axe

Added

Accessibility means people can use the app with a screen reader, a keyboard only, high zoom, or low vision. A lot of it can't be checked automatically, but a useful slice can: images without alt text, inputs without labels, text with too little contrast, buttons with no accessible name, ARIA attributes used wrongly. axe-core is the standard engine for those rules, and @axe-core/playwright runs it inside a Playwright page (npm i -D @axe-core/playwright).

new AxeBuilder({ page }).analyze() scans the page as it is at that moment and returns violations (rules that failed, with the elements), passes, and incomplete (things axe couldn't decide and a human must check). You narrow it with .withTags([...]) (the WCAG level), .include(selector) / .exclude(selector), and .disableRules([...]).

The mental model: a spell checker. It reliably finds misspelled words and some grammar slips, and it's silly not to run it. It can't tell you whether the essay makes sense. axe finds missing labels and bad contrast; it can't tell you whether the labels are true or the page is usable.

Here are the shop's main pages, checked against the WCAG 2.0 and 2.1 A and AA rules (the tags the Playwright docs recommend), including the checkout in its error state:

tests/a11y.spec.ts
import { test, expect, type Page } from "@playwright/test";
import AxeBuilder from "@axe-core/playwright";

const WCAG_AA = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"];

async function signInWithCart(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();
  await page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).click();
}
async function expectNoViolations(page: Page) {
  const results = await new AxeBuilder({ page }).withTags(WCAG_AA).analyze();
  expect(results.violations.map((v) => ({ rule: v.id, targets: v.nodes.map((n) => n.target.join(" ")) }))).toEqual([]);
}

test("sign-in page", async ({ page }) => {
  await page.goto("/practice/");
  await expectNoViolations(page);
});

test("product list, with the toast showing", async ({ page }) => {
  await signInWithCart(page);
  await expect(page.getByRole("status").filter({ hasText: "Added" })).toBeVisible();
  await expectNoViolations(page);
});

test("cart", async ({ page }) => {
  await signInWithCart(page);
  await page.goto("/practice/cart");
  await expect(page.getByRole("table")).toBeVisible();
  await expectNoViolations(page);
});

test("checkout, after submitting it empty", async ({ page }) => {
  await signInWithCart(page);
  await page.goto("/practice/checkout");
  await page.getByLabel("Full name").clear();
  await page.getByRole("button", { name: "Place order" }).click();
  await expect(page.getByRole("alert")).toHaveText("Please fix 4 problems before placing your order.");
  await expectNoViolations(page);
});

test("account page (with the chat iframe and the shadow-DOM newsletter box)", async ({ page }) => {
  await signInWithCart(page);
  await page.goto("/practice/account");
  await expect(page.frameLocator('iframe[title="Support chat"]').getByRole("button", { name: "Send" })).toBeVisible();
  await expectNoViolations(page);
});
npx playwright test
Running 5 tests using 1 worker

  ✓  1 [chromium] › tests/a11y.spec.ts:18:1 › sign-in page (328ms)
  ✓  2 [chromium] › tests/a11y.spec.ts:23:1 › product list, with the toast showing (1.8s)
  ✓  3 [chromium] › tests/a11y.spec.ts:29:1 › cart (1.8s)
  ✓  4 [chromium] › tests/a11y.spec.ts:36:1 › checkout, after submitting it empty (1.9s)
  ✓  5 [chromium] › tests/a11y.spec.ts:45:1 › account page (with the chat iframe and the shadow-DOM newsletter box) (2.0s)

  5 passed (8.3s)
What’s happening
  1. Each test first gets the page into the state worth checking: the toast visible, the cart table rendered, the checkout's four error messages shown, the chat iframe loaded. axe checks only what's on the page when analyze() runs, so a scan of the empty form says nothing about the error state.
  2. withTags(WCAG_AA) limits the scan to rules mapped to WCAG 2.0/2.1 levels A and AA, the level most laws and contracts ask for. Without tags, axe also runs its "best practice" rules (below).
  3. expectNoViolations maps each violation to its rule id and the elements' selectors before asserting. The Playwright docs recommend this kind of fingerprint over comparing the raw violations array, which contains HTML snippets that change for unrelated reasons; and when it fails, the diff is short and readable.
  4. All five pass: with the WCAG A/AA rules, axe 4.14 found no violations on these pages of the shop, including the iframe (axe scans frames) and the open shadow root. That's a real result, but read it carefully: it means "nothing axe can detect", not "accessible". The next two examples show the difference.
AdvancedBest-practice rules: the shop's real findings

Best-practice rules and "needs review": the shop's real findings

Running all of axe's rules (no withTags) adds best-practice checks that aren't strictly WCAG failures. On the shop they do find things. This suite reports them honestly rather than hiding them: the first two tests fail on purpose to show the findings, and the third prints what axe marked incomplete.

tests/best-practice.spec.ts
import { test, expect, type Page } from "@playwright/test";
import AxeBuilder from "@axe-core/playwright";

async function signInWithCart(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();
  await page.getByRole("listitem").filter({ hasText: "Wireless Mouse" }).getByRole("button", { name: "Add to cart" }).click();
}
const fingerprint = (results: Awaited<ReturnType<AxeBuilder["analyze"]>>) =>
  results.violations.map((v) => ({ rule: v.id, impact: v.impact, targets: v.nodes.map((n) => n.target.join(" ")) }));

test("cart, every rule", async ({ page }) => {
  await signInWithCart(page);
  await page.goto("/practice/cart");
  await expect(page.getByRole("table")).toBeVisible();
  expect(fingerprint(await new AxeBuilder({ page }).analyze())).toEqual([]);
});

test("account page, every rule", async ({ page }) => {
  await signInWithCart(page);
  await page.goto("/practice/account");
  await expect(page.frameLocator('iframe[title="Support chat"]').getByRole("button", { name: "Send" })).toBeVisible();
  expect(fingerprint(await new AxeBuilder({ page }).analyze())).toEqual([]);
});

test("cart: what axe couldn't decide", async ({ page }) => {
  await signInWithCart(page);
  await page.goto("/practice/cart");
  await expect(page.getByRole("table")).toBeVisible();
  const { incomplete } = await new AxeBuilder({ page }).analyze();
  for (const item of incomplete) console.log(`needs review: ${item.id} on ${item.nodes.map((n) => n.target.join(" ")).join(", ")}`);
});
npx playwright test
Running 3 tests using 1 worker

  ✘  1 [chromium] › tests/best-practice.spec.ts:14:1 › cart, every rule (1.9s)
  ✘  2 [chromium] › tests/best-practice.spec.ts:21:1 › account page, every rule (2.2s)
needs review: color-contrast on button[data-dec="ms-01"]
needs review: label-content-name-mismatch on button[data-dec="ms-01"], button[data-inc="ms-01"]
  ✓  3 [chromium] › tests/best-practice.spec.ts:28:1 › cart: what axe couldn't decide (2.0s)


  1) [chromium] › tests/best-practice.spec.ts:14:1 › cart, every rule ──────────────────────────────

    Error: expect(received).toEqual(expected) // deep equality

    - Expected  - 1
    + Received  + 9

    - Array []
    + Array [
    +   Object {
    +     "impact": "minor",
    +     "rule": "empty-table-header",
    +     "targets": Array [
    +       "th[scope=\"col\"]:nth-child(5)",
    +     ],
    +   },
    + ]

      16 |   await page.goto("/practice/cart");
      17 |   await expect(page.getByRole("table")).toBeVisible();
    > 18 |   expect(fingerprint(await new AxeBuilder({ page }).analyze())).toEqual([]);
         |                                                                 ^
      19 | });
      20 |
      21 | test("account page, every rule", async ({ page }) => {
        at <project>/tests/best-practice.spec.ts:18:65

    Error Context: test-results/best-practice-cart-every-rule-chromium/error-context.md

  2) [chromium] › tests/best-practice.spec.ts:21:1 › account page, every rule ──────────────────────

    Error: expect(received).toEqual(expected) // deep equality

    - Expected  - 1
    + Received  + 9

    - Array []
    + Array [
    +   Object {
    +     "impact": "moderate",
    +     "rule": "landmark-unique",
    +     "targets": Array [
    +       "main",
    +     ],
    +   },
    + ]

      23 |   await page.goto("/practice/account");
      24 |   await expect(page.frameLocator('iframe[title="Support chat"]').getByRole("button", { name: "Send" })).toBeVisible();
    > 25 |   expect(fingerprint(await new AxeBuilder({ page }).analyze())).toEqual([]);
         |                                                                 ^
      26 | });
      27 |
      28 | test("cart: what axe couldn't decide", async ({ page }) => {
        at <project>/tests/best-practice.spec.ts:25:65

    Error Context: test-results/best-practice-account-page-every-rule-chromium/error-context.md

  2 failed
    [chromium] › tests/best-practice.spec.ts:14:1 › cart, every rule ───────────────────────────────
    [chromium] › tests/best-practice.spec.ts:21:1 › account page, every rule ───────────────────────
  1 passed (7.8s)
What’s happening
  1. Cart: empty-table-header (minor). The cart's last column header is <th><span hidden>Remove</span></th>. hidden removes the text for everyone, screen readers included, so the header is empty. The aria snapshot earlier in this chapter showed the same thing as a bare - columnheader with no name. The fix in the shop would be visually-hidden text (a .sr-only class) instead of hidden. It's best practice, not a WCAG failure, which is why the WCAG-tagged scan passed.
  2. Account: landmark-unique (moderate). axe scans the support chat iframe too, and the chat page has its own <main>, so the account page ends up with two main landmarks with no names to tell them apart. Giving one an aria-label (or not using main inside the embedded chat) fixes it.
  3. Needs review on the cart: color-contrast and label-content-name-mismatch on the − and + buttons. Their visible text is a single symbol and their accessible names are "Decrease quantity of Wireless Mouse" and so on. axe can't compute contrast for a lone symbol or decide whether "−" is "part of" that name, so it hands both to a human. incomplete is easy to ignore and shouldn't be: it's axe telling you where its knowledge ends.
  4. These are the shop's real findings with axe-core 4.14, left in the shop as they are. In a real project you'd fix them, or, if a fix must wait, disable exactly that rule for exactly that page with a ticket link (.disableRules(["empty-table-header"])), never exclude the whole region: exclude turns off every rule for those elements.
AdvancedWhat axe can't catch, demonstrated

axe checks that a field has a label, not that the label is true. This test breaks the checkout so the "Email" and "Delivery address" labels point at each other's fields, then runs the same WCAG scan:

tests/lying-labels.spec.ts
import { test, expect } from "@playwright/test";
import AxeBuilder from "@axe-core/playwright";

test("axe passes a form whose labels lie", async ({ page }) => {
  // The bug: the Email label points at the address box, and the address label at the email field.
  await page.addInitScript(() => {
    document.addEventListener("DOMContentLoaded", () => {
      const email = document.querySelector('label[for="email"]');
      const address = document.querySelector('label[for="address"]');
      email?.setAttribute("for", "address");
      address?.setAttribute("for", "email");
    });
  });
  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.goto("/practice/checkout");

  const results = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]).analyze();
  console.log(`axe violations: ${results.violations.length}`);
  expect(results.violations).toEqual([]);

  // A user (or a test) looking for the email field by its label gets the address box.
  await expect(page.getByLabel("Email")).toHaveAttribute("type", "email", { timeout: 2000 });
});
npx playwright test
Running 1 test using 1 worker

axe violations: 0
  ✘  1 [chromium] › tests/lying-labels.spec.ts:4:1 › axe passes a form whose labels lie (4.0s)


  1) [chromium] › tests/lying-labels.spec.ts:4:1 › axe passes a form whose labels lie ──────────────

    Error: expect(locator).toHaveAttribute(expected) failed

    Locator:  getByLabel('Email')
    Expected: "email"
    Received: ""
    Timeout:  2000ms

    Call log:
      - Expect "toHaveAttribute" getByLabel('Email') with timeout 2000ms
      - waiting for getByLabel('Email')
        21 × locator resolved to <textarea rows="3" id="address" name="address" aria-describedby="address-error"></textarea>
           - unexpected value "null"


      24 |
      25 |   // A user (or a test) looking for the email field by its label gets the address box.
    > 26 |   await expect(page.getByLabel("Email")).toHaveAttribute("type", "email", { timeout: 2000 });
         |                                          ^
      27 | });
      28 |
        at <project>/tests/lying-labels.spec.ts:26:42

    Error Context: test-results/lying-labels-axe-passes-a-form-whose-labels-lie-chromium/error-context.md

  1 failed
    [chromium] › tests/lying-labels.spec.ts:4:1 › axe passes a form whose labels lie ───────────────
What’s happening
  1. addInitScript runs in every page before the shop's code; on DOMContentLoaded it swaps the two labels' for attributes, so "Email" now labels the address textarea and "Delivery address" labels the email input. Both labels are found before either is changed, so the swap is clean.
  2. axe reports 0 violations: every field still has exactly one label, and that's all the label rule can check.
  3. The very next check fails: getByLabel("Email") finds the textarea, which has no type="email". A screen-reader user hears "Email, edit text" and types their address into the delivery box. That's an accessibility bug no rule engine can see, and your functional tests using getByLabel catch it for free, which is one more reason to prefer role and label locators (Chapter 4).
  4. Other things automated checks miss: whether keyboard focus moves somewhere sensible after an action, whether the tab order makes sense, whether a modal traps focus correctly, whether alt text actually describes the image, whether error messages are understandable, whether content works at 400% zoom, and whether a screen reader announces a change at the right moment. The Playwright docs say it directly: automated tests catch common problems such as missing or invalid properties, and many problems can only be found by manual testing.
AdvancedMaking axe part of the suite without making it noisy

Practical guidance for real projects:

  • Share the setup in a fixture (the docs' pattern): a makeAxeBuilder fixture that returns new AxeBuilder({ page }).withTags([...]) with any project-wide exclusions, so every test scans the same way (Chapter 7 covers fixtures).
  • Scan states, not just pages: the open menu, the modal, the form with errors, the empty cart. A scan per important state is cheap (a few hundred milliseconds).
  • Attach the full results to the report with testInfo.attach("accessibility-scan-results", { body: JSON.stringify(results, null, 2), contentType: "application/json" }), so a failure on CI comes with everything axe saw.
  • Existing app with many findings? Snapshot the fingerprints (rule + targets) with toMatchSnapshot, so the build fails on new violations while the backlog is fixed, instead of disabling the check.
  • Keep the manual part: keyboard-only walkthroughs of the critical journeys, a screen-reader pass before big releases, and real users with disabilities when you can. Accessibility Insights for Web (which the Playwright docs point to) guides the manual checks.

#Your turn: check the shop's looks and structure

Added
Your turn: a visual test of the cart that works for any user

Write a visual test of the cart table with two products in it. Sign in as Rohit for the baseline, and make sure the same test signed in as Ana compares against the same baseline and passes. Don't screenshot the whole page.

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

async function cartWithTwoProducts(page: Page, username: string) {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill(username);
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  for (const name of ["Compact Keyboard", "Monitor Light Bar"]) {
    await page.getByRole("listitem").filter({ hasText: name }).getByRole("button", { name: "Add to cart" }).click();
  }
  await page.getByRole("link", { name: "Cart (2)" }).click();
  await expect(page.getByTestId("cart-total")).toHaveText("$108.00");
}

for (const username of ["rohit", "ana"]) {
  test(`the cart table looks right for ${username}`, async ({ page }) => {
    await cartWithTwoProducts(page, username);
    await expect(page.getByRole("table", { name: "Your cart" })).toHaveScreenshot("cart-table.png");
  });
}
npx playwright test --update-snapshots --grep rohit
Running 1 test using 1 worker

A snapshot doesn't exist at <project>/tests/cart-visual.spec.ts-snapshots/cart-table-chromium-darwin.png, writing actual.
  ✓  1 [chromium] › tests/cart-visual.spec.ts:16:3 › the cart table looks right for rohit (1.8s)

  1 passed (2.3s)
npx playwright test
Running 2 tests using 1 worker

  ✓  1 [chromium] › tests/cart-visual.spec.ts:16:3 › the cart table looks right for rohit (1.6s)
  ✓  2 [chromium] › tests/cart-visual.spec.ts:16:3 › the cart table looks right for ana (1.6s)

  2 passed (3.5s)
What’s happening
  1. The arrange helper adds two products and waits for the total ($59.00 + $49.00 = $108.00), so the screenshot is never taken of a half-rendered table.
  2. The screenshot is of the table only. The user's name lives in the header, outside the table, so there's nothing to mask: choosing a tight element is often better than masking.
  3. Both tests use the name cart-table.png, so they share one baseline: the --grep rohit update makes it from Rohit's cart, and the normal run checks both users against it. Both pass because the table doesn't depend on who's signed in.
  4. If you had screenshotted the whole page, Ana's run would fail on "Signed in as ana", and you'd need a mask over the name, plus a fixed-width box for it, as in the masking example.
Your turn: pin down the checkout's error state with an aria snapshot

Submit the checkout with the name cleared and nothing else filled in, then check the error summary and the four field errors with one toMatchAriaSnapshot on the form. Keep the template partial: only what proves the errors are shown.

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

test("an empty checkout shows every error", async ({ page }) => {
  await page.goto("/practice/");
  await page.getByLabel("Username").fill("ana");
  await page.getByLabel("Password").fill("playwright");
  await page.getByRole("button", { name: "Sign in" }).click();
  await page.getByRole("listitem").filter({ hasText: "USB Microphone" }).getByRole("button", { name: "Add to cart" }).click();
  await page.goto("/practice/checkout");
  await page.getByLabel("Full name").clear();

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

  await expect(page.locator("#checkout")).toMatchAriaSnapshot(`
    - alert: Please fix 4 problems before placing your order.
    - textbox "Full name"
    - paragraph: Enter your full name.
    - textbox "Email"
    - paragraph: Enter your email.
    - textbox "Delivery address"
    - paragraph: Enter your full delivery address.
    - checkbox "I agree to the terms"
    - paragraph: You must agree to the terms.
    - button "Place order"
  `);
});
npx playwright test
Running 1 test using 1 worker

  ✓  1 [chromium] › tests/checkout-errors.spec.ts:3:1 › an empty checkout shows every error (1.5s)

  1 passed (2.0s)
What’s happening
  1. Clearing "Full name" (the shop pre-fills it) and submitting triggers all four validation rules, so the alert reads "Please fix 4 problems before placing your order."
  2. The template lists the alert first, then each field followed by its error paragraph, then the button, in page order. Order is checked, so this also proves each error sits right after its own field.
  3. It's partial: the labels' text nodes, the promo code box, the delivery radios and the payment note are all left out, and the match still passes because the default mode is contain.
  4. page.locator("#checkout") scopes it to the form. (A form only gets the form role when it has an accessible name, so a role locator wouldn't find this one; the id is the honest choice here.) Compared with nine separate assertions, the template reads like the screen and fails with a diff that shows which error went missing.
Your turn: an axe scan of the order confirmation

Write a test that places an order and runs axe with the WCAG A and AA tags on the confirmation page, attaching the full results to the report and asserting on a fingerprint of the violations.

Show answer
tests/confirmation-a11y.spec.ts
import { test, expect } from "@playwright/test";
import AxeBuilder from "@axe-core/playwright";

test("the order confirmation has no WCAG A/AA violations", async ({ page }, testInfo) => {
  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: "Standing Desk Mat" }).getByRole("button", { name: "Add to cart" }).click();
  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.getByLabel("I agree to the terms").check();
  await page.getByRole("button", { name: "Place order" }).click();
  await expect(page.getByRole("heading", { name: "Thank you, Rohit!" })).toBeVisible();

  const results = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]).analyze();
  await testInfo.attach("accessibility-scan-results", { body: JSON.stringify(results, null, 2), contentType: "application/json" });

  expect(results.violations.map((v) => ({ rule: v.id, targets: v.nodes.map((n) => n.target.join(" ")) }))).toEqual([]);
  console.log(`rules passed: ${results.passes.length}, violations: ${results.violations.length}`);
});
npx playwright test
Running 1 test using 1 worker

rules passed: 10, violations: 0
  ✓  1 [chromium] › tests/confirmation-a11y.spec.ts:4:1 › the order confirmation has no WCAG A/AA violations (3.1s)

  1 passed (3.6s)
What’s happening
  1. The test places a real order and waits for the thank-you heading, so axe scans the finished confirmation, not the "Placing order…" moment.
  2. testInfo.attach puts the whole result (passes, violations, incomplete) into the HTML report, so whoever investigates a failure on CI sees everything axe saw.
  3. The assertion uses the rule-and-selector fingerprint, so a failure prints a short, stable diff.
  4. The printed line shows how many rules passed and that there were 0 violations. As before, that means nothing axe can detect is wrong; it doesn't prove a screen-reader user can read the confirmation comfortably.

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.