0
0
Cypresstesting~5 mins

cypress-axe for accessibility

Choose your learning style9 modes available
Introduction
We use cypress-axe to check if websites are easy for everyone to use, including people with disabilities. It helps find problems that make websites hard to read or navigate.
When you want to make sure your website works well for people using screen readers.
Before launching a website to catch accessibility issues early.
When you add new features and want to keep your site accessible.
To test if color choices have enough contrast for easy reading.
When you want to follow accessibility laws or guidelines.
Syntax
Cypress
import 'cypress-axe';

cy.injectAxe();
cy.checkA11y();
First, you import cypress-axe to add accessibility commands to Cypress.
Use cy.injectAxe() to add the accessibility testing tool to your page.
Use cy.checkA11y() to run the accessibility checks and see results.
Examples
Visit a page, add axe, then check accessibility on the whole page.
Cypress
cy.visit('https://example.com');
cy.injectAxe();
cy.checkA11y();
Check accessibility only inside the element with class 'main-content'.
Cypress
cy.checkA11y('.main-content');
Run accessibility checks only for specific WCAG rules.
Cypress
cy.checkA11y(null, {
  runOnly: ['wcag2a', 'wcag2aa']
});
Run checks and handle results with a callback function.
Cypress
cy.checkA11y(null, null, (violations) => {
  // custom handling of violations
  expect(violations.length).to.equal(0);
});
Sample Program
This simple HTML page has a heading and a button. We can use cypress-axe to check if it meets accessibility standards.
Cypress
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Accessibility Test</title>
</head>
<body>
  <header>
    <h1>Welcome to Our Site</h1>
  </header>
  <main>
    <button id="clickMe">Click Me</button>
  </main>
</body>
</html>
OutputSuccess
Important Notes
Always run cy.injectAxe() after cy.visit() to load axe on the page.
You can focus checks on specific parts of the page to save time.
Use the browser's DevTools console to see detailed accessibility reports.
Summary
cypress-axe helps find accessibility problems automatically during tests.
Inject axe into your page with cy.injectAxe() before checking.
Use cy.checkA11y() to run accessibility checks and get results.