Max RozenTwitter
AboutNewsletter

Automatically testing for accessibility (a11y) 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();
});

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.

Get The Newsletter!

    No spam, ever.

    Unsubscribe at any time.

    WebMentions

    0 ❤️
    0 💬
    No further replies found. Tweet about this post and it will show up here!
    rssTwitterGitHub

    © 2020 Max Rozen. All rights reserved.