npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

cypress-axe-core

v2.0.0

Published

Test accessibility with axe-core in Cypress

Downloads

10,462

Readme

cypress-axe-core

npm Node.js CI status

Test accessibility with axe-core in Cypress.

⚠️ UPDATE: cypress-axe now supports Cypress 8 (latest release). So you should consider using/switching to the orignal package.

Forked from cypress-axe

Reasons:

  • to upgrade dependencies (i.e. Cypress ^7 & axe-core ^4)
  • RFC 75 👀
  1. Installation and Setup
  2. Examples
  3. Commands

Installation and Setup

  1. Install required packages. Assuming you have Cypress installed already, you will only need to:
npm install --save-dev axe-core cypress-axe-core
  1. Include the commands by importing cypress-axe-core in cypress/support/index.js file:
import 'cypress-axe-core'
  1. Enable results logging by defining cy.tasks in cypress/plugins/index.js file:
module.exports = (on, config) => {
  on('task', {
    log(message) {
      console.log(message)
      return null
    },

    table(message) {
      console.table(message)
      return null
    }
  })
}

NOTE: You can control how results are displayed via the violationsCb config option

After following the steps above (and defining cy.tasks), violations will be displayed as follows:

  • Cypress Default Cypress output

  • Terminal Default terminal output

  • Browser Default browser console output

TypeScript

If you’re using TypeScript, add cypress-axe-core types to your Cypress’s tsconfig.json file:

{
  "compilerOptions": {
    "baseUrl": "./",
    "target": "es5",
    "lib": ["esnext", "dom"],
    "types": ["cypress", "cypress-axe-core"]
  },
  "include": ["."]
}

Examples

Simple

it('passes axe', () => {
  cy.visit('/')
  cy.injectAxe()
  // ...

  cy.checkA11y() // checks the whole document

  cy.get('#mobile-menu').checkA11y() // checks id="mobile-menu only

  cy.wrap({ exclude: ['.not-me'] }).checkA11y() // checks the whole document except class=".not-me"
})

Customised

Leveraging Cypress commands, you can create your own custom command that calls cy.checkA11y with the config you want. For example, if you only want to assert against serious & critical violations but ignore color-contrast rule, you can do something like this:

// cypress/support/commands.js
Cypress.Commands.add(
  'checkAxeViolations',
  { prevSubject: 'optional' },
  (context, options, label) => {
    cy.wrap(context).checkA11y(
      {
        shouldFailFn: violations =>
          violations.filter(
            v =>
              v.id !== 'color-contrast' &&
              ['serious', 'critical'].includes(v.impact)
          ),
        ...options
      },
      label
    )
  }
)

// some.spec.js
it('passes custom axe tests', () => {
  cy.visit('/')
  cy.injectAxe()
  // ...
  cy.checkAxeViolations() // 👈
})

Commands

cy.injectAxe

This will inject the axe-core runtime into the page under test. You must run this after a call to cy.visit() and before you run the checkA11y command.

You run this command with cy.injectAxe() either in your test, or in a beforeEach, as long as the visit comes first.

beforeEach(() => {
  cy.visit('http://localhost:9000')
  cy.injectAxe()
})

cy.checkA11y

When not chained to another element, it will run against the whole document. You can have it at the end of your test (after other interaction assertions) so it checks against all possible violations. It accepts the same (optional) config object that cy.configureCypressAxe accepts

Note: if you have a toggle-able element i.e. a side menu, make sure it's on (shown) by the time cy.checkA11y is called, otherwise you might end up with some false-positive cases. Or, you can target those elements directly to make sure they're tested

cy.get('#menu-button').click()
cy.get('#side-menu-container').checkA11y()

cy.configureCypressAxe

Instead of wrapping or overwriting cy.checkA11y, you can configure it. It accepts the following:

  • axeOptions passed to axe-core.
  • shouldFailFn function that returns array of violations to check for.
  • skipFailures if true, it will log the violations but not assert against them.
  • violationsCb reporter function that receives the result.

The default violationsCb function assumes that cy.task('log') and cy.task('table') have been defined already during the Installation & setup. If you don't want to define those tasks, you can pass a function here to control how results are outputted.

cy.configureCypressAxe({
  axeOptions: [], // axe.RunOptions[]
  shouldFailFn: violations => violations,
  skipFailures: false,
  violationsCb: ({
    filename: 'test.spec.ts', // spec filename
    results: [], // violations axe.Result[]
    label: 'my custom component', // if passed to checkA11y
  }) => void,
})

cy.configureAxe

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

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()
})

Authors

The project was created by Andy Van Slaars, and maintained by Artem Sapegin.

Contributors

Thanks goes to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome!

License

MIT License, see the included License.md file.