Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readTesting

Snapshot page structure with ARIA snapshots

Use a Playwright ARIA snapshot to check navigation roles and link names while letting layout markup change.

You changed the class on a navigation bar, and the test reports a snapshot mismatch. The same two links still appear in the same order. If that is what the test needs to guarantee, snapshot the accessible structure with Playwright.

Scope the snapshot to the navigation

Save this as navigation.spec.ts in a Playwright Test 1.49 or later project with Chromium installed. The fixture uses inline HTML so you can run it without a server. In an app, replace page.setContent with navigation to the page you want to check.

import { expect, test } from '@playwright/test'

test('main navigation exposes the expected links', async ({ page }) => {
  await page.setContent(`
    <nav aria-label="Main" class="nav-grid">
      <a href="/tickets">Tickets</a>
      <a href="/venues">Venues</a>
    </nav>
  `)

  await expect(page.getByRole('navigation', { name: 'Main' }))
    .toMatchAriaSnapshot(`
      - navigation "Main":
        - link "Tickets"
        - link "Venues"
    `)
})

Run pnpm exec playwright test navigation.spec.ts and the test passes with both links under the named navigation.

Each line in the ARIA snapshot describes a role and, where supplied, an accessible name. The navigation role comes from nav. The navigation landmark gets its name from aria-label. The links get theirs from the text. The class nav-grid appears in the fixture without becoming a field in the assertion.

Change the class to nav-row and run it again. The assertion still passes. Change the text from Tickets to Buy now or replace the anchor with a plain span, and the expected link no longer matches. Use the failing diff to decide whether you meant to change what the navigation exposes.

Decide which details belong in the test

The default matching mode checks for the entries you list, in order. Swap the two anchors and the test fails. Add a Contact link between them and the test passes because Tickets and Venues still occur in that order. If the count is part of the contract, add a count assertion on the links inside the same navigation locator.

Write an assertion for the destination if that matters too. A link named Tickets can point at the wrong route and still match the YAML above. Assert its href or check the URL after clicking it.

Pick one existing markup snapshot for a form or navigation region and list which semantics it is supposed to protect. Start with that region and put its expected names and roles in YAML. Keep behavior checks for actions such as submitting the form or following a link.