返回博客

使用 Storybook 进行无障碍测试

通过集成工具获得快速反馈

loading
Varun Vachhar
@winkerVSbecks
最后更新于

美国有26%的成年人至少有一种残障。当你改善无障碍性时,它会对你现有和未来的客户产生巨大影响。这也是一项法律要求。

检查无障碍性最准确的方法是在真实设备上手动测试。但这需要专业的知识和大量时间。这两者在前端团队中都非常稀缺。

Twilio、Adobe 和 Shopify 的团队结合使用自动化和手动测试。自动化可以轻松捕获常见的无障碍问题。手动 QA 则用于需要人工关注的更棘手问题。

有许多深入探讨无障碍性原则的资源,所以我们这里不再赘述。本文将向你展示如何使用 Storybook 自动化无障碍测试。这是一种实用方法,可以帮你发现和解决大部分可能遇到的问题。

为何选择自动化?

在我们开始之前,先了解一下常见的残障类型:视觉、听觉、行动、认知、言语和神经系统。这些用户残障带来了应用的需求,例如:

  • ⌨ 键盘导航
  • 🗣 屏幕阅读器支持
  • 👆 触摸友好
  • 🎨 足够高的颜色对比度
  • ⚡️ 减少动画
  • 🔍 缩放

过去,你需要通过在各种浏览器、设备和屏幕阅读器上检查每个组件来验证这些需求。但这手动操作很不切实际,因为应用程序有几十个组件,而且界面也在不断更新。

自动化加速你的工作流程

自动化工具根据WCAG规则和其他行业认可的最佳实践,对渲染的 DOM 进行启发式审计。它们是第一道 QA 防线,用于捕获明显的无障碍违规问题。

例如,Axe 平均可以自动发现 57% 的 WCAG 问题。这使得团队可以将专家资源集中于需要手动审查的更复杂问题。

许多团队使用Axe 库,因为它可以集成到大多数现有的测试环境中。例如,Twilio Paste 团队使用jest-axe 集成。而 Shopify Polaris 和 Adobe Spectrum 团队则使用Storybook 插件版本。

在整个开发过程中运行这些检查,可以缩短反馈周期并更快地修复问题。以下是工作流程的样子:

  1. 👨🏽‍💻 开发期间:使用 Storybook 专注于单个组件。使用 A11y 插件模拟视力缺陷并在组件级别运行无障碍审计。
  2. QA 阶段:将 Axe 审计集成到你的功能测试流程中。对所有组件运行检查以捕获回归问题。

教程

让我们看看这个工作流程的实际应用。我们将使用我在先前一篇文章中介绍过的 Taskbox 应用。获取代码并跟着操作。

安装无障碍插件

Storybook 的无障碍插件在当前 story 上运行 Axe。它在一个面板中可视化测试结果,并标出所有存在违规的 DOM 节点。

要安装该插件,运行:yarn add -D @storybook/addon-a11y。然后,将 '@storybook/addon-a11y' 添加到你的 .storybook/main.js 文件中的 addons 数组里。

// .storybook/main.js
const path = require('path');
 
const toPath = (_path) => path.join(process.cwd(), _path);
 
module.exports = {
 stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
 addons: [
   '@storybook/addon-links',
   '@storybook/addon-essentials',
   '@storybook/preset-create-react-app',
   '@storybook/addon-a11y',
 ],
 webpackFinal: async (config) => {...},
};

边编码边测试无障碍性

先前博客文章中,我们学习了如何隔离组件并将其所有用例捕获为 stories。例如,下面是 Task 组件的所有 stories。在开发阶段,你可以循环查看每个 story,以验证组件外观并发现任何无障碍问题。

// src/components/Task.stories.js
import React from 'react';
import { Task } from './Task';
 
export default {
 component: Task,
 title: 'Task',
 argTypes: {
   onArchiveTask: { action: 'onArchiveTask' },
   onTogglePinTask: { action: 'onTogglePinTask' },
   onEditTitle: { action: 'onEditTitle' },
 },
};
 
const Template = (args) => <Task {...args} />;
 
export const Default = Template.bind({});
Default.args = {
 task: {
   id: '1',
   title: 'Buy milk',
   state: 'TASK_INBOX',
 },
};
 
export const Pinned = Template.bind({});
Pinned.args = {
 task: {
   id: '2',
   title: 'QA dropdown',
   state: 'TASK_PINNED',
 },
};
 
export const Archived = Template.bind({});
Archived.args = {
 task: {
   id: '3',
   title: 'Write schema for account menu',
   state: 'TASK_ARCHIVED',
 },
};
 
const longTitleString = `This task's name is absurdly large. In fact, I think if I keep going I might end up with content overflow. What will happen? The star that represents a pinned task could have text overlapping. The text could cut-off abruptly when it reaches the star. I hope not!`;
 
export const LongTitle = Template.bind({});
LongTitle.args = {
 task: {
   id: '4',
   title: longTitleString,
   state: 'TASK_INBOX',
 },
};

注意看,插件发现了两个违规问题。第一个,“确保前景和背景颜色之间的对比度符合 WCAG 2 AA 对比度阈值”,特定于 archived(归档)状态。这基本上意味着文本和背景之间的对比度不足。我们可以通过将文本颜色更改为稍微深一些的灰色来修复这个问题——从 gray.400 改为 gray.600

// src/components/Task.js
import React from 'react';
import PropTypes from 'prop-types';
import {
 Checkbox,
 Flex,
 IconButton,
 Input,
 Box,
 VisuallyHidden,
} from '@chakra-ui/react';
import { StarIcon } from '@chakra-ui/icons';
 
export const Task = ({
 task: { id, title, state },
 onArchiveTask,
 onTogglePinTask,
 onEditTitle,
 ...props
}) => (
 
 // code omitted for brevity
 
   <Box width="full" as="label">
     <VisuallyHidden>Edit</VisuallyHidden>
     <Input
       variant="unstyled"
       flex="1 1 auto"
       color={state === 'TASK_ARCHIVED' ? 'gray.600' : 'gray.700'}
       textDecoration={state === 'TASK_ARCHIVED' ? 'line-through' : 'none'}
       fontSize="sm"
       isTruncated
       value={title}
       onChange={(e) => onEditTitle(e.target.value, id)}
     />
   </Box>
 
   // code omitted for brevity
 </Flex>
);
 
Task.propTypes = {
 task: PropTypes.shape({
   id: PropTypes.string.isRequired,
   title: PropTypes.string.isRequired,
   state: PropTypes.string.isRequired,
 }),
 onArchiveTask: PropTypes.func.isRequired,
 onTogglePinTask: PropTypes.func.isRequired,
 onEditTitle: PropTypes.func.isRequired,
};

第二个违规问题,“确保<li>元素被语义化使用”,表明 DOM 结构不正确。Task 组件渲染一个<li>元素。然而,在它的 stories 中,它没有被<ul>包裹。这说得通。这些 stories 是为 Task 组件准备的。<ul> 实际上是由 TaskList 提供的。因此,DOM 结构将在 TaskList 的 stories 中验证。所以,忽略这个错误是安全的。实际上,我们可以继续为所有 Task 的 stories 禁用这条规则。

// src/components/Task.stories.js
import React from 'react';
import { Task } from './Task';
 
export default {
 component: Task,
 title: 'Task',
 argTypes: {
   onArchiveTask: { action: 'onArchiveTask' },
   onTogglePinTask: { action: 'onTogglePinTask' },
   onEditTitle: { action: 'onEditTitle' },
 },
 parameters: {
   a11y: {
     config: {
       rules: [{ id: 'listitem', enabled: false }],
     },
   },
 },
};
 
// remaining code omitted for brevity

你现在可以对所有其他组件重复这个过程。

将无障碍测试集成到 Storybook 中,可以简化你的开发工作流程。在开发组件时,你无需在不同的工具之间切换。你需要的一切都在浏览器中。你甚至可以模拟视力障碍,例如氘色盲(绿色弱)、绿色盲或蓝色盲。

防止回归

组件是相互依赖的——一个组件的更改可能会意外地破坏其他组件。为了确保不会引入无障碍违规问题,我们需要在合并更改之前对所有组件运行 Axe。

Stories 是基于 ES6 模块格式编写的,允许你将它们与其他测试框架一起重用。在上一篇文章中,我们探讨了如何将stories 导入 Jest 并使用 Testing Library 验证交互。下面是 InboxScreen 的测试文件示例:

// src/InboxScreen.test.js
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import {
 render,
 waitFor,
 cleanup,
 within,
 fireEvent,
} from '@testing-library/react';
import { composeStories } from '@storybook/testing-react';
import { getWorker } from 'msw-storybook-addon';
import * as stories from './InboxScreen.stories';
 
describe('InboxScreen', () => {
 afterEach(() => {
   cleanup();
 });
 
 // Clean up after all tests are done, preventing this
 // interception layer from affecting irrelevant tests
 afterAll(() => getWorker().close());
 
 const { Default } = composeStories(stories);
 
 it('should pin a task', async () => {
   const { queryByText, getByRole } = render(<Default />);
 
   await waitFor(() => {
     expect(queryByText('You have no tasks')).not.toBeInTheDocument();
   });
 
   const getTask = () => getByRole('listitem', { name: 'Export logo' });
 
   const pinButton = within(getTask()).getByRole('button', { name: 'pin' });
 
   fireEvent.click(pinButton);
 
   const unpinButton = within(getTask()).getByRole('button', {
     name: 'unpin',
   });
 
   expect(unpinButton).toBeInTheDocument();
 });
 
 // More interaction tests
 it('should archive a task', async () => {...});
 it('should edit a task', async () => {...});
});

类似地,我们可以使用Jest Axe 集成来对组件运行无障碍测试。首先安装它:yarn add -D jest-axe

接下来,添加一个运行 Axe 并检查违规的 it 块。Jest-axe 还提供了一个方便的断言 toHaveNoViolations,可以通过一个函数调用来验证这一点。

// src/InboxScreen.test.js
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import {
 render,
 waitFor,
 cleanup,
 within,
 fireEvent,
} from '@testing-library/react';
import { axe, toHaveNoViolations } from 'jest-axe';
import { composeStories } from '@storybook/testing-react';
import { getWorker } from 'msw-storybook-addon';
import * as stories from './InboxScreen.stories';
 
expect.extend(toHaveNoViolations);
 
describe('InboxScreen', () => {
 afterEach(() => {
   cleanup();
 });
 
 // Clean up after all tests are done, preventing this
 // interception layer from affecting irrelevant tests
 afterAll(() => getWorker().close());
 
 const { Default } = composeStories(stories);
 
 // Run axe
 it('Should have no accessibility violations', async () => {
   const { container, queryByText } = render(<Default />);
 
   await waitFor(() => {
     expect(queryByText('You have no tasks')).not.toBeInTheDocument();
   });
 
   const results = await axe(container);
   expect(results).toHaveNoViolations();
 });
 
 it('should pin a task', async () => {...});
 it('should archive a task', async () => {...});
 it('should edit a task', async () => {...});
});

运行 yarn test 启动 Jest。它将执行所有交互测试,并同时运行无障碍审计。现在,你可以在修改代码的任何时候运行整个测试套件。这能帮你捕获回归问题。

我们已经介绍了如何将自动化无障碍测试融入 UI 开发工作流程。这并不能让你的应用完全无障碍。你仍然需要使用辅助技术(如 VoiceOver 或 NVDA)测试界面。然而,自动化确实能为你节省时间,并尽早发现问题。

结论

Web 无障碍性并不容易——在迫近的截止日期、业务目标和技术债务之间平衡无障碍性可能会让人不知所措。

像 Axe 和 Storybook 无障碍插件这样的工具可以集成到你现有的开发工作流程中,并提供快速的反馈回路。在构建 UI 时发现并修复问题可以节省时间。更重要的是,使界面无障碍能为你的所有用户带来更好的体验!

将测试用例编写成 stories 意味着我们可以将它们重用于各种类型的测试。stories 文件成为组件所有行为的单一事实来源。接下来,我们将探讨另一个示例——用户流程测试。我们将介绍如何使用 Cypress 来验证跨多个组件执行的任务。加入邮件列表,以便在更多 UI 测试文章发布时收到通知。

加入 Storybook 邮件列表

获取最新新闻、更新和发布信息

7,180开发者及更多

我们正在招聘!

加入 Storybook 和 Chromatic 背后的团队。构建被数十万开发者在生产环境中使用的工具。远程优先。

查看职位

热门文章

交互测试先睹为快

使用 Storybook 的 play 函数测试连接组件
loading
Dominic Nguyen

测试用户流程

验证你的 UI 端到端工作正常
loading
Varun Vachhar

如何测试组件交互

了解如何模拟用户行为并运行功能检查
loading
Varun Vachhar
加入社区
7,180开发者及更多
为何使用为何选择 Storybook组件驱动 UI
文档指南教程更新日志遥测
社区插件参与其中博客
展示探索项目组件词汇表
开源软件
Storybook - Storybook 中文

特别鸣谢 Netlify CircleCI