We can add accessibility testing to our jest
unit tests with jest-axe
which gives us:
Here we'll see how to use jest-axe
with react-testing-library
to render the components for jest-axe
to audit for accessibility.
The React Testing Library is a very light-weight solution for testing React components. It provides light utility functions on top of react-dom and react-dom/test-utils, in a way that encourages better testing practices.
Instructor: [0:00] To get started using jest-axe with React Testing Library, you'll first need to npm install or yarn add jest-axe, and if you haven't already, React Testing Library, and save it to your development dependencies.
[0:16] Now that that's installed, let's go ahead and write a unit test. Here, I have the scaffolding for a unit test already started. What we'll need to add is, we'll need to import render from React Testing Library. We'll also need to import aXe, and to have no violations from jest-axe. We're already importing the LoginPage component that we want to test for accessibility.
[0:44] The next thing we need to do, is we need to extend Jest's expect function to use jest-axe's, to have no violations, so that we can use it in our expectations. Now, let's write our test. We use React Testing Library's render function to render the component we want to test. We need to pass the container into the aXe function. It will scan that component for any accessibility violations.
[1:11] Finally, we'll use the toHaveNoViolations expectation on that results object, to make sure that there were no accessibility violations found.
[1:20] Let's go ahead and run this test and see what it looks like. We run our test suite by running npm run test. You can see, it finds our login unit test. Here, it's logged our results. We can see that one of our tests failed. Here's what that looks like.
[1:34] Let's fix these issues. We can run it again and see what we get. Now that I think I fixed all of my issues, let me run my test again and see what I get. Here, we can see that this time the test passed.