Home >Web Front-end >JS Tutorial >Automated Testing with jest-axe
When building web applications, ensuring accessibility should be as important as delivering features or fixing bugs. Automated testing tools like jest-axe make it easy to catch common accessibility issues early in development.
jest-axe is a Jest matcher built on top of the axe-core accessibility engine. It allows you to test your rendered components for accessibility violations, integrating seamlessly with your existing Jest test suite.
Addressing accessibility errors early in the development process is crucial for several reasons:
First, install the package:
npm install --save-dev jest-axe
Next, add it to your test file:
import { axe, toHaveNoViolations } from 'jest-axe'; expect.extend(toHaveNoViolations);
Here’s an example of how you can test a simple component for accessibility:
import React from 'react'; import { render } from '@testing-library/react'; import { axe } from 'jest-axe'; function Button() { return <button>Click me</button>; } describe('Button component', () => { it('should have no accessibility violations', async () => { const { container } = render(<Button />); const results = await axe(container); expect(results).toHaveNoViolations(); }); });
If you’re working with Vue, jest-axe integrates just as easily. Here’s an example:
import { mount } from '@vue/test-utils'; import { axe, toHaveNoViolations } from 'jest-axe'; expect.extend(toHaveNoViolations); const Button = { template: '<button>Click me</button>' }; describe('Button component (Vue)', () => { it('should have no accessibility violations', async () => { const wrapper = mount(Button); const results = await axe(wrapper.element); expect(results).toHaveNoViolations(); }); });
By adding jest-axe to your test suite, you’re taking a solid step towards building accessible web applications. However, remember that no tool can guarantee full accessibility. Combine automated testing with manual checks and user testing for the best results.
Happy testing!
The above is the detailed content of Automated Testing with jest-axe. For more information, please follow other related articles on the PHP Chinese website!