Skip to main content

Accessibility Testing with Playwright

Add Zod and Playwright to your project

pnpm create playwright
pnpm add @axe-core/playwright

Create an Accessibility Fixture

axe-fixture.ts
import {test as base} from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';

type AxeFixture = {
makeAxeBuilder: () => AxeBuilder;
};

// This new "test" can be used in multiple test files, and each of them will get
// a consistently configured AxeBuilder instance.
export const test = base.extend<AxeFixture>({
makeAxeBuilder: async ({page}, use, testInfo) => {
const makeAxeBuilder = () => new AxeBuilder({page})
.withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])

await use(makeAxeBuilder);
}
});
export {expect} from '@playwright/test';

Use the Accessibility Fixture in your Test

a11y.spec.ts
import {expect, test} from './axe-test';

test('has a11y', async ({page, makeAxeBuilder}, testInfo,
) => {
await page.goto('https://playwright.dev/');

await expect(page).toHaveScreenshot({maxDiffPixels: 100});

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

await testInfo.attach('accessibility-scan-results', {
body: JSON.stringify(accessibilityScanResults, null, 2),
contentType: 'application/json',
});

expect(accessibilityScanResults.violations).toEqual([]); // 5
});

Test Execution

playwright test

Test Results

Passing Scenario

Accessibility Test Results

Failure Scenario

Failing Accessibility Test Results