Accessibility Testing - coursehero/ch-react-workshop GitHub Wiki
Web accessibility allows us to expand the number of users for our apps, helps companies gain trust, and makes apps more useable for everyone. It's also an essential part of every product development, and can be most easily included through integrating accessibility tests into your testing pipeline. Fortunately, Cypress has an official plugin for automated accessibility testing that is easy to set up: cypress-axe, which uses the axe-core
of Deque Labs. Axe is an accessibility testing engine for websites and HTML-based user interfaces that is both lightweight and fast.
Cypress-axe
supports the following accessibility standards:
- WCAG 2.1
- WCAG 2.0
- Section 508
There are three variants of the Testing Library that we need to know:
The Testing Library provides several helpers for querying elements. Learn them all and use in order of priority.
The preferred queries are getByRole
for small tests and findByRole
+ accessible name for Cypress tests.
Example:
cy.findByRole('button', {name: /submit/i})
"submit" here is the accessible name: the name of a user interface element that may be derived from a visible (e.g., the visible text on a button) or invisible (e.g., the text alternative that describes an icon) property of the user interface element. If you'd rather not rely on the visible text (as that may change, you could provide an aria-label
instead).
If none of the preferred queries works for you, you can still use data-testid
and cy.getByTestId()
.
💡 Tip: use the Testing Playground to help debug your HTML for accessibility and to select the best query. |
To use the cypress-axe plugin, install cypress-axe
and axe-core
:
npm install --save-dev cypress-axe axe-core
Then, add the cypress-axe commands by importing the package into the Cypress/support/index.js file
// Cypress/support/index.js
import 'cypress-axe'
You're all set up! Here is how to test violations in a Cypress test (using the cypress-axe plugin):
cy.visit(...)
cy.injectAxe()
cy.checkA11y() // or: cy.checkA11y(undefined, undefined, undefined, true) to temporarily skip failures
Some additional notes on these commands:
-
cy.injectAxe
injects theaxe-core
library into the current page, and needs to be used aftercy.visit
and beforecy.checkA11y
-
cy.checkA11y
will run axe against the document at the point in which it is called. This means that you can call it after interacting with the page to uncover issues introduced as a result of rendering in response to user actions.
The violations will be shown in the dev console as well as in the terminal logs (optional: follow this guide to set terminal logs up).
💡 Tip: consider testing the whole page as well as the component where you're doing dynamic changes. |
- Learn from MDN or Google.
- Test your app using WebAIM.
- Download the axe browser extension.