Playwright Masters

Playwright Accessibility Testing: The Complete Guide (2026)

Playwright accessibility testing means using Playwright to check that a website works for everyone, including people who use screen readers, keyboards or zoom, or who have low vision. You do it in two ways: you run an automatic scanner called axe-core inside your Playwright tests, and you use Playwright’s built-in accessibility checks such as getByRole(), toHaveAccessibleName() and toMatchAriaSnapshot(). Together they find many accessibility bugs every time your code changes, before real users run into them.

Table of Contents

Who is this guide for? Testers, developers and students who already know some Playwright basics. If you are brand new, start with our Playwright Automation Testing Tutorial and then come back here.

Playwright Accessibility Testing

What Is Accessibility (A11y)?

Web accessibility means building websites that everyone can see, hear, understand and use, whatever their abilities. The short form “a11y” stands for the word “accessibility”: the letter a, then 11 letters, then the letter y.

Think of a school building. Stairs work for most students, but a ramp lets a student in a wheelchair come in too. Accessibility is the “ramp” for websites.

People who depend on accessible websites include:

  • Blind users, who listen to pages through screen readers such as NVDA, JAWS or VoiceOver.
  • Low-vision users, who zoom in to 200–400% or need strong colour contrast.
  • Colour-blind users, who cannot tell red from green, so colour alone must never carry meaning.
  • Users who can’t use a mouse, who move through the page using only the Tab, Enter, Space and arrow keys.
  • Deaf users, who need captions on videos.
  • Users with attention or learning differences, who need clear labels, simple layouts and no flashing motion.

The global rulebook for this is WCAG (Web Content Accessibility Guidelines). WCAG has four simple principles, remembered as POUR:

Principle

Simple meaning

Example check

Perceivable

Users can notice the content

Images have alt text

Operable

Users can control the page

Everything works with a keyboard

Understandable

Users can make sense of it

Form errors explain what went wrong

Robust

It works with assistive tools

Correct roles and labels for screen readers

Why Accessibility Testing Matters in 2026

Accessibility testing matters because inaccessible websites lock out real users, create legal risk and hurt search visibility.

  • More people are affected than you think. The World Health Organization estimates that about 1 in 6 people worldwide live with a significant disability.
  • Laws now require it. The European Accessibility Act has applied since June 2025. In the US, ADA lawsuits commonly cite WCAG 2.1 AA, and India’s Rights of Persons with Disabilities Act, 2016 covers digital accessibility for many organisations.
  • Accessible sites are easier for machines to read. Clear headings, labels and landmarks help search engines and AI assistants understand your pages.
  • Fixing early is cheaper. A missing label caught in a pull request takes 2 minutes to fix. The same bug found after launch can take days of meetings and fixes.
  • It’s a career skill. QA engineers who can automate accessibility checks stand out in interviews. Our Playwright Interview Questions guide shows how often modern testing roles expect broad automation skills.

What Playwright Can and Cannot Check

Playwright with axe-core can automatically catch rule-based problems, but it cannot judge whether a page is truly easy to use. That still needs a human.

What automated Playwright tests catch well:

  • Missing alt text on images
  • Form fields without labels
  • Text with too little colour contrast
  • Buttons and links with no readable name
  • Duplicate IDs on interactive elements
  • Invalid or misused ARIA attributes
  • Missing page language (<html lang>)
  • Skipped heading levels and missing landmarks
  • Keyboard focus that goes missing or gets stuck (with your own tests)

What still needs a human:

  • Whether alt text actually describes the image well
  • Whether reading order makes sense to a screen reader user
  • Whether error messages are clear and helpful
  • Whether captions match the video
  • How easy the whole journey feels for a disabled person

Deque, the company that makes axe-core, reports that automated axe scans find a little over half of accessibility issues by volume. Treat automation as your safety net, not your finish line.

The Two Ways to Test Accessibility in Playwright

Playwright accessibility testing works best when you combine a rule scanner (axe-core) with Playwright’s own role-based checks. Each catches problems the other misses.

Feature

axe-core scan

Playwright built-in checks

What it does

Checks the page against about 100 accessibility rules

Checks the specific roles, names and structure you expect

Install needed

Yes (@axe-core/playwright)

No, built into @playwright/test

Best for

Broad coverage: contrast, labels, ARIA errors

Exact behaviour: “this button must be named Pay now“

Example

new AxeBuilder({ page }).analyze()

toHaveAccessibleName(), toMatchAriaSnapshot()

Catches regressions

Yes, new rule violations

Yes, when structure or names change

Important update: The old page.accessibility.snapshot() method has been removed from Playwright after years of being deprecated. If an older tutorial shows it, use toMatchAriaSnapshot() and axe-core instead.

Setup: Install axe-core for Playwright

To add accessibility scanning, install the @axe-core/playwright package next to your existing Playwright project.

If Playwright isn’t installed yet, follow our How to Install Playwright guide first. Then run:

npm install –save-dev @axe-core/playwright

That’s it. One package, no browser plugin, no extra server.

Keep your accessibility tests easy to find by naming them like this:

tests/

  a11y/

    home.a11y.spec.ts

    checkout.a11y.spec.ts

  fixtures/

    a11y.ts

Your First Accessibility Test

A basic Playwright accessibility test opens a page, runs an axe scan, and expects zero violations.

// tests/a11y/home.a11y.spec.ts

import { test, expect } from ‘@playwright/test’;

import AxeBuilder from ‘@axe-core/playwright’;

 

test(‘home page has no automatically detectable accessibility issues’, async ({ page }) => {

  await page.goto(‘https://your-site.com/’);

 

  const results = await new AxeBuilder({ page }).analyze();

 

  expect(results.violations).toEqual([]);

});

What each line does, in plain words:

  1. page.goto() opens the page, like typing a web address.
  2. new AxeBuilder({ page }) gets the accessibility checker ready for this page.
  3. .analyze() runs every rule and collects the results.
  4. results.violations is the list of broken rules. An empty list means the scan passed.

Run it:

npx playwright test tests/a11y

Tip: axe checks the page exactly as it looks right now. If a menu, modal or tab is hidden, axe won’t check what’s inside it. Open it first, then scan.

Build a Reusable Accessibility Fixture

A fixture keeps your accessibility settings in one place, so every test scans the same way. If fixtures are new to you, read our Playwright Fixtures guide first.

// tests/fixtures/a11y.ts

import { test as base } from ‘@playwright/test’;

import AxeBuilder from ‘@axe-core/playwright’;

 

type A11yFixtures = {

  makeAxeBuilder: () => AxeBuilder;

};

 

export const test = base.extend<A11yFixtures>({

  makeAxeBuilder: async ({ page }, use) => {

    const makeAxeBuilder = () =>

      new AxeBuilder({ page })

        .withTags([‘wcag2a’, ‘wcag2aa’, ‘wcag21a’, ‘wcag21aa’, ‘wcag22aa’])

        .exclude(‘#live-chat-widget’); // third-party, tracked in JIRA-456

 

    await use(makeAxeBuilder);

  },

});

 

export { expect } from ‘@playwright/test’;

Now every test stays short and consistent:

import { test, expect } from ‘../fixtures/a11y’;

 

test(‘pricing page meets WCAG 2.2 AA (automated rules)’, async ({ page, makeAxeBuilder }) => {

  await page.goto(‘/pricing’);

  const results = await makeAxeBuilder().analyze();

  expect(results.violations).toEqual([]);

});

If your team uses the Page Object Model, add a scan step after each page object loads, so every important screen gets checked.

Playwright's Built-in Accessibility Assertions

Playwright includes accessibility assertions that check the exact role, name and description a screen reader will announce, with no extra package.

These go beyond rule scanning. axe can tell you a button has a name. Only your test can say what that name should be.

Assertion

What it checks

Added in

getByRole()

Finds elements the way assistive technology sees them

Core locator

toHaveAccessibleName()

The name a screen reader reads out

v1.44

toHaveAccessibleDescription()

The extra hint text read after the name

v1.44

toHaveRole()

The element’s ARIA role (button, checkbox, dialog…)

v1.44

toHaveAccessibleErrorMessage()

The error linked with aria-errormessage

v1.50

toMatchAriaSnapshot()

The whole accessibility tree structure

v1.49

Example: an accessible signup form

test(‘signup form announces names, hints and errors correctly’, async ({ page }) => {

  await page.goto(‘/signup’);

 

  const email = page.getByRole(‘textbox’, { name: ‘Email address’ });

 

  await expect(email).toHaveAccessibleName(‘Email address’);

  await expect(email).toHaveAccessibleDescription(‘We will never share your email.’);

 

  await page.getByRole(‘button’, { name: ‘Create account’ }).click();

 

  await expect(email).toHaveAttribute(‘aria-invalid’, ‘true’);

  await expect(email).toHaveAccessibleErrorMessage(‘Please enter a valid email address.’);

});

Why this is powerful: if a developer swaps the <label> for placeholder text, getByRole(‘textbox’, { name: ‘Email address’ }) stops finding the field and the test fails. Your locators become accessibility checks. Our Playwright Locators and Playwright Assertions guides explain these building blocks in depth.

ARIA Snapshots: Lock Your Page Structure

An ARIA snapshot is a YAML description of what assistive technology “sees” on the page, and toMatchAriaSnapshot() fails the test if that structure changes unexpectedly.

It’s like a fingerprint for your page’s accessibility tree. Unlike screenshots, it ignores colours and pixels and focuses on roles, names and order.

test(‘main navigation keeps its accessible structure’, async ({ page }) => {

  await page.goto(‘/’);

 

  await expect(page.getByRole(‘navigation’, { name: ‘Main’ })).toMatchAriaSnapshot(`

    – navigation “Main”:

      – list:

        – listitem:

          – link “Home”

        – listitem:

          – link “Courses”

        – listitem:

          – link “Contact”

  `);

});

How to create snapshots without typing them by hand:

  1. Open Playwright Codegen (npx playwright codegen your-site.com).
  2. Click the “Assert snapshot” tool and pick an element. Codegen writes the YAML for you.
  3. Or leave the template empty and run npx playwright test –update-snapshots to generate it.

ARIA snapshot vs visual snapshot:

 

ARIA snapshot

Visual screenshot

Compares

Roles, names, structure

Pixels

Breaks on font or colour change?

No

Yes

Catches a removed label?

Yes

Often no

Best for

Accessibility regressions

Layout and design regressions

Use both together. Our Playwright Visual Testing guide covers the pixel side.

Newer versions: recent Playwright releases let you call expect(page).toMatchAriaSnapshot() directly on the page, and store snapshots in separate .yml files for cleaner tests.

Keyboard Accessibility Tests

Keyboard testing checks that every action on your page can be done with only the Tab, Shift+Tab, Enter, Space, Escape and arrow keys. axe can’t fully test this, so you write Playwright tests for it yourself.

Test 1: The “skip to content” link appears first

test(‘first Tab press focuses the skip link’, async ({ page }) => {

  await page.goto(‘/’);

  await page.keyboard.press(‘Tab’);

  await expect(page.getByRole(‘link’, { name: ‘Skip to main content’ })).toBeFocused();

});

Test 2: A modal traps focus and closes with Escape

test(‘dialog keeps focus inside and returns it on close’, async ({ page }) => {

  await page.goto(‘/account’);

 

  const openBtn = page.getByRole(‘button’, { name: ‘Delete account’ });

  await openBtn.click();

 

  const dialog = page.getByRole(‘dialog’, { name: ‘Confirm deletion’ });

  await expect(dialog).toBeVisible();

 

  // Tab several times: focus must never leave the dialog

  for (let i = 0; i < 6; i++) {

    await page.keyboard.press(‘Tab’);

    const focusInside = await dialog.evaluate(el => el.contains(document.activeElement));

    expect(focusInside).toBe(true);

  }

 

  await page.keyboard.press(‘Escape’);

  await expect(dialog).toBeHidden();

  await expect(openBtn).toBeFocused(); // focus returns to the trigger

});

Test 3: A custom dropdown works with arrow keys

test(‘country menu supports arrow keys and Enter’, async ({ page }) => {

  await page.goto(‘/checkout’);

  const combo = page.getByRole(‘combobox’, { name: ‘Country’ });

  await combo.focus();

  await page.keyboard.press(‘ArrowDown’);

  await page.keyboard.press(‘ArrowDown’);

  await page.keyboard.press(‘Enter’);

  await expect(combo).toHaveValue(/India/);

});

Keyboard checklist for every page:

  • Focus is always visible (a clear outline, never outline: none with nothing replacing it)
  • Tab order follows the visual order, top to bottom and left to right
  • No keyboard trap, except inside open modals
  • Escape closes popups and menus
  • Focus moves into a modal when it opens and back out when it closes

Test Real-World Conditions: Reflow, Dark Mode, Reduced Motion

Playwright can imitate the screen sizes and display settings disabled users really use, so you can scan the page in each of those states.

Reflow at 320px (WCAG 1.4.10)

Users who zoom to 400% effectively see a 320-pixel-wide screen. Content must fit without sideways scrolling.

test(‘page reflows at 320px with no horizontal scroll’, async ({ page }) => {

  await page.setViewportSize({ width: 320, height: 800 });

  await page.goto(‘/’);

  const hasSideScroll = await page.evaluate(

    () => document.documentElement.scrollWidth > document.documentElement.clientWidth

  );

  expect(hasSideScroll).toBe(false);

});

Contrast in dark mode

Many sites pass contrast in light mode but fail in dark mode.

test(‘dark mode keeps readable contrast’, async ({ page, makeAxeBuilder }) => {

  await page.emulateMedia({ colorScheme: ‘dark’ });

  await page.goto(‘/’);

  const results = await makeAxeBuilder().withRules([‘color-contrast’]).analyze();

  expect(results.violations).toEqual([]);

});

Reduced motion and forced colours

await page.emulateMedia({ reducedMotion: ‘reduce’ });   // users sensitive to animation

await page.emulateMedia({ forcedColors: ‘active’ });    // Windows High Contrast users

After switching these on, check that carousels stop moving on their own and that icons and borders stay visible. For phone and tablet layouts, combine this with our Playwright Mobile Emulation guide.

Make Failures Easy to Read and Fix

A good accessibility test tells the developer exactly which rule failed, how serious it is, and where to learn the fix. A raw JSON dump wastes everyone’s time.

Print a clean summary on failure

const results = await makeAxeBuilder().analyze();

 

const summary = results.violations.map(v =>

  `• [${v.impact}] ${v.id}: ${v.help} (${v.nodes.length} element(s))\n  Fix guide: ${v.helpUrl}\n  First target: ${v.nodes[0]?.target.join(‘ ‘)}`

).join(‘\n’);

 

expect(results.violations, summary).toEqual([]);

Attach the full report to the HTML report

test(‘checkout scan with attached report’, async ({ page, makeAxeBuilder }, testInfo) => {

  await page.goto(‘/checkout’);

  const results = await makeAxeBuilder().analyze();

 

  await testInfo.attach(‘accessibility-scan-results’, {

    body: JSON.stringify(results, null, 2),

    contentType: ‘application/json’,

  });

 

  expect(results.violations).toEqual([]);

});

The JSON then appears inside the Playwright HTML Report, so anyone can open it with one click. To see what the page looked like at the moment of failure, open the Playwright Trace Viewer.

Understand the impact levels

Impact

Meaning

Action

critical

Blocks some users completely

Fix before release

serious

Major barrier

Fix before release

moderate

Annoying, with a workaround

Plan this sprint

minor

Small issue

Add to backlog

Run Accessibility Tests in CI as a Quality Gate

Running accessibility tests in your CI pipeline blocks new accessibility bugs from being merged. That’s how teams stop regressions for good.

Step 1: Add a dedicated project in playwright.config.ts

import { defineConfig, devices } from ‘@playwright/test’;

 

export default defineConfig({

  projects: [

    {

      name: ‘a11y’,

      testMatch: /.*\.a11y\.spec\.ts/,

      use: { …devices[‘Desktop Chrome’] },

    },

    // …your functional projects

  ],

});

Accessibility rules check the page structure, which is the same in every browser, so one Chromium run is usually enough and keeps CI fast. Learn more in Playwright Projects.

Step 2: Block merges on serious issues first (gradual rollout)

If an old site has hundreds of issues, failing on all of them at once will frustrate the team. Start strict on the worst ones:

const blocking = results.violations.filter(

  v => v.impact === ‘critical’ || v.impact === ‘serious’

);

expect(blocking, summary).toEqual([]);

Rollout plan:

  • Weeks 1–2: Report only (never fail) and collect a baseline
  • Weeks 3–4: Fail on critical
  • Month 2: Fail on critical + serious
  • Month 3+: Fail on everything for the WCAG AA tags

Step 3: Run it in your pipeline

npx playwright test –project=a11y

For full GitHub Actions, Jenkins and Azure DevOps setups, follow our Playwright CI/CD guide. To make large suites faster, see Playwright Parallel Testing.

Python and Java Examples

Playwright accessibility testing works in Python and Java too, using community and Deque axe packages.

Python (pytest)

pip install pytest-playwright axe-playwright-python

 

from playwright.sync_api import Page

from axe_playwright_python.sync_playwright import Axe

 

def test_home_page_accessibility(page: Page):

    page.goto(“https://your-site.com/”)

    results = Axe().run(page)

    assert results.violations_count == 0, results.generate_report()

Playwright’s built-in Python assertions work too: expect(locator).to_have_accessible_name(“Email address”) and expect(locator).to_match_aria_snapshot(…). New to Python? See Playwright with Python.

Java (JUnit)

<dependency>

  <groupId>com.deque.html.axe-core</groupId>

  <artifactId>playwright</artifactId>

  <version>4.10.1</version>

</dependency>

Check Maven Central for the newest version before you add it.

import com.deque.html.axecore.playwright.AxeBuilder;

import com.deque.html.axecore.results.AxeResults;

 

@Test

void homePageHasNoA11yViolations() {

    page.navigate(“https://your-site.com/”);

    AxeResults results = new AxeBuilder(page)

        .withTags(List.of(“wcag2a”, “wcag2aa”, “wcag21a”, “wcag21aa”))

        .analyze();

    assertEquals(Collections.emptyList(), results.getViolations());

}

More Java setup help is in Playwright with Java.

Common Violations and How to Fix Them

Most accessibility failures come from a small set of repeated mistakes, and each one has a simple fix.

axe rule ID

What’s wrong

Bad code

Fixed code

image-alt

Image has no text alternative

<img src=”logo.png”>

<img src=”logo.png” alt=”Playwright Masters logo”>

label

Input has no label

<input type=”email” placeholder=”Email”>

<label for=”em”>Email</label><input id=”em” type=”email”>

button-name

Icon button has no name

<button><svg>…</svg></button>

<button aria-label=”Close”><svg aria-hidden=”true”>…</svg></button>

color-contrast

Text too faint

Grey #999 on white

Use #595959 or darker (4.5:1 ratio)

link-name

Link has no readable text

<a href=”/cart”><i class=”icon”></i></a>

<a href=”/cart” aria-label=”View cart”>…</a>

html-has-lang

Page language missing

<html>

<html lang=”en”>

heading-order

Jumps from h1 to h4

<h1>…<h4>

Use <h2> next, in order

duplicate-id-aria

Same ID used twice

Two id=”name”

Make every ID unique

aria-allowed-attr

Wrong ARIA on an element

<div aria-checked=”true”>

Add role=”checkbox”, or use a real <input type=”checkbox”>

Golden rule: Use real HTML elements first (<button>, <a>, <label>, <nav>). Add ARIA only when no native element fits. Wrong ARIA can be worse than no ARIA.

Best Practices Checklist

Follow these practices to build an accessibility test suite that stays useful as your app grows:

  • Scan your top user journeys first: home, login, search, checkout and signup
  • Scan after each interaction, not just on page load (open modals, menus and tabs)
  • Use getByRole() locators everywhere, so ordinary tests double as accessibility checks
  • Keep axe settings in one shared fixture
  • Target WCAG 2.1 AA or 2.2 AA tags by default
  • Give every exclude() and disableRules() a comment and a ticket number
  • Attach JSON results to reports for easy debugging
  • Add keyboard tests for every custom widget (dropdowns, modals, tabs, sliders)
  • Run accessibility checks in CI on every pull request
  • Do a manual screen reader pass (NVDA or VoiceOver) before major releases
  • Keep the @axe-core/playwright version up to date for new rules

Want to see where these skills fit in a full learning plan? Check our Playwright Roadmap and Playwright Syllabus.

Mistakes Beginners Make

The most common Playwright accessibility testing mistakes are scanning too early, trusting automation alone, and hiding problems instead of fixing them.

  1. Scanning before the page finishes loading. Wait for key content with await expect(locator).toBeVisible() before running analyze(). Otherwise you get flaky results. Our Playwright Flaky Tests guide explains waiting the right way.
  2. Believing “0 violations” means “fully accessible.” It only means no automatic rule failed.
  3. Snapshotting the whole violations array. It contains HTML snippets that change often. Snapshot only rule IDs and targets, or use ARIA snapshots instead.
  4. Excluding entire page sections. exclude(‘main’) hides everything and makes the test pointless.
  5. Running accessibility scans in all three browsers. It triples CI time with almost no extra value.
  6. Using old tutorials with page.accessibility.snapshot(). That API has been removed from Playwright.
  7. Fixing symptoms with ARIA. Adding role=”button” to a <div> without keyboard support only fakes accessibility.

Frequently Asked Questions

Does Playwright have built-in accessibility testing?

Yes, partly. Playwright has built-in accessibility assertions such as toHaveAccessibleName(), toHaveRole(), toHaveAccessibleErrorMessage() and toMatchAriaSnapshot(). For full WCAG rule scanning, you add the free @axe-core/playwright package.

What is axe-core in Playwright?

axe-core is a free, open-source accessibility engine from Deque Systems. The @axe-core/playwright package runs it inside your Playwright tests and returns a list of WCAG violations for the page.

Is Playwright accessibility testing free?

Yes. Playwright and axe-core are both free and open source. Paid platforms add dashboards and reporting, but you don’t need them to start.

Which WCAG version should I test with Playwright?

Most teams test against WCAG 2.1 AA or WCAG 2.2 AA. Use the tags wcag2a, wcag2aa, wcag21a, wcag21aa and wcag22aa in withTags().

Can Playwright test screen reader behaviour?

Playwright can’t run a real screen reader, but it checks what a screen reader would announce. It does this through role locators, accessible-name assertions and ARIA snapshots. Final checks with NVDA, JAWS or VoiceOver should still be done by a person.

What is the difference between toMatchAriaSnapshot and a screenshot test?

toMatchAriaSnapshot() compares the accessibility tree (roles, names, structure) as YAML. A screenshot test compares pixels. ARIA snapshots catch missing labels, while screenshots catch visual layout changes.

How do I test keyboard navigation in Playwright?

Use page.keyboard.press(‘Tab’) to move focus, then expect(locator).toBeFocused() to confirm focus landed on the right element. Test Escape, Enter, Space and the arrow keys on every custom widget.

Should accessibility tests run on every browser?

Usually no. axe checks the page structure, which is the same across browsers, so running in Chromium only is enough for most teams and keeps pipelines fast.

How much time does an axe scan add to a test?

An axe scan usually adds a fraction of a second per page, depending on page size. That’s small enough to add scans inside existing functional tests.

What replaced page.accessibility.snapshot() in Playwright?

page.accessibility was removed after a long deprecation. Use locator.ariaSnapshot() and toMatchAriaSnapshot() for structure, and axe-core for rule-based scanning.

Can AI tools help with Playwright accessibility testing?

Yes. AI agents connected through Playwright MCP read the same accessibility tree that ARIA snapshots use, so they can explore pages and suggest tests. Learn more in our Playwright MCP guide.

Final Thoughts

Playwright accessibility testing turns accessibility from a once-a-year audit into an automatic check on every code change. Start with one axe scan on your home page, add role-based assertions to your existing tests, protect your key screens with ARIA snapshots, and gate your CI on serious violations. Then keep humans in the loop for what machines can’t judge.

Small steps, done every day, build websites that work for everyone.

Playwright Masters automation testing logo - White Back ground

Playwright Masters Team

Playwright Automation Testing Experts | Industry-Focused Training & Practical Learning

Playwright Masters is a dedicated automation testing training platform focused on helping learners build practical skills in Playwright automation testing. Our training covers real-world automation concepts, framework practices, coding, debugging, API testing, cross-browser testing, CI/CD, and interview preparation to help learners develop job-ready testing skills.

Scroll to Top

Start Your Playwright Automation Career Today

Get FREE Demo + Syllabus & Become Job-Ready in Playwright.