如何在 CI 流程中集成 axe-core 进行无障碍测试?

解读

国内大厂(阿里、腾讯、字节、美团等)在 2022 年后陆续把「无障碍合规」写进前端门禁,CI 红线一旦扫描出「可访问性阻塞级问题」,MR 直接打回。 axe-core 是 GitHub 上 star 最高的开源无障碍检测引擎,支持 WCAG 2.1 AA 规则集,且提供 CLI、Puppeteer、Cypress、Playwright 等多种调用方式,天然适合嵌入 GitLab-CI / GitHub Actions / Jenkins 等国内主流流水线。
面试官问「怎么集成」,核心想看三点:

  1. 是否知道「只在本地跑一遍」远远不够,必须放在 CI 的「构建后、测试前」阶段,阻塞发布。
  2. 是否理解「Vue 单页路由切换」带来的动态 DOM 更新,需要遍历所有页面状态,而不是只扫首页。
  3. 是否掌握「国产环境常见坑」:Docker 镜像源、headless Chrome 下载失败、报告本地化、误报过滤、性能兜底(超时/内存)。

知识点

  1. axe-core 运行模式
    • 浏览器注入:通过 Puppeteer/Playwright 把 axe.min.js 注入到真实渲染页,再调用 axe.run() 采集 violations。
    • 静态扫描:仅分析 HTML 字符串,无法捕获 Vue 渲染后的 DOM,不推荐。
  2. Vue 技术栈配套工具
    • vue-axe:只在开发环境生效,生产打包自动剔除,不能用于 CI。
    • jest-axe:基于 JSDOM,适合单元级别,无法覆盖交互路由,CI 只能做补充。
  3. CI 阶段设计
    • 构建阶段:vite build → dist 产物。
    • 服务阶段:用 npx serve -s dist 启动静态服务器(国内常用 nginx:alpine 镜像)。
    • 扫描阶段:并行跑 puppeteer + axe-core 脚本,遍历 router.options.routes 生成的完整 URL 列表。
    • 质量门禁:violations 数 > 0 时以非 0 exit code 中断流水线,并输出 JUnit XML 供 GitLab 面板可视化。
  4. 国产化细节
    • 镜像加速:Dockerfile 里把 registry.npmmirror.com 设为 npm 源,Puppeteer 下载 Chromium 时加 PUPPETEER_DOWNLOAD_HOST=https://npmmirror.com/mirrors。
    • 误报过滤:在 axe.run({ rules: { 'color-contrast': { enabled: false } } }) 关闭已知设计类误报,或维护 .axeignore.json 文件。
    • 性能兜底:单页扫描加 timeout=30s,内存超限加 --max-old-space-size=4096,并做增量扫描(只扫 MR 变更的页面)。

答案

以 GitLab-CI 为例,给出可直接落地的 yml 片段与扫描脚本,兼顾国内网络与 Vue 路由特点。

  1. 安装依赖
npm i -D axe-core puppeteer chalk xml2js
  1. 编写 scripts/axe-scan.js
import puppeteer from 'puppeteer';
import axeCore from 'axe-core';
import { resolve } from 'path';
import { writeFileSync } from 'fs';

const PORT = process.env.CI_PORT || 4173;
const HOST = `http://localhost:${PORT}`;

// 根据 src/router/index.js 自动生成完整路径
const routePaths = ['/', '/login', '/dashboard', '/profile']; // 实际可动态读取路由表

(async () => {
  const browser = await puppeteer.launch({
    headless: true,
    executablePath: process.env.CI ? '/usr/bin/chromium-browser' : undefined,
    args: ['--no-sandbox', '--disable-setuid-sandbox']
  });
  const violations = [];
  for (const path of routePaths) {
    const page = await browser.newPage();
    await page.goto(`${HOST}${path}`, { waitUntil: 'networkidle2' });
    await page.addScriptTag({ path: resolve('node_modules/axe-core/axe.min.js') });
    const results = await page.evaluate(() => axe.run());
    if (results.violations.length) {
      violations.push(...results.violations.map(v => ({ ...v, url: path })));
    }
    await page.close();
  }
  await browser.close();

  // 生成 JUnit XML 供 GitLab 解析
  const junit = `
<testsuites>
  <testsuite name="axe" tests="${violations.length}" failures="${violations.length}">
    ${violations.map((v, i) => `
      <testcase name="${v.id}">
        <failure message="${v.description}">${v.help} @ ${v.url}</failure>
      </testcase>
    `).join('')}
  </testsuite>
</testsuites>`;
  writeFileSync('axe-junit.xml', junit);

  if (violations.length) {
    console.error(`❌ 发现 ${violations.length} 条无障碍阻塞问题`);
    process.exit(1);
  }
  console.log('✅ 无障碍检测通过');
})();
  1. .gitlab-ci.yml 关键阶段
stages:
  - build
  - a11y
  - test

variables:
  PUPPETEER_DOWNLOAD_HOST: "https://npmmirror.com/mirrors"

build:
  stage: build
  image: node:18-alpine
  script:
    - npm config set registry https://registry.npmmirror.com
    - npm ci
    - npm run build
  artifacts:
    paths:
      - dist/

a11y:
  stage: a11y
  image: buildkite/puppeteer:18-alpine
  dependencies:
    - build
  script:
    - npm config set registry https://registry.npmmirror.com
    - npm ci --only=dev
    - npx serve -s dist -l 4173 &
    - sleep 5
    - node scripts/axe-scan.js
  artifacts:
    when: always
    reports:
      junit: axe-junit.xml
    expire_in: 7 days
  allow_failure: false   // 阻塞发布
  1. 效果
    MR 触发后,a11y 阶段自动启动 headless Chrome,遍历所有路由,若存在 violations,GitLab 直接红叉并列出详细规则说明,开发必须修复后方可合并。

拓展思考

  1. 增量扫描:解析 MR 的 git diff,只扫描变更的页面和组件,CI 耗时从 3min 降到 30s。
  2. 双轨验证:单元层用 jest-axe 检测组件快照,端到端层用 axe-core 检测真实 DOM,两者互补,避免漏网之鱼。
  3. 设计系统对接:把无障碍规则写进 Design Token(颜色对比、最小字号),在 Storybook 中通过 @storybook/addon-a11y 实时高亮,提前把问题消灭在 UI 评审阶段。
  4. 合规报告:国内政企项目需出具《信息系统无障碍符合性声明》,可将 axe 结果转换成 GB/T 37668-2019 格式,配合第三方机构审计,直接满足政府招标要求。