QA and Test Automation · Lab 18 of 35
Accessibility Testing Lab: axe, ARIA Snapshots and Keyboard Tests
Automate accessibility checks on ShopRung with Playwright: axe scans against WCAG A and AA, a real finding on the home page handled the way teams do, ARIA snapshots of the header, and keyboard-only tests. Then learn what automation cannot check.
⏱ 45 minIntermediate💸 Free6 steps
Node.js 22Playwright Test 1.63@axe-core/playwright 4.14TypeScriptShopRung
Overview video
What you will build
A Playwright project with 7 accessibility tests:
- axe scans of the login and product pages against WCAG 2.1 A and AA: no violations.
- The home page, where axe finds a real issue on all 12 Add to cart buttons. The test records it as a known issue and fails if anything new appears.
- An ARIA snapshot of the header: the navigation and search, as a screen reader sees them.
- Keyboard tests: log in with no mouse, a wrong password announced to screen readers, and a logical tab order through the products.
Before you start
- Playwright end to end, or comfort with Playwright tests in TypeScript.
- The ideas behind this lab: Accessibility testing and the accessible names in DOM and locators.
- ShopRung installed, as in lab 1 setup.
Setup
S1Start ShopRung
Start ShopRung as in lab 1 with npm start, and leave it running.
curl http://localhost:8080/api/healthcurl http://localhost:8080/api/healthcurl.exe http://localhost:8080/api/health {"status":"UP","app":"ShopRung","version":"1.0.0"} S2Create the project folder
Make a folder shoprung-accessibility, add the files from step 1, and install. This project adds one library: @axe-core/playwright, which runs the axe accessibility engine inside a Playwright test.
mkdir shoprung-accessibility
cd shoprung-accessibility
# add package.json, .gitignore and playwright.config.ts from step 1, then:
npm install
npx playwright install chromium Project files
Playwright plus the axe integration, both pinned.
axe-core is the most widely used open-source accessibility rules engine. It checks the page for problems like missing labels, low colour contrast and broken ARIA. @axe-core/playwright runs it on the page your test has open.
{
"name": "shoprung-accessibility",
"private": true,
"scripts": {
"test": "playwright test",
"report": "playwright show-report"
},
"devDependencies": {
"@playwright/test": "1.63.0",
"@axe-core/playwright": "4.14.1"
}
} - Pinned too: a new axe version can add rules, and new findings should arrive on purpose.line 10
node_modules/
playwright/.auth/
test-results/
playwright-report/ import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
workers: 1,
reporter: [['list'], ['html', { open: 'never' }]],
use: {
baseURL: process.env.BASE_URL ?? 'http://localhost:8080',
trace: 'retain-on-failure',
},
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
}); Scan two pages with axe
The login and product pages pass every WCAG 2.1 A and AA rule axe can check.
Create tests/axe.spec.ts. A for loop makes one test per page. Each test opens the page, waits for the main heading (ShopRung builds pages with JavaScript, and a scan of an empty page finds nothing), then runs axe with the WCAG A and AA rule tags, the level most laws and policies ask for.
expect(results.violations).toEqual([]) passes only when there are none. When it fails, the output lists each violation with its rule id, impact, a help link and the elements involved.
import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';
const WCAG_AA = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'];
// Pages built by JavaScript: wait for the main heading before scanning, or axe scans an empty page.
const pages = [
{ name: 'login', path: '/#/login' },
{ name: 'product', path: '/#/product/1' },
];
for (const { name, path } of pages) {
test(`${name} page has no WCAG A/AA violations`, async ({ page }) => {
await page.goto(path);
await page.locator('main h1').waitFor();
const results = await new AxeBuilder({ page }).withTags(WCAG_AA).analyze();
expect(results.violations).toEqual([]);
});
} - Only WCAG A and AA rules. axe also has best-practice and AAA rules you can add later.line 4
- Scan the finished page, not the loading one.line 15
- No violations at all. The failure output shows exactly what is wrong.line 17
npx playwright test ✓ 1 [chromium] › tests/axe.spec.ts:13:7 › login page has no WCAG A/AA violations ✓ 2 [chromium] › tests/axe.spec.ts:13:7 › product page has no WCAG A/AA violations 2 passed (2.3s)
A real finding on the home page
Scan the home page, understand its one issue, and turn it into a known-issue test.
Scan the home page and axe reports one serious problem on 12 elements: label-content-name-mismatch. Each Add to cart button shows "Add to cart", but its accessible name, from its aria-label, is "Add Clean Code Notebook to cart". The visible words are not inside the name. That breaks WCAG 2.5.3, Label in Name: a person using voice control says "click Add to cart", and nothing matches.
You cannot fix ShopRung, and in a real team the fix belongs to the developers. So you report the bug and write a test that records exactly what is known: one rule, 12 elements. Replace tests/axe.spec.ts with the version below. It passes today, fails if a new kind of problem appears, and fails when the known one is fixed, which reminds you to tighten it to toEqual([]).
import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';
const WCAG_AA = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'];
// Pages built by JavaScript: wait for the main heading before scanning, or axe scans an empty page.
const pages = [
{ name: 'login', path: '/#/login' },
{ name: 'product', path: '/#/product/1' },
];
for (const { name, path } of pages) {
test(`${name} page has no WCAG A/AA violations`, async ({ page }) => {
await page.goto(path);
await page.locator('main h1').waitFor();
const results = await new AxeBuilder({ page }).withTags(WCAG_AA).analyze();
expect(results.violations).toEqual([]);
});
}
test('home page: only the known Add to cart issue', async ({ page }) => {
await page.goto('/');
await expect(page.getByTestId('product-card')).toHaveCount(12);
const results = await new AxeBuilder({ page }).withTags(WCAG_AA).analyze();
// Known issue, reported as a bug: the buttons show "Add to cart" but are named
// "Add <product> to cart", so the visible text is not inside the accessible name (WCAG 2.5.3).
// This test fails if a NEW kind of violation appears, or if the known one changes.
const summary = results.violations.map((v) => `${v.id} x${v.nodes.length}`);
expect(summary).toEqual(['label-content-name-mismatch x12']);
}); - Wait for all 12 cards, or the count of problems changes from run to run.line 23
- Say why the exception exists and where it is tracked.line 25
- Exactly what is known. Anything else fails.line 29
npx playwright test tests/axe.spec.ts 3 passed (2.9s)
Lock the header's structure with an ARIA snapshot
The navigation and search, asserted as a screen reader sees them.
Create tests/structure.spec.ts. toMatchAriaSnapshot compares part of the page's accessibility tree with a short YAML description: the roles and names assistive technology uses. ShopRung's header has a navigation named Main with four links, and a search landmark with a labelled search box and a Search button.
The cart link's name includes the item count, so it is matched with a regular expression: /Cart \d+/. If someone removes a label, turns a link into an unnamed icon or drops the search landmark, this test fails with a clear diff.
Tip: in the Playwright VS Code extension or with npx playwright codegen, you can generate a snapshot like this from the live page.
import { test, expect } from '@playwright/test';
test('the header keeps its landmarks and names', async ({ page }) => {
await page.goto('/');
await expect(page.getByRole('navigation', { name: 'Main' })).toMatchAriaSnapshot(`
- navigation "Main":
- link "Products"
- link /Cart \\d+/
- link "Orders"
- link "Log in"
`);
await expect(page.getByRole('search')).toMatchAriaSnapshot(`
- search:
- searchbox "Search products"
- button "Search"
`);
}); - A landmark with a name: screen reader users can jump straight to it.line 6
- A regex for the part that changes (the count).line 8
- The name comes from the label, which is visually hidden but present.line 14
npx playwright test tests/structure.spec.ts 1 passed (1.1s)
Keyboard-only tests
Log in without a mouse, check an error is announced, and check the tab order.
Create tests/keyboard.spec.ts. Many people use only a keyboard, and so do screen reader users. Three tests:
- Log in with the keyboard. Type the email, press Tab and check focus is on the password field, type the password, press Enter. The header must say Hi, Alice Shah.
- A wrong password is announced. ShopRung shows errors in an element with
role="alert", which screen readers read out the moment it appears. The test finds it by that role and checks the text Email or password is wrong. - Reading order. From the first product's link, Tab goes to its Add button, then to the next product's link: the same order you read the page in.
import { test, expect } from '@playwright/test';
test.beforeEach(async ({ request }) => {
await request.post('/api/test/reset');
});
test('log in with the keyboard only', async ({ page }) => {
await page.goto('/#/login');
await page.getByLabel('Email').focus();
await page.keyboard.type('alice@shoprung.test');
await page.keyboard.press('Tab');
await expect(page.getByLabel('Password')).toBeFocused();
await page.keyboard.type('Alice123!');
await page.keyboard.press('Enter'); // submits the form, no mouse
await expect(page.getByTestId('user-name')).toHaveText('Hi, Alice Shah');
});
test('a wrong password is announced to screen readers', async ({ page }) => {
await page.goto('/#/login');
await page.getByLabel('Email').fill('alice@shoprung.test');
await page.getByLabel('Password').fill('wrong');
await page.getByLabel('Password').press('Enter');
// role="alert" makes screen readers read the message out as soon as it appears
await expect(page.getByRole('alert')).toHaveText('Email or password is wrong');
});
test('product cards are reached in reading order', async ({ page }) => {
await page.goto('/');
await expect(page.getByTestId('product-card')).toHaveCount(12);
await page.getByRole('link', { name: 'Clean Code Notebook' }).focus();
await page.keyboard.press('Tab');
await expect(page.getByRole('button', { name: 'Add Clean Code Notebook to cart' })).toBeFocused();
await page.keyboard.press('Tab');
await expect(page.getByRole('link', { name: 'Testing Field Guide' })).toBeFocused();
}); - Tab moved focus where a user expects.line 12
- Forms must submit with Enter. No mouse anywhere in this test.line 14
- If this locator finds nothing, the error is silent for screen reader users.line 24
npx playwright test Running 7 tests using 1 worker ... 7 passed (5.2s)
What automation cannot check
A short manual routine to run alongside the suite.
Automated checks are a floor, not a certificate. They cannot tell you whether alt text is meaningful, whether the page makes sense read aloud, or whether checkout is usable at 400% zoom. Spend ten minutes on ShopRung with this routine and write down anything odd, as you did in the exploratory testing lab:
- Keyboard only: log in, add two products, apply SAVE10, place the order. Is focus always visible? Did you ever get stuck?
- Screen reader: do the same with VoiceOver (Cmd+F5 on a Mac) or NVDA (free, Windows). Listen to how each Add to cart button is announced.
- Zoom: 200% and 400% in the browser. Does anything overlap or disappear?
- Colour: is anything shown only by colour? ShopRung's out of stock state also uses text, which is right.
Check it works
Prove the scan catches a real problem. In tests/axe.spec.ts, add this line right after await page.locator('main h1').waitFor(); inside the loop. It unwraps the email field from its label, the kind of mistake a refactor can make:
await page.evaluate(() => { const i = document.querySelector('input[name=email]')!; i.closest('label')!.replaceWith(i); }); // TEMPORARY
Run the suite. The login test fails with a critical violation, rule label, "Form elements must have labels". Remove the line again and the suite passes.
npx playwright test tests/axe.spec.ts -g login Error: expect(received).toEqual(expected) // deep equality
- Array []
+ Array [
+ Object {
+ "description": "Ensure every form element has a label",
+ "help": "Form elements must have labels",
+ "id": "label",
+ "impact": "critical",
... Troubleshooting
axe finds nothing at all, even on a broken page.
The scan ran before the page rendered. Wait for the main heading or a known element first.
The home page test reports a different number than 12.
The scan ran while cards were still appearing. Keep the toHaveCount(12) wait before scanning.
The ARIA snapshot fails on the cart link.
Its name includes the item count. Keep the regular expression /Cart \d+/ instead of an exact name.
The alert test fails after a while.
ShopRung's message disappears after a few seconds. Check it right after pressing Enter, as the test does.
What changes in production
- Teams run axe on key pages in CI on every pull request, and fail the build on new violations rather than on a long list of old ones.
- Known issues are tracked as bugs and recorded in the test with a comment, never hidden by disabling a rule for the whole suite.
- ARIA snapshots protect shared components like headers, menus and dialogs, where one change affects every page.
- Manual checks with real screen readers, and sessions with disabled users, cover what scanners cannot. Most laws target WCAG AA.
Interview angle
“How do you automate accessibility testing, and what are its limits?”
I run axe in the UI suite on key pages after they render, limited to WCAG A and AA, and fail on violations; known issues are tracked as bugs and pinned in the test so anything new still fails. ARIA snapshots protect the structure of shared components, and keyboard tests check focus order, Enter to submit and that errors are announced. Automation catches a part of the problems: meaningful alt text, reading order, zoom and real screen reader use need manual checks. For example, axe found that our Add to cart buttons break Label in Name, which affects voice control users.
Clean up
The full project
Every file from this lab, as it is after the last step.