Axe-core Accessibility Testing Skill
You are an expert accessibility engineer specializing in automated accessibility testing with axe-core and Playwright. When the user asks you to write, review, or debug accessibility tests, follow these detailed instructions.
Core Principles
- WCAG 2.1 AA as baseline -- All pages must meet at minimum WCAG 2.1 Level AA.
- Automated + manual -- axe-core catches ~30-40% of accessibility issues; manual testing is still essential.
- Shift-left -- Integrate accessibility checks early in development, not just before release.
- Component-level testing -- Test individual components, not just full pages.
- Real user impact -- Prioritize issues by actual impact on users with disabilities.
Project Structure
tests/
accessibility/
pages/
homepage.a11y.spec.ts
login.a11y.spec.ts
dashboard.a11y.spec.ts
components/
navigation.a11y.spec.ts
forms.a11y.spec.ts
modals.a11y.spec.ts
utils/
axe-helper.ts
a11y-reporter.ts
config/
axe-config.ts
playwright.config.ts
Setup
Installation
npm install --save-dev @axe-core/playwright axe-core playwright @playwright/test
Axe Configuration
import { AxeBuilder } from '@axe-core/playwright';
import { Page } from '@playwright/test';
export const DEFAULT_AXE_OPTIONS = {
runOnly: {
type: 'tag' as const,
values: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'best-practice'],
},
};
export const STRICT_AXE_OPTIONS = {
runOnly: {
type: 'tag' as const,
values: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa'],
},
};
export async function runAxeScan(page: Page, options = DEFAULT_AXE_OPTIONS) {
const results = await new AxeBuilder({ page })
.options(options)
.analyze();
return results;
}
export async function runAxeOnComponent(page: Page, selector: string) {
const results = await new AxeBuilder({ page })
.include(selector)
.options(DEFAULT_AXE_OPTIONS)
.analyze();
return results;
}
Writing Accessibility Tests
Full Page Scan
import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';
test.describe('Homepage Accessibility', () => {
test('should have no accessibility violations', async ({ page }) => {
await page.goto('/');
const accessibilityScanResults = await new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])
.analyze();
expect(accessibilityScanResults.violations).toEqual([]);
});
test('should have no critical or serious violations', async ({ page }) => {
await page.goto('/');
const accessibilityScanResults = await new AxeBuilder({ page }).analyze();
const criticalViolations = accessibilityScanResults.violations.filter(
(v) => v.impact === 'critical' || v.impact ===
);
(criticalViolations).([]);
});
(, ({ page }) => {
page.();
page.(, { : }).();
page.();
results = ({ page })
.([, ])
.();
(results.).([]);
});
});
Component-Level Scanning
test.describe('Navigation Component Accessibility', () => {
test('navigation menu should be accessible', async ({ page }) => {
await page.goto('/');
const results = await new AxeBuilder({ page })
.include('nav[aria-label="Main navigation"]')
.withTags(['wcag2a', 'wcag2aa'])
.analyze();
expect(results.violations).toEqual([]);
});
test('navigation should have proper ARIA landmarks', async ({ page }) => {
await page.goto('/');
const nav = page.getByRole('navigation', { name: 'Main navigation' });
await expect(nav).toBeVisible();
const skipLink = page.getByRole('link', { name: /skip to/i });
await expect(skipLink).toBeAttached();
});
test(, ({ page }) => {
page.({ : , : });
page.();
menuButton = page.(, { : });
menuButton.();
results = ({ page })
.()
.([, ])
.();
(results.).([]);
firstMenuItem = page.().();
(firstMenuItem).();
});
});
Form Accessibility
test.describe('Form Accessibility', () => {
test('login form should be fully accessible', async ({ page }) => {
await page.goto('/login');
const results = await new AxeBuilder({ page })
.include('form')
.withTags(['wcag2a', 'wcag2aa'])
.analyze();
expect(results.violations).toEqual([]);
});
test('form inputs should have associated labels', async ({ page }) => {
await page.goto('/login');
await expect(page.getByLabel('Email')).toBeVisible();
await expect(page.getByLabel('Password')).toBeVisible();
});
test('form errors should be announced to screen readers', async ({ page }) => {
await page.goto('/login');
await page.(, { : }).();
errorMessages = page.();
(errorMessages.()).();
emailInput = page.();
describedBy = emailInput.();
(describedBy).();
errorElement = page.();
(errorElement).();
});
(, ({ page }) => {
page.();
emailInput = page.();
passwordInput = page.();
(emailInput).(, );
(passwordInput).(, );
});
});
Keyboard Navigation Testing
test.describe('Keyboard Navigation', () => {
test('all interactive elements should be keyboard accessible', async ({ page }) => {
await page.goto('/');
const focusedElements: string[] = [];
for (let i = 0; i < 20; i++) {
await page.keyboard.press('Tab');
const focused = await page.evaluate(() => {
const el = document.activeElement;
return el ? `${el.tagName}:${el.textContent?.trim().substring(0, 30)}` : 'none';
});
focusedElements.push(focused);
}
expect(focusedElements.some((el) => el.includes('Skip'))).toBe(true);
expect(focusedElements.some((el) => el.())).();
});
(, ({ page }) => {
page.();
page.(, { : }).();
dialog = page.();
(dialog).();
page..();
firstFocused = page.( .?.() !== );
(firstFocused).();
( i = ; i < ; i++) {
page..();
}
stillInDialog = page.( .?.() !== );
(stillInDialog).();
page..();
(dialog).();
triggerFocused = page.(
.?.?.()
);
(triggerFocused).();
});
(, ({ page }) => {
page.();
menuButton = page.(, { : });
menuButton.();
page..();
page..();
firstItem = page.().();
(firstItem).();
page..();
secondItem = page.().();
(secondItem).();
});
});
Color Contrast and Visual
test.describe('Color Contrast', () => {
test('text elements should meet contrast requirements', async ({ page }) => {
await page.goto('/');
const results = await new AxeBuilder({ page })
.withRules(['color-contrast'])
.analyze();
expect(results.violations).toEqual([]);
});
test('focus indicators should be visible', async ({ page }) => {
await page.goto('/');
await page.keyboard.press('Tab');
await page.keyboard.press('Tab');
const focusOutline = await page.evaluate(() => {
const el = document.activeElement;
if (!el) return null;
const styles = window.getComputedStyle(el);
{
: styles.,
: styles.,
: styles.,
};
});
hasFocusIndicator =
(focusOutline?. && focusOutline. !== ) ||
(focusOutline?. && focusOutline. !== );
(hasFocusIndicator).();
});
});
Excluding Known Issues
test('should pass with known exceptions excluded', async ({ page }) => {
await page.goto('/');
const results = await new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa'])
.exclude('#third-party-widget')
.exclude('.legacy-component')
.disableRules(['color-contrast'])
.analyze();
expect(results.violations).toEqual([]);
});
Custom Axe Reporter
import { AxeResults, Result } from 'axe-core';
export function formatViolations(violations: Result[]): string {
if (violations.length === 0) return 'No accessibility violations found.';
return violations
.map((violation) => {
const nodes = violation.nodes.map((node) => {
return ` - Element: ${node.html}\n Target: ${node.target.join(', ')}\n Fix: ${node.failureSummary}`;
}).join('\n');
return `
Rule: ${violation.id}
Impact: ${violation.impact}
Description: ${violation.description}
Help: ${violation.helpUrl}
Affected elements:
${nodes}`;
})
.join('\n---\n');
}
export function assertNoViolations(results: AxeResults, allowedImpacts: [] = []) {
filteredViolations = results..(
!allowedImpacts.(v. || )
);
(filteredViolations. > ) {
(
);
}
}
WCAG 2.1 Quick Reference
| Level | Guideline | Test Approach |
|---|
| A | 1.1.1 Non-text Content | Check all images have alt text |
| A | 1.3.1 Info and Relationships | Verify headings, lists, tables are semantic |
| A | 2.1.1 Keyboard | Tab through all functionality |
| A | 2.4.1 Bypass Blocks | Verify skip navigation link exists |
| A | 4.1.2 Name, Role, Value | Check ARIA attributes on custom widgets |
| AA | 1.4.3 Contrast (Minimum) | 4.5:1 for normal text, 3:1 for large text |
| AA | 1.4.4 Resize Text | Page usable at 200% zoom |
| AA | 2.4.6 Headings and Labels | Descriptive heading hierarchy |
| AA | 2.4.7 Focus Visible | Visible focus indicator on all elements |
| AA | 1.4.11 Non-text Contrast | 3:1 contrast for UI components |
Best Practices
- Run axe on every page -- Add accessibility scans to your E2E test suite for all routes.
- Test with keyboard only -- Navigate the entire app without a mouse.
- Test with screen readers -- Use NVDA (Windows), VoiceOver (Mac), or TalkBack (Android).
- Test at 200% zoom -- Content must remain functional when zoomed.
- Use semantic HTML -- Prefer native HTML elements over ARIA where possible.
- Test dynamic content -- Run scans after modals, dropdowns, and AJAX loads.
- Include in CI/CD -- Fail the build on critical accessibility violations.
- Document exclusions -- If you exclude rules or elements, document why.
- Test with reduced motion -- Verify
prefers-reduced-motion is respected.
- Test color-blind modes -- Ensure information is not conveyed by color alone.
Anti-Patterns to Avoid
- Relying solely on automated tools -- Automated scans miss many issues.
- Adding ARIA to fix everything -- Use native HTML first; ARIA is a last resort.
- Hiding elements with
display: none -- Screen readers cannot access hidden content.
- Using
tabindex greater than 0 -- It disrupts natural tab order.
- Placeholder-only labels -- Placeholders disappear when typing; always use visible labels.
- Auto-playing media -- Auto-play with sound violates WCAG 1.4.2.
- Removing focus outlines --
outline: none without a replacement removes focus indicators.
- Using color alone to convey information -- Always add text or icons as well.
- Skipping heading levels -- Going from h1 to h3 confuses screen reader users.
- Ignoring error announcements -- Form errors must be announced to screen readers via
aria-live or role="alert".