axe-core
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineseaxe-core - Quick Reference
axe-core 快速参考
When NOT to Use This Skill
本技能不适用场景
- Manual WCAG compliance audits - Use the skill for understanding guidelines and manual testing
wcag - Screen reader testing - axe-core doesn't replace manual screen reader verification
- Complex ARIA pattern implementation - Use skill for ARIA authoring practices
wcag - Accessibility strategy planning - This is for test automation, not accessibility consulting
Deep Knowledge: Usewith technology:mcp__documentation__fetch_docsfor comprehensive documentation on rules, configuration, and integrations.axe-core
- 手动WCAG合规审计 - 如需了解指南和手动测试,请使用技能
wcag - 屏幕阅读器测试 - axe-core无法替代手动屏幕阅读器验证
- 复杂ARIA模式实现 - 如需ARIA开发最佳实践,请使用技能
wcag - 无障碍战略规划 - 本技能用于测试自动化,不提供无障碍咨询服务
深度知识:使用工具,指定技术为mcp__documentation__fetch_docs,可获取关于规则、配置和集成的完整文档。axe-core
Setup Base
基础安装
bash
npm install -D @axe-core/react # For React
npm install -D axe-core # Core librarybash
npm install -D @axe-core/react # 适用于React
npm install -D axe-core # 核心库Pattern Essenziali
核心模式
React DevTools Integration
React DevTools集成
typescript
import React from 'react';
import ReactDOM from 'react-dom/client';
if (process.env.NODE_ENV !== 'production') {
import('@axe-core/react').then(axe => {
axe.default(React, ReactDOM, 1000);
});
}typescript
import React from 'react';
import ReactDOM from 'react-dom/client';
if (process.env.NODE_ENV !== 'production') {
import('@axe-core/react').then(axe => {
axe.default(React, ReactDOM, 1000);
});
}Jest/Vitest Integration
Jest/Vitest集成
typescript
import { axe, toHaveNoViolations } from 'jest-axe';
expect.extend(toHaveNoViolations);
test('should have no accessibility violations', async () => {
const { container } = render(<MyComponent />);
const results = await axe(container);
expect(results).toHaveNoViolations();
});typescript
import { axe, toHaveNoViolations } from 'jest-axe';
expect.extend(toHaveNoViolations);
test('should have no accessibility violations', async () => {
const { container } = render(<MyComponent />);
const results = await axe(container);
expect(results).toHaveNoViolations();
});Playwright Integration
Playwright集成
typescript
import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';
test('should not have accessibility issues', async ({ page }) => {
await page.goto('/');
const accessibilityScanResults = await new AxeBuilder({ page }).analyze();
expect(accessibilityScanResults.violations).toEqual([]);
});
// With specific rules
test('should pass WCAG AA', async ({ page }) => {
await page.goto('/');
const results = await new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa'])
.analyze();
expect(results.violations).toEqual([]);
});typescript
import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';
test('should not have accessibility issues', async ({ page }) => {
await page.goto('/');
const accessibilityScanResults = await new AxeBuilder({ page }).analyze();
expect(accessibilityScanResults.violations).toEqual([]);
});
// 搭配指定规则使用
test('should pass WCAG AA', async ({ page }) => {
await page.goto('/');
const results = await new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa'])
.analyze();
expect(results.violations).toEqual([]);
});Cypress Integration
Cypress集成
typescript
// cypress/support/commands.ts
import 'cypress-axe';
// In test
describe('Accessibility', () => {
it('has no violations', () => {
cy.visit('/');
cy.injectAxe();
cy.checkA11y();
});
});typescript
// cypress/support/commands.ts
import 'cypress-axe';
// 测试用例中
describe('Accessibility', () => {
it('has no violations', () => {
cy.visit('/');
cy.injectAxe();
cy.checkA11y();
});
});Programmatic Usage
程序化调用
typescript
import axe from 'axe-core';
async function checkAccessibility() {
const results = await axe.run();
if (results.violations.length > 0) {
console.log('Violations:', results.violations);
}
}typescript
import axe from 'axe-core';
async function checkAccessibility() {
const results = await axe.run();
if (results.violations.length > 0) {
console.log('违规项:', results.violations);
}
}Anti-Patterns
反模式
| Anti-Pattern | Why It's Wrong | Correct Approach |
|---|---|---|
| Running axe on empty/loading states | Tests incomplete DOM, false negatives | Wait for content to load before running axe |
| Ignoring all violations | Defeats purpose of automated testing | Fix violations or document exceptions with reasoning |
| Testing only homepage | Most accessibility issues in complex interactions | Test all critical user flows and components |
| Not configuring WCAG level | Tests against all rules, may be too strict | Set |
| Running axe synchronously in loops | Slow test execution | Use |
| Committing violations to CI | Prevents catching regressions | Fail builds on new violations |
| Testing hidden/inactive components | Axe tests invisible elements unnecessarily | Use |
| No baseline for legacy code | All violations block progress | Create baseline, track improvements incrementally |
| 反模式 | 问题原因 | 正确做法 |
|---|---|---|
| 在空页面/加载状态下运行axe | 测试不完整的DOM,会出现假阴性 | 运行axe前等待内容完全加载 |
| 忽略所有违规项 | 违背自动化测试的初衷 | 修复违规项,或记录例外情况并说明原因 |
| 仅测试首页 | 多数无障碍问题出现在复杂交互场景 | 测试所有核心用户流程和组件 |
| 不配置WCAG等级 | 会测试所有规则,可能过于严格 | 如需测试目标等级,设置 |
| 在循环中同步运行axe | 测试执行速度慢 | 使用 |
| 提交违规代码到CI | 无法拦截回归问题 | 出现新违规项时直接阻断构建 |
| 测试隐藏/未激活的组件 | Axe会不必要地测试不可见元素 | 对隐藏区域使用 |
| 遗留代码没有基准线 | 所有违规项都会阻塞进度 | 建立基准线,逐步跟踪优化进度 |
Quick Troubleshooting
快速问题排查
| Issue | Diagnosis | Solution |
|---|---|---|
| axe finds no violations but page is inaccessible | Automated tools catch only ~30-40% of issues | Supplement with manual keyboard and screen reader testing |
| "No violations" but form has issues | axe doesn't test form logic/flow | Test form submission, error handling manually |
| Timeout in Playwright axe tests | Large/complex page takes too long | Increase timeout or analyze specific regions |
| False positive on custom component | axe rule doesn't understand pattern | Use |
| Violations in third-party widgets | Can't modify external code | Document exceptions, contact vendor, or replace widget |
| Different results in different browsers | Browser-specific rendering differences | Run axe in multiple browsers, use cross-browser test suite |
| CI fails but local passes | Environment differences (timing, content) | Ensure consistent test data and wait conditions |
| Too many violations to fix at once | Legacy codebase with extensive issues | Create baseline, use |
| 问题 | 原因分析 | 解决方案 |
|---|---|---|
| axe未检测到违规项但页面确实存在无障碍问题 | 自动化工具仅能覆盖约30-40%的问题 | 补充手动键盘测试和屏幕阅读器测试 |
| 显示「无违规项」但表单存在问题 | axe不会测试表单逻辑/流程 | 手动测试表单提交、错误处理逻辑 |
| Playwright axe测试超时 | 大型/复杂页面扫描耗时过长 | 延长超时时间,或仅分析指定区域 |
| 自定义组件出现误报 | axe规则不识别当前模式 | 使用 |
| 第三方组件出现违规 | 无法修改外部代码 | 记录例外情况,联系供应商,或替换组件 |
| 不同浏览器下测试结果不同 | 浏览器特定的渲染差异 | 在多个浏览器中运行axe,使用跨浏览器测试套件 |
| CI测试失败但本地测试通过 | 环境差异(加载时序、内容) | 确保测试数据一致,添加合理的等待条件 |
| 违规项过多无法一次性修复 | 遗留代码库存在大量问题 | 建立基准线,使用 |