Write Tests with Axe DevTools Cypress
Writing accessibility tests with Axe DevTools for Web in Cypress
Producing accessibility scan results with Axe DevTools can be as easy as one line of code. These results can be consumed raw, used in conjunction with an assertion library, or used to create accessibility reports.
These instructions apply to Cypress 10.0 and later.
Prerequisites
In order to test pages with Axe DevTools, you first need it installed in your project. If you haven’t completed this step yet, view the installation guide.
Project Structure
.
├── package.json
├── cypress.config.js
├── cypress
│ ├── e2e
│ │ └── test.cy.js
│ └── support
│ └── e2e.jsSetup
The following is required to use Axe DevTools Cypress.
Include the following line in cypress/support/e2e.js:
import '@axe-devtools/cypress';Within the cypress.config.js file, you will need to add the following:
const { defineConfig } = require('cypress');
const axeDevtoolsCypressPlugin = require("@axe-devtools/cypress/dist/plugin");
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
axeDevtoolsCypressPlugin(on);
return config;
}
}
});Complete Sample File
Call cy.axeAnalyze() and cy.getAxeResults() inside each it() block, and use a unique filename for each test to avoid overwriting results from other tests.
Add this code to the test.cy.js file in the e2e directory:
describe('Axe DevTools Cypress', () => {
it('Scans the home page for accessibility issues', () => {
// Visit the page to test
cy.visit('https://broken-workshop.dequelabs.com')
// Run an accessibility scan on the current page
cy.axeAnalyze()
// Write results to a uniquely named file; use a different name for each test to avoid overwriting
cy.getAxeResults().then(results => {
cy.writeFile('./results/broken-workshop.json', results)
})
})
})