axe-core

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

axe-core - Quick Reference

axe-core 快速参考

When NOT to Use This Skill

本技能不适用场景

  • Manual WCAG compliance audits - Use the
    wcag
    skill for understanding guidelines and manual testing
  • Screen reader testing - axe-core doesn't replace manual screen reader verification
  • Complex ARIA pattern implementation - Use
    wcag
    skill for ARIA authoring practices
  • Accessibility strategy planning - This is for test automation, not accessibility consulting
Deep Knowledge: Use
mcp__documentation__fetch_docs
with technology:
axe-core
for comprehensive documentation on rules, configuration, and integrations.
  • 手动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 library
bash
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-PatternWhy It's WrongCorrect Approach
Running axe on empty/loading statesTests incomplete DOM, false negativesWait for content to load before running axe
Ignoring all violationsDefeats purpose of automated testingFix violations or document exceptions with reasoning
Testing only homepageMost accessibility issues in complex interactionsTest all critical user flows and components
Not configuring WCAG levelTests against all rules, may be too strictSet
withTags(['wcag2a', 'wcag2aa'])
for target level
Running axe synchronously in loopsSlow test executionUse
Promise.all()
for parallel execution
Committing violations to CIPrevents catching regressionsFail builds on new violations
Testing hidden/inactive componentsAxe tests invisible elements unnecessarilyUse
exclude
parameter for hidden sections
No baseline for legacy codeAll violations block progressCreate baseline, track improvements incrementally
反模式问题原因正确做法
在空页面/加载状态下运行axe测试不完整的DOM,会出现假阴性运行axe前等待内容完全加载
忽略所有违规项违背自动化测试的初衷修复违规项,或记录例外情况并说明原因
仅测试首页多数无障碍问题出现在复杂交互场景测试所有核心用户流程和组件
不配置WCAG等级会测试所有规则,可能过于严格如需测试目标等级,设置
withTags(['wcag2a', 'wcag2aa'])
在循环中同步运行axe测试执行速度慢使用
Promise.all()
并行执行
提交违规代码到CI无法拦截回归问题出现新违规项时直接阻断构建
测试隐藏/未激活的组件Axe会不必要地测试不可见元素对隐藏区域使用
exclude
参数排除
遗留代码没有基准线所有违规项都会阻塞进度建立基准线,逐步跟踪优化进度

Quick Troubleshooting

快速问题排查

IssueDiagnosisSolution
axe finds no violations but page is inaccessibleAutomated tools catch only ~30-40% of issuesSupplement with manual keyboard and screen reader testing
"No violations" but form has issuesaxe doesn't test form logic/flowTest form submission, error handling manually
Timeout in Playwright axe testsLarge/complex page takes too longIncrease timeout or analyze specific regions
False positive on custom componentaxe rule doesn't understand patternUse
disableRules
or add proper ARIA to fix
Violations in third-party widgetsCan't modify external codeDocument exceptions, contact vendor, or replace widget
Different results in different browsersBrowser-specific rendering differencesRun axe in multiple browsers, use cross-browser test suite
CI fails but local passesEnvironment differences (timing, content)Ensure consistent test data and wait conditions
Too many violations to fix at onceLegacy codebase with extensive issuesCreate baseline, use
--save
flag to track improvements
问题原因分析解决方案
axe未检测到违规项但页面确实存在无障碍问题自动化工具仅能覆盖约30-40%的问题补充手动键盘测试和屏幕阅读器测试
显示「无违规项」但表单存在问题axe不会测试表单逻辑/流程手动测试表单提交、错误处理逻辑
Playwright axe测试超时大型/复杂页面扫描耗时过长延长超时时间,或仅分析指定区域
自定义组件出现误报axe规则不识别当前模式使用
disableRules
禁用对应规则,或添加正确的ARIA属性修复
第三方组件出现违规无法修改外部代码记录例外情况,联系供应商,或替换组件
不同浏览器下测试结果不同浏览器特定的渲染差异在多个浏览器中运行axe,使用跨浏览器测试套件
CI测试失败但本地测试通过环境差异(加载时序、内容)确保测试数据一致,添加合理的等待条件
违规项过多无法一次性修复遗留代码库存在大量问题建立基准线,使用
--save
参数跟踪优化进度