0
0
Cypresstesting~15 mins

cypress-axe for accessibility - Build an Automation Script

Choose your learning style9 modes available
Check homepage accessibility using cypress-axe
Preconditions (3)
Step 1: Open the homepage URL in the browser
Step 2: Inject the axe-core accessibility testing library into the page
Step 3: Run accessibility checks on the entire page
Step 4: Collect and analyze accessibility violations
✅ Expected Result: No accessibility violations are found on the homepage
Automation Requirements - Cypress with cypress-axe plugin
Assertions Needed:
Assert that there are zero accessibility violations after running axe check
Best Practices:
Use cy.injectAxe() to inject axe-core before running checks
Use cy.checkA11y() to run accessibility checks
Use semantic selectors or data attributes for targeting elements if needed
Run accessibility checks on meaningful page sections or entire page
Fail test if any accessibility violations are detected
Automated Solution
Cypress
/// <reference types="cypress" />
import 'cypress-axe';

describe('Homepage Accessibility Test', () => {
  beforeEach(() => {
    cy.visit('https://example.com');
    cy.injectAxe();
  });

  it('Has no detectable accessibility violations on load', () => {
    cy.checkA11y(null, null, (violations) => {
      expect(violations).to.have.length(0);
    });
  });
});

This test script uses Cypress with the cypress-axe plugin to check accessibility on the homepage.

Import and setup: We import 'cypress-axe' to add accessibility commands.

beforeEach: Visits the homepage URL and injects the axe-core library into the page so accessibility checks can run.

Test case: Runs cy.checkA11y() on the entire page (null selector means whole page). The callback receives any violations found.

Assertion: We assert that the violations array length is zero, meaning no accessibility issues were detected.

This approach ensures the test fails if any accessibility problems exist, helping maintain an accessible website.

Common Mistakes - 4 Pitfalls
Not calling cy.injectAxe() before cy.checkA11y()
Using hardcoded CSS selectors that are brittle for targeting elements
Ignoring accessibility violations by not asserting on the violations array
Running accessibility checks before the page is fully loaded
Bonus Challenge

Now add data-driven testing to check accessibility on three different pages: homepage, about page, and contact page

Show Hint