使用 jest-axe 对组件做快照无障碍断言

解读

国内一线团队已将「无障碍」纳入 CI 红线,面试官问此题,核心想验证三件事:

  1. 你是否真的把 a11y 写进自动化测试,而不是“用 Lighthouse 跑一下”就完事;
  2. 你是否理解快照测试与断言测试的差异,避免“快照绿、无障碍红”的假阴性;
  3. 你是否能在 jest-axe 的基础上,结合业务场景做二次封装,让用例可读、可维护、可阻断流水线。

因此,回答必须给出可落地的代码骨架,并解释每一步的“国内工程痛点”。

知识点

  • jest-axe 本质:把 axe-core 的审计结果转成 Jest 断言,不依赖浏览器,在 JSDOM 里即可运行,适合 CI。
  • 快照测试局限:@testing-library/jest-dom 的快照只会序列化 DOM 结构,不会包含 a11y 缺陷,必须显式调用 expect(...).toHaveNoViolations()。
  • 国内常见踩坑: – 动态弹层(Modal、Drawer)未加 aria-hidden,导致 axe 报“焦点未囚禁”; – 中文图标字体未加 aria-label,被识别为“空按钮”; – 颜色对比度阈值 4.5:1 在深色模式被忽略。
  • 二次封装策略:把 toHaveNoViolations() 再包一层 toPassA11y(),自动过滤产品已确认的误报,并输出中文错误日志,方便测试/产品阅读。

答案

下面给出可直接拷贝到项目的完整示例,基于 React + TypeScript + Jest 27,覆盖快照与断言双保险。

  1. 安装依赖(国内镜像源)
npm i -D jest-axe @testing-library/react @testing-library/jest-dom
# 如用 cnpm 或 yarn,加 --registry=https://registry.npmmirror.com
  1. 配置 jest.setup.js(放在项目根目录)
import 'jest-axe/extend-expect';          // 注入 toHaveNoViolations
import { configure } from '@testing-library/react';

configure({ testIdAttribute: 'data-testid' }); // 与国内测试组习惯保持一致
  1. 二次封装工具函数 src/utils/test-a11y.tsx
import { ReactElement } from 'react';
import { render } from '@testing-library/react';
import { axe, toHaveNoViolations } from 'jest-axe';

expect.extend(toHaveNoViolations);

/**
 * 统一入口:快照 + 无障碍
 * @param ui 组件
 * @param options 透传 render 选项
 */
export async function testA11y(ui: ReactElement, options?: any) {
  const { container } = render(ui, options);

  // 1. 快照断言:保证结构回归
  expect(container.firstChild).toMatchSnapshot();

  // 2. 无障碍断言:保证无红线
  const results = await axe(container);
  expect(results).toHaveNoViolations();
}
  1. 组件用例 src/components/Button/__tests__/index.test.tsx
import React from 'react';
import { testA11y } from '@/utils/test-a11y';
import Button from '../index';

describe('<Button />', () => {
  it('渲染符合快照且无障碍', async () => {
    await testA11y(<Button>保存</Button>);
  });

  it('图标按钮需补 aria-label', async () => {
    await testA11y(<Button icon={<span className="icon-save" />} aria-label="保存" />);
  });
});
  1. 误报过滤(国内设计规范允许 4.0:1 的灰色文字)
    在 jest.setup.js 追加自定义规则:
const { configure } = require('jest-axe');

configure({
  rules: {
    'color-contrast': { enabled: false }, // 如设计已出豁免单,可关闭
  },
});
  1. 流水线集成(GitLab CI 示例)
test-a11y:
  stage: test
  image: node:16-slim
  script:
    - npm ci --registry=https://registry.npmmirror.com
    - npm run test:a11y
  coverage: '/Lines\s*:\s*(\d+\.\d+)%/'
  allow_failure: false   // 红线,阻断合并

运行 npm run test:a11y 后,任何违反 WCAG 2.1 AA 的提交都会被拒绝,同时本地快照 diff 也能提示结构回归。

拓展思考

  1. 多端场景:小程序 WebView 里跑不了 JSDOM,可把同一套用例移植到 miniprogram-simulate + jest-axe-core,在 CI 里起 headless 小程序容器,保证 H5 与小程序双端无障碍一致性。
  2. 交互态覆盖:快照只捕获初始 DOM,需补充用户行为后的审计,例如
    fireEvent.click(screen.getByRole('button', { name: /展开/ }));
    const results = await axe(document.body);
    expect(results).toHaveNoViolations();
    
  3. 性能与噪音平衡:大型列表一次性审计耗时 > 2s,可在 axe 配置里加 resultTypes: ['violations'],只阻断严重级别,warning 走日志告警,避免阻塞开发节奏。
  4. 推动左移:把 testA11y 封装成 VSCode Snippet,开发阶段保存即触发,让问题在“写组件”时暴露,而不是“提测”时返工,真正落地国内高速迭代的敏捷节奏。