
Security News
TypeScript is Porting Its Compiler to Go for 10x Faster Builds
TypeScript is porting its compiler to Go, delivering 10x faster builds, lower memory usage, and improved editor performance for a smoother developer experience.
jest-axe is a Jest matcher for aXe for testing accessibility. It allows developers to integrate accessibility checks into their Jest test suites, ensuring that their web applications meet accessibility standards.
Accessibility Testing
This feature allows you to test for accessibility violations in your HTML. The code sample demonstrates how to use jest-axe to check if a rendered HTML string has any accessibility violations.
const { axe, toHaveNoViolations } = require('jest-axe');
expect.extend(toHaveNoViolations);
test('should demonstrate this matcher`s usage', async () => {
const render = () => '<img src="#" alt="test" />';
const html = render();
const results = await axe(html);
expect(results).toHaveNoViolations();
});
axe-core is the underlying library used by jest-axe for accessibility testing. It provides a comprehensive set of rules for accessibility checks and can be used directly in various environments, including Node.js and browsers. Compared to jest-axe, axe-core is more low-level and requires more setup to integrate with testing frameworks.
cypress-axe is a plugin for Cypress that allows you to run aXe accessibility checks within your Cypress end-to-end tests. It is similar to jest-axe but is designed for use with Cypress instead of Jest, making it suitable for integration and end-to-end testing rather than unit testing.
pa11y is an accessibility testing tool that can be used to run automated accessibility tests on web pages. It provides a command-line interface and can be integrated into CI/CD pipelines. While jest-axe is focused on Jest integration, pa11y offers a broader range of usage scenarios, including command-line usage and integration with other testing frameworks.
Custom Jest matcher for axe for testing accessibility
The GDS Accessibility team found that around ~30% of access barriers are missed by automated testing.
Tools like axe are similar to code linters such as eslint or stylelint: they can find common issues but cannot guarantee that what you build works for users.
You'll also need to:
Color contrast checks do not work in JSDOM so are turned off in jest-axe.
npm install --save-dev jest jest-axe jest-environment-jsdom
TypeScript users can install the community maintained types package:
npm install --save-dev @types/jest-axe
/**
* @jest-environment jsdom
*/
const { axe, toHaveNoViolations } = require('jest-axe')
expect.extend(toHaveNoViolations)
it('should demonstrate this matcher`s usage', async () => {
const render = () => '<img src="#"/>'
// pass anything that outputs html to axe
const html = render()
expect(await axe(html)).toHaveNoViolations()
})
Note, you can also require
'jest-axe/extend-expect'
which will callexpect.extend
for you. This is especially helpful when using the jestsetupFilesAfterEnv
configuration.
const React = require('react')
const { render } = require('react-dom')
const App = require('./app')
const { axe, toHaveNoViolations } = require('jest-axe')
expect.extend(toHaveNoViolations)
it('should demonstrate this matcher`s usage with react', async () => {
render(<App/>, document.body)
const results = await axe(document.body)
expect(results).toHaveNoViolations()
})
const React = require('react')
const App = require('./app')
const { render } = require('@testing-library/react')
const { axe, toHaveNoViolations } = require('jest-axe')
expect.extend(toHaveNoViolations)
it('should demonstrate this matcher`s usage with react testing library', async () => {
const { container } = render(<App/>)
const results = await axe(container)
expect(results).toHaveNoViolations()
})
Note: If you're using
react testing library
<9.0.0 you should be using thecleanup
method. This method removes the rendered application from the DOM and ensures a clean HTML Document for further testing.
If you're using React Portals, use the baseElement
instead of container
:
it('should work with React Portals as well', async () => {
const { baseElement } = render(<App/>)
const results = await axe(baseElement)
expect(results).toHaveNoViolations()
})
const App = require('./App.vue')
const { mount } = require('@vue/test-utils')
const { axe, toHaveNoViolations } = require('jest-axe')
expect.extend(toHaveNoViolations)
it('should demonstrate this matcher`s usage with vue test utils', async () => {
const wrapper = mount(Image)
const results = await axe(wrapper.element)
expect(results).toHaveNoViolations()
})
const App = require('./app')
const { render } = require('@testing-library/vue')
const { axe, toHaveNoViolations } = require('jest-axe')
expect.extend(toHaveNoViolations)
it('should demonstrate this matcher`s usage with react testing library', async () => {
const { container } = render(<App/>)
const results = await axe(container)
expect(results).toHaveNoViolations()
})
Note: If you're using
vue testing library
<3.0.0 you should be using thecleanup
method. This method removes the rendered application from the DOM and ensures a clean HTML Document for further testing.
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { axe } from "jest-axe";
import { SomeComponent } from "./some.component";
describe("SomeComponent", () => {
let fixture: ComponentFixture<SomeComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [SomeComponent],
});
fixture = TestBed.createComponent(SomeComponent);
});
it("should create", async () => {
const results = await axe(fixture.nativeElement);
expect(results).toHaveNoViolations();
});
});
Note: You may need to extend jest by importing
jest-axe/extend-expect
attest-setup.ts
thrown: "Exceeded timeout of 5000 ms for a test. Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
aXe core does not work when timers (setTimeout) are mocked. When using jest.useFakeTimers()
aXe core will timeout often causing failing tests.
We recommend renabling the timers temporarily for aXe:
jest.useRealTimers();
const results = await axe(wrapper.element);
jest.useFakeTimers();
The axe
function allows options to be set with the same options as documented in axe-core:
const { axe, toHaveNoViolations } = require('jest-axe')
expect.extend(toHaveNoViolations)
it('should demonstrate this matcher`s usage with a custom config', async () => {
const render = () => `
<div>
<img src="#"/>
</div>
`
// pass anything that outputs html to axe
const html = render()
const results = await axe(html, {
rules: {
// for demonstration only, don't disable rules that need fixing.
'image-alt': { enabled: false }
}
})
expect(results).toHaveNoViolations()
})
All page content must be contained by landmarks (region)
When testing with aXe sometimes it assumes you are testing a page. This then results in unexpected violations for landmarks for testing isolation components.
You can disable this behaviour with the region
rule:
const { configureAxe } = require('jest-axe')
const axe = configureAxe({
rules: {
// disable landmark rules when testing isolated components.
'region': { enabled: false }
}
})
If you find yourself repeating the same options multiple times, you can export a version of the axe
function with defaults set.
Note: You can still pass additional options to this new instance; they will be merged with the defaults.
This could be done in Jest's setup step
// Global helper file (axe-helper.js)
const { configureAxe } = require('jest-axe')
const axe = configureAxe({
rules: {
// for demonstration only, don't disable rules that need fixing.
'image-alt': { enabled: false }
}
})
module.exports = axe
// Individual test file (test.js)
const { toHaveNoViolations } = require('jest-axe')
const axe = require('./axe-helper.js')
expect.extend(toHaveNoViolations)
it('should demonstrate this matcher`s usage with a default config', async () => {
const render = () => `
<div>
<img src="#"/>
</div>
`
// pass anything that outputs html to axe
const html = render()
expect(await axe(html)).toHaveNoViolations()
})
The configuration object passed to configureAxe
, accepts a globalOptions
property to configure the format of the data used by axe and to add custom checks and rules. The property value is the same as the parameter passed to axe.configure.
// Global helper file (axe-helper.js)
const { configureAxe } = require('jest-axe')
const axe = configureAxe({
globalOptions: {
checks: [/* custom checks definitions */]
},
// ...
})
module.exports = axe
An array which defines which impact level should be considered. This ensures that only violations with a specific impact on the user are considered. The level of impact can be "minor", "moderate", "serious", or "critical".
// Global helper file (axe-helper.js)
const { configureAxe } = require('jest-axe')
const axe = configureAxe({
impactLevels: ['critical'],
// ...
})
module.exports = axe
Refer to Developing Axe-core Rules for instructions on how to develop custom rules and checks.
FAQs
Custom Jest matcher for aXe for testing accessibility
The npm package jest-axe receives a total of 655,689 weekly downloads. As such, jest-axe popularity was classified as popular.
We found that jest-axe demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
TypeScript is porting its compiler to Go, delivering 10x faster builds, lower memory usage, and improved editor performance for a smoother developer experience.
Research
Security News
The Socket Research Team has discovered six new malicious npm packages linked to North Korea’s Lazarus Group, designed to steal credentials and deploy backdoors.
Security News
Socket CEO Feross Aboukhadijeh discusses the open web, open source security, and how Socket tackles software supply chain attacks on The Pair Program podcast.