DEV Community

loading...
Cover image for Automatically testing for accessibility issues with jest-axe

Automatically testing for accessibility issues with jest-axe

Max Rozen
Frontend Dev at Atlassian. Writes about React & building a SaaS while employed. Building PerfBeacon.com.
Originally published at maxrozen.com ・1 min read

Hey, you! Does your project have jest already installed?

Do you wish management would care more about accessibility but just can't get them to invest or pay attention?

A few design systems I've worked with had the following code to prevent app-wide accessibility regressions, and it's so simple yet powerful that I had to share.

import React from 'react';
import { render } from '@testing-library/react`;
import { axe, toHaveNoViolations } from 'jest-axe';

expect.extend(toHaveNoViolations);

function AccessibleForm() {
  return (
    <form>
      <label htmlFor="email">Email</label>
      <input id="email" placeholder="email" />
    </form>
  );
}

test('accessible forms pass axe', async () => {
  const { container } = render(<AccessibleForm />);
  expect(await axe(container)).toHaveNoViolations();
});

Credit to Kent C. Dodds' TestingJavaScript.com course for the above snippet

With a few lines of code, auditing your entire design system for accessibility issues suddenly becomes surprisingly doable.

Without @testing-library/react, the code is more or less the same. Using Enzyme, you mount() your component, and pass it to jest-axe to validate.

It's worth noting that while this can find issues with inaccessible HTML, it doesn't guarantee your components are actually accessible. To do that, you'll want to involve actual people with disabilities involved in your research. For more information about jest-axe, see the GitHub repo.

Further reading

Google's actually has a pretty comprehensive article on auditing accessibility at https://web.dev/accessibility-auditing-react/ - however it mainly touches on catching issues via eslint or while running the application in development, rather than using your test suite.

Discussion (0)

Forem Open with the Forem app