Automated accessibility checks are the cheapest quality gate a React team can install, and also the most over-trusted. A clean axe run means the markup satisfies a few dozen machine-checkable rules; it says nothing about whether someone who never uses a mouse can finish the checkout flow you shipped on Friday. Teams that take accessibility seriously treat automation as the opening ten minutes of an audit rather than the last, then add a short, scripted human pass for everything a rule engine cannot judge. In this lesson you will wire axe-core into Jest so violations fail a pull request, read a violation report without panicking or blindly disabling rules, test keyboard and ARIA state the way assistive technology exercises it, and run a manual screen reader pass that fits inside a coffee break.
âšī¸Automation is evidence, not certification
No tool can certify conformance, because conformance is a judgement about whether a person can complete a task. Use scanners to remove the embarrassingly obvious defects at machine speed, then spend your human attention on flow, order and meaning.
What a scanner sees and what it never will
WCAG conformance is a human judgement guided by machine evidence. Automated tools reliably evaluate roughly a third of the success criteria, the third expressible as DOM predicates: every image has an alt attribute, every input has a programmatic label, every button has an accessible name, contrast clears a threshold, landmark regions exist. Everything about meaning and workflow is out of reach. An image tagged with a filename as its alternative text passes the check and tells a blind user nothing. A button labelled "Click here" passes too. A dialog that traps focus correctly and then dumps the reader at the top of the document on close passes every static rule ever written.
The practical consequence is that tool selection is about covering different failure classes, not about hunting for one authoritative linter.
| Layer | Typical tool | Strong at | Blind to |
|---|---|---|---|
| Component markup | jest-axe | Missing names, invalid ARIA, misuse of roles | Whether the name is the right name |
| Page audit | Lighthouse CI | Weighted scoring, drift between builds | Anything that only happens after a click |
| Flow with assistive tech | Playwright plus axe injection | Violations revealed by real interaction | Reading comfort, tone, confusion |
| Human pass | NVDA, VoiceOver, keyboard only | Dead ends, surprise focus moves, odd order | Scale: one pass covers one path |
Use each layer where it is cheap. jest-axe costs milliseconds and belongs in any test that renders standalone UI. Lighthouse runs once per build against the handful of pages that carry the business. The human pass is reserved for flows where a mistake costs a customer: sign in, pay, change a password, manage a subscription.
Putting axe-core inside the test suite
A component test is the right home for markup rules, because the failure appears at the moment someone writes the markup and the stack trace points at the offending line. jest-axe is a thin wrapper: extend the matchers once in a setup file, render, await the axe scan, and assert on the result. Scanning a specific subtree rather than the whole document keeps failures local and avoids reporting violations you are not ready to own.
JSDOM does not perform layout, so axe cannot compute colour contrast during a unit run. Contrast must be checked in a real browser, either through Lighthouse or an injected axe scan in Playwright, and that split should be deliberate rather than discovered during an audit.
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { axe, toHaveNoViolations } from 'jest-axe';
import { ProfileForm } from './ProfileForm';
expect.extend(toHaveNoViolations);
describe('ProfileForm accessibility', () => {
it('has no axe violations in its default state', async () => {
const { container } = render(<ProfileForm />);
expect(await axe(container)).toHaveNoViolations();
});
it('links the error to the field and marks it invalid after a failed save', async () => {
render(<ProfileForm />);
const user = userEvent.setup();
await user.clear(screen.getByLabelText(/display name/i));
await user.click(screen.getByRole('button', { name: /save/i }));
const input = screen.getByLabelText(/display name/i);
expect(input).toHaveAttribute('aria-invalid', 'true');
const describedBy = input.getAttribute('aria-describedby');
expect(describedBy).toBeTruthy();
expect(document.getElementById(describedBy)).toHaveTextContent(/required/i);
expect(await axe(input.closest('form'))).toHaveNoViolations();
});
});
Note the second test does more than run a scanner: it proves the error is programmatically associated with the field, which is the difference between a message a sighted user sees and a message a screen reader user hears.
Reading a violation report like a triager
An axe result is a list of rules, each with an impact level, a help string, WCAG tags and an array of failing nodes with selectors and HTML snippets. The mistake is to treat the list as a backlog of equal items. Sort it instead into three buckets and the workload usually collapses.
The first bucket is a real defect with a one-line fix: an image missing an alt attribute, a form control with no label, a duplicate id. Close those in the same pull request. The second bucket is a design decision: a contrast ratio that falls short because the brand palette chose it, or a custom component that needs a proper role before it can be named. Those need a ticket and an owner, not a hurried patch. The third bucket is a contextual false positive, such as a decorative image inside a link whose visible text already names the destination.
Disable rules narrowly and with a comment that survives review. A scoped disable inside a single test documents the reasoning; a global configuration that switches off twenty rules documents nothing and quietly removes the gate you just built. If a rule keeps firing on legitimate patterns, configure it once with a documented exception and keep the rest of the suite strict.
const disabledForDecorativeMedia = {
'image-redundant-alt': { enabled: false },
};
it('renders the gallery without flagging decorative thumbnails', async () => {
const { container } = render(<Gallery items={galleryItems} />);
// The link name comes from the visible caption, so alt text would be read twice.
const results = await axe(container, { rules: disabledForDecorativeMedia });
expect(results).toHaveNoViolations();
});
Keyboard and ARIA state deserve their own tests
Screen reader users drive much of the web through the same focus events a keyboard produces, so keyboard tests double as assistive technology tests. What matters is that state changes are both visible and announced: a menu reports aria-expanded, a selected tab reports aria-selected, a dialog restores focus to the control that opened it, and Escape always has a way out.
Write these tests with real event synthesis rather than calling handlers directly. Firing a click on a div proves nothing about whether the element is reachable, and calling a close function proves nothing about where focus lands afterwards.
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { NavMenu } from './NavMenu';
describe('NavMenu keyboard behaviour', () => {
it('opens on Enter, closes on Escape and returns focus to the trigger', async () => {
render(<NavMenu />);
const user = userEvent.setup();
const trigger = screen.getByRole('button', { name: /products/i });
trigger.focus();
await user.keyboard('{Enter}');
expect(trigger).toHaveAttribute('aria-expanded', 'true');
expect(screen.getByRole('menu')).toBeInTheDocument();
expect(screen.getByRole('menuitem', { name: /pricing/i })).toHaveFocus();
await user.keyboard('{Escape}');
expect(trigger).toHaveAttribute('aria-expanded', 'false');
expect(trigger).toHaveFocus();
});
it('keeps arrow key navigation inside the menu', async () => {
render(<NavMenu />);
const user = userEvent.setup();
const trigger = screen.getByRole('button', { name: /products/i });
trigger.focus();
await user.keyboard('{Enter}{ArrowDown}');
expect(screen.getByRole('menuitem', { name: /pricing/i })).toHaveFocus();
expect(screen.getByRole('menuitem', { name: /docs/i })).not.toHaveFocus();
});
});
The focus assertion after Escape is the one teams forget. Losing focus to the document body is invisible to a sighted developer using a mouse and immediately disorienting to anyone tabbing through the page.
The twenty-minute manual pass
Automation scales, but it cannot hear your interface. Set a timer and run the same script every release so results are comparable rather than anecdotal. Start with the mouse unplugged: tab through the primary flow and confirm that focus is always visible, that the order matches the visual order, that nothing is reachable only by dragging, and that no keyboard trap exists. A focus style removed for aesthetics is a feature removal.
Next, zoom the browser to two hundred percent and then to four hundred percent with reflow enabled. Content should remain readable without horizontal scrolling in a viewport as narrow as a phone. Then toggle the operating system's high contrast or forced colours mode and confirm that boundaries, icons and focus rings are still distinguishable, because many designs rely on a single low-contrast border that disappears entirely.
Finally, turn on a screen reader and walk the same flow. On macOS that is VoiceOver with Safari; on Windows, NVDA with Firefox or Chrome. Check the rotor or element list for heading and landmark structure, confirm that dynamic messages such as toasts and validation errors are announced through a polite live region, and listen for labels that read as gibberish because two fields share a similar name. Record the script as a checklist in the pull request template so the pass happens when the risk is highest, which is right before release.
Gating the pipeline without drowning in noise
A quality gate that fails on every minor issue trains people to ignore it. Run component tests on every pull request, and run page level audits on the routes that matter with thresholds rather than perfection: an accessibility score at or above zero point nine five, no critical impact violations, and no regression against the previous build. Lighthouse keeps history in continuous integration, which turns a vague complaint about quality into a number that moved.
# .github/workflows/accessibility.yml
name: accessibility
on: [pull_request]
jobs:
checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci
- run: npm test -- --runInBand
- run: npx lhci autorun
env:
LHCI_GITHUB_APP_TOKEN: ${{ secrets.LHCI_GITHUB_APP_TOKEN }}
Pair the gate with a monthly deeper session: one person, one assistive technology, one real task, notes shared with the team. Automated checks protect you from regression; the human pass is what discovers that your product is technically compliant and practically unusable.
Common Mistakes
Treating a green axe run as proof that the product is accessible
Fix: Use automation for the machine-checkable third of WCAG, then script a keyboard and screen reader pass for meaning, order and flow.
Disabling a rule globally the first time it fires
Fix: Scope the exception to one test with a comment explaining the context, and keep the remaining rules strict.
Testing only the initial render of a component
Fix: Scan again after interaction, because errors, expanded menus and dialogs introduce the markup where violations usually appear.
Removing focus outlines so screenshots look clean
Fix: Style a clearly visible focus ring with :focus-visible, and assert in tests that focus lands where the keyboard user expects.
Best Practices
- Extend the jest-axe matchers once in a shared setup file so every component test gets a scan for free
- Pair each axe assertion with a behavioural assertion about the accessible name, role or state it protects
- Run contrast checks in a real browser, since JSDOM has no layout and axe cannot compute colour ratios there
- Keep a written manual test script in the pull request template so the screen reader pass happens before release, not after an complaint
- Track violations by impact level and fix critical and serious issues first, because they block tasks rather than annoy them
Key Takeaways
- Automated tools verify roughly a third of WCAG: the part expressible as DOM predicates, never the part about meaning
- jest-axe belongs in component tests, Lighthouse in the build, and a scripted human pass before release; each covers a different failure class
- Read violation reports as three buckets: quick fixes, design decisions and documented exceptions, and never disable a rule globally out of fatigue
- Keyboard tests are assistive technology tests, so assert focus after Escape and aria state after every interactive change
- Contrast cannot be verified in JSDOM, so browser level audits are mandatory rather than optional