DEV Community

Cover image for Automatically testing for accessibility issues with jest-axe
Max Rozen
Max Rozen

Posted on • Originally published at maxrozen.com

Automatically testing for accessibility issues with jest-axe

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();
});
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
miguelrodoma95 profile image
Miguel Rodriguez

Any idea if you can do this using and other react/react-native elements instead of html?

Tried it and keep getting error "All page content should be contained by landmarks (region)"