### Install cypress-axe for Cypress v10+ Source: https://github.com/component-driven/cypress-axe/blob/master/README.md Installs cypress-axe and its peer dependencies for Cypress version 10 and above. ```sh npm install --save-dev axe-core cypress cypress-axe ``` -------------------------------- ### Install cypress-axe Source: https://context7.com/component-driven/cypress-axe/llms.txt Install cypress-axe and its peer dependencies. Register the commands in Cypress's support file. ```sh # Cypress v10+ npm install --save-dev axe-core cypress cypress-axe ``` ```js // cypress/support/e2e.js (Cypress v10+) import 'cypress-axe' // cypress/support/index.js (Cypress v9 and below) import 'cypress-axe' ``` ```js const { defineConfig } = require('cypress') module.exports = defineConfig({ e2e: { baseUrl: 'http://localhost:3000', video: false, }, }) ``` -------------------------------- ### Full Real-World Test Suite Example Source: https://context7.com/component-driven/cypress-axe/llms.txt A comprehensive example demonstrating combined usage of context scoping, impact filtering, retry logic, violation callbacks, and conditional failure suppression for a full accessibility test suite. ```javascript // cypress/e2e/full-a11y.cy.js import 'cypress-axe' function logViolations(violations) { cy.task('log', `--- ${violations.length} A11Y VIOLATION(S) ---`) violations.forEach(({ id, impact, description, helpUrl, nodes }) => { cy.task('log', `[${impact.toUpperCase()}] ${id}: ${description}`) cy.task('log', ` Help: ${helpUrl}`) cy.task('log', ` Affected nodes: ${nodes.length}`) }) } describe('Full Accessibility Suite', () => { beforeEach(() => { cy.visit('http://localhost:3000') cy.injectAxe() cy.configureAxe({ rules: [{ id: 'region', enabled: false }] // disable landmark rule globally }) }) it('homepage has no critical WCAG 2.1 AA violations', () => { cy.checkA11y(null, { runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa', 'wcag21aa'] }, includedImpacts: ['critical', 'serious'] }, logViolations) }) it('navigation is fully accessible', () => { cy.checkA11y('nav', {}, logViolations) }) it('modal is accessible after interaction', () => { cy.get('[data-cy=open-modal]').click() cy.checkA11y('.modal', { retries: 3, interval: 200 }, logViolations) }) it('legacy footer has known issues (non-blocking)', () => { cy.checkA11y('footer', { includedImpacts: ['critical'] }, logViolations, true) // skipFailures = true for known legacy issues }) }) ``` -------------------------------- ### Install cypress-axe for Cypress v9 Source: https://github.com/component-driven/cypress-axe/blob/master/README.md Installs a specific version of cypress-axe (0.14.0) and Cypress (v9.6.0) for compatibility with older Cypress versions. ```sh npm install --save-dev axe-core cypress@9.6.0 cypress-axe@0.14.0 ``` -------------------------------- ### cy.configureAxe() Source: https://context7.com/component-driven/cypress-axe/llms.txt Configures axe-core before running checks. This command allows registering custom rules, setting a reporter format, or applying locale overrides. It wraps axe.configure() and must be called after cy.injectAxe(). ```APIDOC ## cy.configureAxe() ### Description Configures axe-core before running checks — allows registering custom rules, setting a reporter format, or applying locale overrides. Wraps `axe.configure()` and must be called after `cy.injectAxe()`. ### Method cy.configureAxe(options) ### Parameters #### Options - **rules** (Array) - Optional - An array of rule configurations. - **reporter** (string) - Optional - The reporter format (e.g., 'v2'). - **locale** (Object) - Optional - Locale overrides for rule descriptions. ### Request Example ```js cy.visit('http://localhost:3000/dashboard') cy.injectAxe() cy.configureAxe({ rules: [ { id: 'color-contrast', enabled: false // disable a specific rule } ], reporter: 'v2', locale: { lang: 'en', rules: { 'color-contrast': { description: 'Ensures color contrast ratio is sufficient' } } } }) cy.checkA11y() ``` ``` -------------------------------- ### Configure axe-core rules and run check Source: https://github.com/component-driven/cypress-axe/blob/master/README.md Configures axe-core with custom options and then checks the page for accessibility violations. ```js it('Has no detectable a11y violations on load (custom configuration)', () => { // Configure aXe and test the page at initial load cy.configureAxe({ branding: { brand: String, application: String }, reporter: 'option', checks: [Object], rules: [Object], locale: Object }) cy.checkA11y() }) ``` -------------------------------- ### cy.configureAxe Source: https://github.com/component-driven/cypress-axe/blob/master/README.md Configures the format of the data used by aXe, allowing for custom rules and options. ```APIDOC ## cy.configureAxe() ### Purpose To configure the format of the data used by aXe. This can be used to add new rules, which must be registered with the library to execute. ### Description User specifies the format of the JSON structure passed to the callback of axe.run. [Link - aXe Docs: axe.configure](https://www.deque.com/axe/documentation/api-documentation/#api-name-axeconfigure) ### Method `cy.configureAxe(options)` ### Parameters #### options (object) - **branding** (object) - Optional - Contains `brand` (String) and `application` (String) properties. - **reporter** (string) - Optional - Specifies the reporter option. - **checks** (Array) - Optional - An array of check objects. - **rules** (Array) - Optional - An array of rule objects. - **locale** (Object) - Optional - Locale configuration object. ### Request Example ```js it('Has no detectable a11y violations on load (custom configuration)', () => { cy.configureAxe({ branding: { brand: String, application: String }, reporter: 'option', checks: [Object], rules: [Object], locale: Object }) cy.checkA11y() }) ``` ``` -------------------------------- ### cy.injectAxe Source: https://github.com/component-driven/cypress-axe/blob/master/README.md Injects the axe-core runtime into the page under test. This command must be run after cy.visit() and before checkA11y. ```APIDOC ## cy.injectAxe() ### Description Injects the `axe-core` runtime into the page under test. This command must be run after `cy.visit()` and before `checkA11y`. ### Method `cy.injectAxe()` ### Parameters #### injectOptions (optional) - **axeCorePath** (string) - Optional - Allows specifying the file path from which `axe-core` will be injected. If not provided, it attempts to resolve `axe-core/axe.min.js` using `require.resolve`, falling back to `node_modules/axe-core/axe.min.js`. ### Request Example ```js beforeEach(() => { cy.visit('http://localhost:9000') cy.injectAxe() }) ``` ### Request Example with axeCorePath ```js beforeEach(() => { cy.visit('http://localhost:9000') cy.injectAxe({ axeCorePath: '' }) }) ``` ``` -------------------------------- ### Import cypress-axe commands Source: https://github.com/component-driven/cypress-axe/blob/master/README.md Imports the cypress-axe commands into your Cypress support file. Use `e2e.js` for Cypress v10+ and `index.js` for older versions. ```js import 'cypress-axe' ``` -------------------------------- ### Configure axe-core with cy.configureAxe Source: https://context7.com/component-driven/cypress-axe/llms.txt Configures axe-core before running checks, allowing custom rules, reporter formats, or locale overrides. Wraps axe.configure() and must be called after cy.injectAxe(). ```js it('runs with a custom axe configuration', () => { cy.visit('http://localhost:3000/dashboard') cy.injectAxe() cy.configureAxe({ rules: [ { id: 'color-contrast', enabled: false // disable a specific rule } ], reporter: 'v2', locale: { lang: 'en', rules: { 'color-contrast': { description: 'Ensures color contrast ratio is sufficient' } } } }) cy.checkA11y() }) ``` -------------------------------- ### cy.checkA11y Source: https://github.com/component-driven/cypress-axe/blob/master/README.md Runs axe against the document to identify accessibility issues. ```APIDOC ## cy.checkA11y() ### Description Runs axe against the document at the point in which it is called. This allows for uncovering accessibility issues introduced after interactions with the page. ### Method `cy.checkA11y(context, options, violationCallback)` ### Parameters #### context (optional) Defines the scope of the analysis - the part of the DOM that you would like to analyze. This can be the entire document or a specific selector (e.g., class name, ID, selector). #### options (optional) Configuration options for the axe-core run. #### violationCallback (optional) A callback function to be executed when accessibility violations are found. ``` -------------------------------- ### Inject axe-core with cy.injectAxe Source: https://context7.com/component-driven/cypress-axe/llms.txt Injects the axe-core runtime into the current page. Must be called after cy.visit() and before cy.checkA11y(). Optionally specify a custom path to the axe-core bundle. ```js // cypress/e2e/accessibility.cy.js describe('Accessibility', () => { beforeEach(() => { cy.visit('http://localhost:3000') cy.injectAxe() // With a custom axe-core path: // cy.injectAxe({ axeCorePath: 'node_modules/axe-core/axe.min.js' }) }) it('passes a basic axe audit on the homepage', () => { cy.checkA11y() }) }) ``` -------------------------------- ### Inject axe-core into the page Source: https://github.com/component-driven/cypress-axe/blob/master/README.md Injects the axe-core runtime into the page. Must be called after `cy.visit()` and before `cy.checkA11y()`. ```js beforeEach(() => { cy.visit('http://localhost:9000') cy.injectAxe() }) ``` -------------------------------- ### Basic cy.checkA11y Usage Source: https://context7.com/component-driven/cypress-axe/llms.txt Runs an axe-core audit against the full document or a specific element. Fails the test with an assertion error if violations are found. ```js describe('Page-level accessibility checks', () => { beforeEach(() => { cy.visit('http://localhost:3000') cy.injectAxe() }) it('has no a11y violations on initial load', () => { cy.checkA11y() // Assertion: "0 accessibility violations were detected" }) it('has no a11y violations on a specific element', () => { cy.checkA11y('#main-content') }) it('has no a11y violations after a button click', () => { cy.get('button#open-modal').click() cy.checkA11y('.modal') }) }) ``` -------------------------------- ### Configure TypeScript for cypress-axe Source: https://github.com/component-driven/cypress-axe/blob/master/README.md Adds cypress-axe types to your Cypress `tsconfig.json` file for TypeScript projects. ```json { "compilerOptions": { "baseUrl": "./", "target": "es5", "lib": ["esnext", "dom"], "types": ["cypress", "cypress-axe"] }, "include": ["."] } ``` -------------------------------- ### Basic cypress-axe Usage Source: https://github.com/component-driven/cypress-axe/blob/master/README.md Use `cy.checkA11y()` to test for accessibility violations on page load or after interactions. It can be applied to the entire page or a specific context. ```javascript // Basic usage it('Has no detectable a11y violations on load', () => { // Test the page at initial load cy.checkA11y() }) ``` ```javascript // Applying a context and run parameters it('Has no detectable a11y violations on load (with custom parameters)', () => { // Test the page at initial load (with context and options) cy.checkA11y('.example-class', { runOnly: { type: 'tag', values: ['wcag2a'] } }) }) ``` ```javascript // Basic usage after interacting with the page it('Has no a11y violations after button click', () => { // Interact with the page, then check for a11y issues cy.get('button').click() cy.checkA11y() }) ``` -------------------------------- ### Inject axe-core with custom path Source: https://github.com/component-driven/cypress-axe/blob/master/README.md Injects axe-core into the page, allowing specification of a custom path for the axe-core script. ```js beforeEach(() => { cy.visit('http://localhost:9000') cy.injectAxe({ axeCorePath: '' }) }) ``` -------------------------------- ### Custom Violation Logging with cy.task Source: https://github.com/component-driven/cypress-axe/blob/master/README.md Implement a `violationCallback` to perform custom actions, such as logging detailed violation information to the terminal using `cy.task`. ```javascript module.exports = (on, config) => { on('task', { log(message) { console.log(message) return null }, table(message) { console.table(message) return null } }) } ``` -------------------------------- ### Filtering and Retrying cypress-axe Checks Source: https://github.com/component-driven/cypress-axe/blob/master/README.md Configure `cy.checkA11y()` with options to filter violations by impact level, retry checks with initial findings, or skip test failures for temporary measures. ```javascript it('Has no detectable a11y violations on load (filtering to only include critical impact violations)', () => { // Test on initial load, only report and assert for critical impact items cy.checkA11y(null, { includedImpacts: ['critical'] }) }) ``` ```javascript it('Only logs a11y violations while allowing the test to pass', () => { // Do not fail the test when there are accessibility failures cy.checkA11y(null, null, null, true) }) ``` ```javascript it('Has no a11y violations after asynchronous load', () => { // Retry the check if there are initial failures cy.checkA11y(null, { retries: 3, interval: 100 }) }) ``` -------------------------------- ### Retry accessibility checks with `retries` and `interval` Source: https://context7.com/component-driven/cypress-axe/llms.txt Use `retries` and `interval` options to re-run accessibility checks if violations are found. This is useful for content that loads dynamically or asynchronously. `interval` specifies the delay in milliseconds between retries. ```javascript it('waits for dynamic content before auditing', () => { cy.visit('http://localhost:3000/async-page') cy.injectAxe() cy.checkA11y(null, { retries: 5, interval: 500 // retry up to 5 times, 500ms apart }) }) ``` -------------------------------- ### Register `log` and `table` tasks for terminal logging Source: https://context7.com/component-driven/cypress-axe/llms.txt Register custom `log` and `table` tasks within Cypress configuration to enable terminal output from violation callbacks. This allows for structured logging of accessibility issues directly in the console. ```javascript // cypress.config.js const { defineConfig } = require('cypress') module.exports = defineConfig({ e2e: { baseUrl: 'http://localhost:3000', setupNodeEvents(on) { on('task', { log(message) { console.log(message) return null }, table(data) { console.table(data) return null } }) } } }) ``` -------------------------------- ### cy.checkA11y() Source: https://context7.com/component-driven/cypress-axe/llms.txt Runs an axe-core audit against the full document or a specific element. Fails the test with an assertion error if any violations are found. It can optionally accept a context parameter to scope the audit and an options object for further configuration. ```APIDOC ## cy.checkA11y() ### Description Runs an axe-core audit against the full document (or a specific element) at the point in the test where it is called. Fails the test with an assertion error if any violations are found. ### Method cy.checkA11y([context], [options]) ### Parameters #### Context - **context** (string | Object | null) - Optional - Scopes the accessibility audit to a specific part of the DOM using any valid CSS selector, element reference, or axe `ElementContext` object. #### Options - **includedImpacts** (Array) - Optional - Filters violations to only those matching specific impact levels (`"minor"`, `"moderate"`, `"serious"`, `"critical"`). ### Request Example ```js // Basic usage cy.checkA11y() // Audit a specific element cy.checkA11y('#main-content') // Audit only the navigation and footer cy.checkA11y('nav') // Audit using an axe ElementContext object (include/exclude) cy.checkA11y({ include: [['#main-content']], exclude: [['#third-party-widget']] }) // Filter violations by impact level cy.checkA11y(null, { includedImpacts: ['critical', 'serious'] }) ``` ### Response #### Success Response - **Assertion**: "0 accessibility violations were detected" #### Failure Response - **Assertion Error**: Details about the accessibility violations found. ``` -------------------------------- ### cy.checkA11y Context Parameter Source: https://context7.com/component-driven/cypress-axe/llms.txt Scopes the accessibility audit to a specific DOM part using CSS selectors, element references, or axe ElementContext objects. ```js it('audits only the navigation and footer', () => { cy.visit('http://localhost:3000') cy.injectAxe() // Audit a single CSS selector cy.checkA11y('nav') // Audit using an axe ElementContext object (include/exclude) cy.checkA11y({ include: [['#main-content']], exclude: [['#third-party-widget']] }) }) ``` -------------------------------- ### Custom violation logging with `violationCallback` Source: https://context7.com/component-driven/cypress-axe/llms.txt Implement a `violationCallback` function to handle accessibility violations. This function receives an array of violation objects, allowing for custom logging, reporting, or integration with other services. ```javascript // cypress/support/e2e.js — register a terminal logging task // (in cypress.config.js setupNodeEvents or plugins file) module.exports = (on) => { on('task', { log(message) { console.log(message); return null }, table(message) { console.table(message); return null } }) } // In the spec file: function terminalLog(violations) { cy.task( 'log', `${violations.length} accessibility violation${violations.length === 1 ? '' : 's'} detected` ) const violationData = violations.map(({ id, impact, description, nodes }) => ({ id, impact, description, nodes: nodes.length })) cy.task('table', violationData) } it('logs violations to the terminal without failing the test', () => { cy.visit('http://localhost:3000') cy.injectAxe() cy.checkA11y(null, null, terminalLog) }) ``` -------------------------------- ### cy.checkA11y Options: includedImpacts Source: https://context7.com/component-driven/cypress-axe/llms.txt Filters violations to specific impact levels (minor, moderate, serious, critical). Useful for gradually introducing accessibility testing on legacy applications. ```js it('only fails on critical and serious violations', () => { cy.visit('http://localhost:3000/legacy-page') cy.injectAxe() cy.checkA11y(null, { includedImpacts: ['critical', 'serious'] }) }) ``` -------------------------------- ### Custom Accessibility Violation Logging in Cypress Source: https://github.com/component-driven/cypress-axe/blob/master/README.md Define a custom function to log accessibility violations to the terminal using Cypress tasks. This allows for detailed reporting of issues found by axe-core. ```javascript // Define at the top of the spec file or just import it function terminalLog(violations) { cy.task( 'log', `${violations.length} accessibility violation${violations.length === 1 ? '' : 's'} ${violations.length === 1 ? 'was' : 'were'} detected` ) // pluck specific keys to keep the table readable const violationData = violations.map( ({ id, impact, description, nodes }) => ({ id, impact, description, nodes: nodes.length }) ) cy.task('table', violationData) } // Then in your test... it('Logs violations to the terminal', () => { cy.checkA11y(null, null, terminalLog) }) ``` -------------------------------- ### Append Text to Element with Timeout Source: https://github.com/component-driven/cypress-axe/blob/master/test/index.html This JavaScript snippet appends text to an element after a delay. Ensure the target element exists before execution. ```javascript setTimeout(() => { document.getElementById('link').appendChild(document.createTextNode('Link')); }, 101); ``` -------------------------------- ### Restrict accessibility checks with `runOnly` options Source: https://context7.com/component-driven/cypress-axe/llms.txt The `runOnly` option allows you to specify which rules or tags axe-core should evaluate. This is useful for focusing on specific accessibility standards like WCAG 2.1 AA. ```javascript it('checks only WCAG 2.1 AA rules', () => { cy.visit('http://localhost:3000') cy.injectAxe() cy.checkA11y(null, { runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'] } }) }) ``` -------------------------------- ### Suppress test failures with `skipFailures` parameter Source: https://context7.com/component-driven/cypress-axe/llms.txt Set the `skipFailures` parameter to `true` to log accessibility violations without causing the test to fail. This is useful for temporary measures during remediation efforts. ```javascript it('observes but does not fail on a11y violations', () => { cy.visit('http://localhost:3000/known-issues') cy.injectAxe() cy.checkA11y(null, null, null, true) // Test always passes; violations appear in the Cypress command log }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.