如何为自定义组件编写无障碍测试用例?

解读

面试官问“如何为自定义组件编写无障碍测试用例”,并不是想听你背一遍 WAI-ARIA 规范,而是考察三件事:

  1. 你是否把“可访问性”当成组件的交付硬指标,而不是上线前补票;
  2. 你是否能在 Vue 单测体系里把“机器可跑”的自动化用例落地(国内主流是 Jest + Vue Test Utils,也有团队切 Vitest);
  3. 你是否了解国内监管与甲方验收场景——2021 年起,政企项目需符合 GB/T 37668-2019(等效 WCAG 2.1 AA),测试报告里必须出现“键盘可达”“焦点顺序”“语义化标签”“色彩对比”四项硬指标,否则过不了第三方测评。

因此,回答要给出“能在 CI 里跑、能出报告、能复现缺陷”的最小闭环,同时把典型踩坑(中文语音读屏、输入法冲突、低版本 Chrome 内核)点出来,才能体现“资深”。

知识点

  1. 国内合规基线:GB/T 37668-2019 ≈ WCAG 2.1 AA,验收时测评机构会拉 Deque axe-core 规则库跑分,得分低于 90 即视为不通过。
  2. Vue 技术栈测试三层模型:
    • 单元(Unit):聚焦单个组件的语义、角色、状态;
    • 集成(Integration):测键盘焦点顺序、事件冒泡;
    • 端到端(E2E):用真实读屏(NVDA、争渡、永德)跑完整用户流程。
  3. 必备工具链:
    • 自动化规则扫描:jest-axe / vitest-axe(axe-core 封装);
    • 语义查询:Vue Test Utils 的 findByRole, findByLabelText(基于 @testing-library/dom);
    • 键盘仿真:user-event@14 的 keyboard('{Tab}{Enter}');
    • 焦点断言:document.activeElement 与 toHaveFocus();
    • 色彩对比:color-contrast-checker 在 Jest 里断言 expect(contrastRatio).toBeGreaterThan(4.5)。
  4. 读屏差异:中文环境必须验证“争渡 2023 读屏 + 搜狗输入法”组合,否则 aria-live 区域会被输入法截断,导致“提交成功”不朗读。
  5. 常见缺陷:
    • 自定义按钮用 div 实现,缺 role="button" 与键盘回车监听;
    • 弹窗组件焦点未锁(focus trap),Tab 跳出浏览器地址栏;
    • 动态 aria-label 拼接中文变量,读屏出现“百分之二十”而不是“20%”。

答案

下面给出一个可直接落地的“最小合规用例”示例,以 ElementPlus 的二次封装 <MyDialog> 组件为例,目标是通过 axe-core 0 违规、键盘 3 步闭环、读屏可朗读。技术栈:Vue3 + Vitest + jsdom + jest-axe + @testing-library/user-event。

  1. 目录约定 src/components/MyDialog.vue
    src/components/tests/MyDialog.a11y.spec.js
    把无障碍用例独立命名,方便 CI 并行跑。

  2. 组件关键代码(只留可访问性相关)

<template>
  <Teleport to="body">
    <div v-if="modelValue"
         role="dialog"
         aria-modal="true"
         :aria-label="title"
         @keydown.esc="close"
         ref="dialogEl">
      <!-- 焦点陷阱容器 -->
      <div tabindex="0" @focus="focusLast"></div>
      <header>
        <h2 id="dialog-title">{{ title }}</h2>
        <button aria-label="关闭对话框" @click="close" ref="closeBtn">×</button>
      </header>
      <main>
        <slot />
      </main>
      <footer>
        <button @click="confirm" ref="confirmBtn">确定</button>
        <button @click="close">取消</button>
      </footer>
      <div tabindex="0" @focus="focusFirst"></div>
    </div>
  </Teleport>
</template>
<script setup>
import { nextTick, watch } from 'vue'
const props = defineProps({ modelValue: Boolean, title: String })
const emit = defineEmits(['update:modelValue'])
const dialogEl = ref(null), closeBtn = ref(null), confirmBtn = ref(null)

watch(() => props.modelValue, async (v) => {
  if (v) {
    await nextTick()
    closeBtn.value?.focus()
  }
})
function close() { emit('update:modelValue', false) }
function confirm() { emit('confirm'); close() }
function focusFirst() { closeBtn.value?.focus() }
function focusLast()  { confirmBtn.value?.focus() }
</script>
  1. 测试用例(MyDialog.a11y.spec.js)
import { describe, it, expect, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { axe, toHaveNoViolations } from 'jest-axe'
import user from '@testing-library/user-event'
import MyDialog from '../MyDialog.vue'

expect.extend(toHaveNoViolations)

describe('MyDialog 无障碍测试', () => {
  it('axe 扫描应 0 违规', async () => {
    const wrapper = mount(MyDialog, {
      props: { modelValue: true, title: '测试弹窗' }
    })
    const html = wrapper.element.parentNode // jsdom 根节点
    const results = await axe(html, {
      rules: { 'color-contrast': { enabled: false } } // 如样式未加载,先关闭对比度
    })
    expect(results).toHaveNoViolations()
    wrapper.unmount()
  })

  it('Tab 键应在弹窗内部循环', async () => {
    const wrapper = mount(MyDialog, {
      props: { modelValue: true, title: '测试' }
    })
    const closeBtn   = wrapper.find('button[aria-label="关闭对话框"]').element
    const confirmBtn = wrapper.find('button').element // 第一个确定按钮
    // 初始焦点应在关闭按钮
    expect(document.activeElement).toBe(closeBtn)
    // 连续 Tab 正向循环
    await user.keyboard('{Tab}') // 跳到取消
    await user.keyboard('{Tab}') // 跳到尾部哨兵
    await user.keyboard('{Tab}') // 循环回关闭
    expect(document.activeElement).toBe(closeBtn)
    // Shift+Tab 反向
    await user.keyboard('{Shift>}{Tab}{/Shift}')
    expect(document.activeElement).toBe(confirmBtn)
    wrapper.unmount()
  })

  it('ESC 键应关闭弹窗并返还焦点到触发源', async () => {
    const onUpdate = vi.fn()
    const trigger  = document.createElement('button')
    trigger.textContent = '打开'
    document.body.appendChild(trigger)
    trigger.focus() // 模拟用户先点触发按钮

    const wrapper = mount(MyDialog, {
      props: { modelValue: true, 'onUpdate:modelValue': onUpdate }
    })
    await user.keyboard('{Escape}')
    expect(onUpdate).toHaveBeenCalledWith(false)
    await nextTick()
    expect(document.activeElement).toBe(trigger) // 焦点返还
    document.body.removeChild(trigger)
    wrapper.unmount()
  })

  it('读屏应朗读标题与角色', () => {
    // jsdom 无语音,但可断言属性存在
    const wrapper = mount(MyDialog, {
      props: { modelValue: true, title: '用户协议' }
    })
    const dialog = wrapper.find('[role="dialog"]')
    expect(dialog.attributes('aria-label')).toBe('用户协议')
    expect(dialog.attributes('aria-modal')).toBe('true')
    wrapper.unmount()
  })
})
  1. 运行与报告 package.json 脚本:
"test:a11y": "vitest run src/components/__tests__/*.a11y.spec.js --reporter=verbose"

CI 中把输出重定向到 junit.xml,再交给测评机构做合规佐证。

  1. 落地 checklist(面试时可脱口而出)
  • 每个自定义组件都配 *.a11y.spec.js;
  • 必须过 axe-core 0 违规才允许合并 MR;
  • 焦点顺序、ESC 关闭、焦点返还三大交互 100% 用例覆盖;
  • 中文读屏验证在 E2E 阶段由人工补测,记录视频备查;
  • 色彩对比度用真实主题 token 跑,不允许 hardcode 关闭。

拓展思考

  1. 如果组件库要出海,如何一次性通过 WCAG 2.2 与欧盟 EN 301 549?

    • 把 axe-core 规则升到 4.8 以上,新增 target-size、focus-appearance;
    • 用 @guidepup/playwright 做 NVDA 语音断言,实现“机器听写”自动化;
    • 在 Storybook 加 @storybook/addon-a11y,MR 阶段自动评论违规截图,零成本教育设计师。
  2. 低代码平台 90% 页面由拖拽生成,如何批量给 Vue 组件注入无障碍测试?

    • 在物料中心注册时,强制上传 “a11y 测试快照” JSON(jest-axe 结果);
    • 平台渲染器运行时把每个组件的 role、aria-label 作为元数据写进 DOM,供 axe 扫描;
    • 出包阶段用 webpack 插件做“合规门禁”,一旦新增组件缺失快照,直接中断流水线。
  3. 微前端场景下,子应用使用 Qiankun 嵌入主应用,焦点跨沙箱逃逸怎么测?

    • 在单测层用 jsdom 无法模拟,必须在 E2E 层用 Playwright 的 page.waitForFunction 监听 document.activeElement 跨 bundle 变化;
    • 主应用提供 focus-trap 全局公用模块,子应用通过 window.$globalFocusTrap 注入,测试用例断言 Trap 栈深度为 1,防止多层弹窗焦点错乱。

把以上三点作为“加分项”主动抛给面试官,既展示视野,也暗示你具备架构级落地能力,面评通常能再涨一档。