Detecting accessibility issues on CI with cypress-axe
Unless we check the accessibility of our pages every time we change them, it’s to easy to introduce regressions. Therefore, we should test accessibility during our Continuous Integration (CI) checks.
Cypress-axe allows us to do exactly that, and it’s a good place to do that in Cypress because we already render all the pages in our end-to-end tests and run them during CI.
Setting up cypress-axe
- Install cypress-axe (assuming we already have Cypress installed and configured on our project):
npm install --dev cypress-axe
- Import the commands, add to the cypress/support/index.js:
- Update the plugins file, cypress/plugins/index.js:
We need this for printing the results in the terminal.
- Add a custom Cypress command, cypress/support/commands.js:
This command runs cypress-axe
checkA11y method with a custom violation callback function that prints a list of violations to the terminal, and can be chained to queries.
To run accessibility checks, we need to do two things:
- Inject Axe into the
page —we need to do it once, after calling
- Run the checks using our
command —we can do it multiple times to check the page in different states.
A test case could look like this:
If there are any accessibility violations, the test case fails:
And the list of violations is printed in the terminal:
We could also check a particular area of the page, for example, a modal: