Docs
Storybook Docs

可访问性测试

Web 可访问性是指使网站和应用对所有人(无论其能力或使用的技术如何)都具有可访问性和包容性的实践。这意味着支持键盘导航、屏幕阅读器支持、足够的颜色对比度等要求。

¥Web accessibility is the practice of making websites and apps accessible and inclusive to all people, regardless of ability or the technology they’re using. That means supporting requirements such as keyboard navigation, screen reader support, sufficient color contrast, etc.

无障碍不仅是正确的做法,而且越来越受到人们的重视。例如,欧洲无障碍 act 计划于 2025 年 6 月生效。同样,在美国,类似 美国禁用法案 (ADA)《康复法案》第 508 条 的法律适用于许多面向公众的服务。许多这些规则都基于 WCAG,这是一项旨在使 Web 内容可访问的标准化指南。

¥Accessibility is not only the right thing to do, but it is increasingly mandated. For example, the European accessibility act is scheduled to go into law in June 2025. Similarly in the US, laws like the Americans with Disabilities Act (ADA) and Section 508 of the Rehabilitation Act apply to many public-facing services. Many of these laws are based on WCAG, a standardized guideline for making web content accessible.

无障碍测试会根据基于 WCAG 规则和其他行业认可的最佳实践的一组启发式方法,审核渲染的 DOM。它们充当 QA 的第一行,以捕获明显的可访问性违规行为。

¥Accessibility tests audit the rendered DOM against a set of heuristics based on WCAG rules and other industry-accepted best practices. They act as the first line of QA to catch blatant accessibility violations.

安装

¥Install the addon

Storybook 提供了一个 Accessibility (a11y) 插件,以帮助确保你的组件具有可访问性。它建立在 Deque 的 axe-core 库 之上,后者会自动捕获 高达 57% 的 WCAG 问题

¥Storybook provides an Accessibility (a11y) addon to help ensure the accessibility of your components. It is built on top of Deque’s axe-core library, which automatically catches up to 57% of WCAG issues.

运行此命令在你的项目中安装并配置插件:

¥Run this command to install and configure the addon in your project:

npx storybook add @storybook/addon-a11y

Storybook 的 add 命令可自动补齐插件的安装和设置。要手动安装,请参阅我们的 documentation 了解如何安装插件。

¥Storybook's add command automates the addon's installation and setup. To install it manually, see our documentation on how to install addons.

你的 Storybook 现在将包含一些用于检查组件无障碍功能的功能,包括工具栏中用于模拟不同视力障碍的按钮,以及用于检查违规行为的无障碍插件面板。

¥Your Storybook will now include some features to check the accessibility of your components, including a button in the toolbar to simulate different vision impairments and an Accessibility addon panel to check for violations.

Storybook UI with accessibility features annotated

与 Vitest 插件集成

¥Integration with Vitest addon

辅助功能插件旨在与 Vitest 插件 集成,以便你可以在运行组件测试的同时使用 运行辅助功能测试

¥The accessibility addon is designed to integrate with the Vitest addon, so that you can run accessibility tests alongside your component tests.

自动配置:

¥Automatic configuration:

在已安装 @storybook/addon-a11y 的项目中运行 npx storybook add @storybook/addon-vitest 时,Storybook 会自动执行以下操作:

¥When you run npx storybook add @storybook/addon-vitest in a project that already has @storybook/addon-a11y installed, Storybook will automatically:

  1. 更新 .storybook/vitest.setup.ts 以包含 Accessibility 插件的注解

    ¥Update .storybook/vitest.setup.ts to include the Accessibility addon's annotations

  2. 配置辅助功能测试以与组件测试同时运行

    ¥Configure accessibility tests to run alongside component tests

这允许你在 Storybook UI 和 CI 环境中自动运行组件测试的辅助功能测试。

¥This allows you to run accessibility tests automatically with your component tests in both the Storybook UI and in CI environments.

手动配置:

¥Manual configuration:

如果你需要手动配置(例如,如果跳过了自动迁移),你可以将以下内容添加到 .storybook/vitest.setup.ts 中:

¥If you need to configure this manually (for example, if the automigration was skipped), you can add the following to your .storybook/vitest.setup.ts:

import * as previewAnnotations from '@storybook/preview-api';
// Replace your-renderer with the renderer you are using, e.g. react, svelte, vue3, etc.
import { setProjectAnnotations } from '@storybook/your-renderer';
import * as a11yAddonAnnotations from '@storybook/addon-a11y/preview';
 
const annotations = setProjectAnnotations([
  previewAnnotations,
  a11yAddonAnnotations,
]);
 
// Run Storybook's beforeAll hook
beforeAll(annotations.beforeAll);

如果你在 Storybook 中的所有故事都使用 CSF 工厂,则无需更新 .storybook/vitest.setup.ts

¥If you are using CSF Factories for all of the stories in your Storybook, you do not need to update .storybook/vitest.setup.ts.

检查违规

¥Check for violations

导航到故事时,将运行自动无障碍检查,并在无障碍插件面板中报告结果。

¥When you navigate to a story, automated accessibility checks are run and the results are reported in the Accessibility addon panel.

结果分为三个子选项卡:

¥The results are broken down into three sub-tabs:

  • 违规行为是指已知的违反 WCAG 规则和最佳实践的行为。

    ¥Violations are known violations of WCAG rules and best practices

  • 通过的是已知非违规行为

    ¥Passes are known non-violations

  • “不完整”高亮了你需要手动确认的区域,因为它们无法自动检查。

    ¥Incomplete highlights areas that you should confirm manually because they could not be checked automatically

配置

¥Configure

由于该插件基于 axe-core 构建,因此许多可用配置都与其可用选项相对应:

¥Because the addon is built on top of axe-core, much of the configuration available maps to its available options:

属性默认描述
parameters.a11y.context'body'上下文 传递给 axe.run。定义要针对哪些元素运行检查。
parameters.a11y.config(见下文)配置已传递给 axe.configure()。最常用于 配置单个规则
parameters.a11y.options{}选项 传递给 axe.run。可用于调整所检查的规则集。
parameters.a11y.testundefined确定与 Vitest 插件一起运行时的测试行为。更多详情如下
globals.a11y.manualundefined设置为 true 以防止故事在访问时被自动分析。更多详情如下
Default parameters.a11y.config

默认情况下,Storybook 禁用 区域规则,这通常不适用于故事中的组件,并且可能导致误报。

¥By default, Storybook disables the region rule, which does not typically apply to components in stories and can lead to false negatives.

{
rules: [
  {
    id: 'region',
    enabled: false,
  }
]
}

我们将分享一些示例来展示如何使用其中一些配置属性。

¥We’ll share examples to show how to use some of these configuration properties.

这里,它们应用于项目中的所有故事,即 .storybook/preview.ts

¥Here, they are applied to all stories in a project, in .storybook/preview.ts:

.storybook/preview.ts
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
import type { Preview } from '@storybook/your-framework';
 
const preview: Preview = {
  parameters: {
    a11y: {
      /*
       * Axe's context parameter
       * See https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#context-parameter
       * to learn more. Typically, this is the CSS selector for the part of the DOM you want to analyze.
       */
      context: 'body',
      /*
       * Axe's configuration
       * See https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#api-name-axeconfigure
       * to learn more about the available properties.
       */
      config: {},
      /*
       * Axe's options parameter
       * See https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#options-parameter
       * to learn more about the available options.
       */
      options: {},
    },
  },
  initialGlobals: {
    a11y: {
      // Optional flag to prevent the automatic check
      manual: true,
    },
  },
};
 
export default preview;

你还可以将配置应用于文件(在 meta 中)中的所有故事或单个故事:

¥You can also apply the configuration for all stories in a file (in the meta) or an individual story:

Button.stories.ts
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
import type { Meta, StoryObj } from '@storybook/your-framework';
 
import { Button } from './Button';
 
const meta = {
  component: Button,
  parameters: {
    a11y: {
      /*
       * Axe's context parameter
       * See https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#context-parameter
       * to learn more.
       */
      context: {},
      /*
       * Axe's configuration
       * See https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#api-name-axeconfigure
       * to learn more about the available properties.
       */
      config: {},
      /*
       * Axe's options parameter
       * See https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#options-parameter
       * to learn more about the available options.
       */
      options: {},
      /*
       * Configure test behavior
       * See: https://storybook.js.org/docs/next/writing-tests/accessibility-testing#test-behavior
       */
      test: 'error',
    },
  },
  globals: {
    a11y: {
      // Optional flag to prevent the automatic check
      manual: true,
    },
  },
} satisfies Meta<typeof Button>;
export default meta;
 
type Story = StoryObj<typeof meta>;
 
export const ExampleStory: Story = {
  parameters: {
    a11y: {
      // ...same config available as above
    },
  },
  globals: {
    a11y: {
      // ...same config available as above
    },
  },
};

规则集

¥Rulesets

该插件使用 axe-core 库来运行可访问性检查。默认情况下,它会运行一组基于 WCAG 2.0 和 2.1 指南的规则以及一些最佳实践:

¥The addon uses the axe-core library to run accessibility checks. By default, it runs a set of rules that are based on the WCAG 2.0 and 2.1 guidelines, as well as some best practices:

你可以找到这些规则集的细分,以及 axe-core 文档 中可用的其他规则集。

¥You can find a breakdown of these rulesets, as well as the other rulesets available in axe-core’s documentation.

要更改检查的规则(例如,检查 WCAG 2.2 AA 或 WCAG 2.x AAA 规则),请使用 runOnly 选项

¥To change the rules that are checked against (e.g. to check against WCAG 2.2 AA or WCAG 2.x AAA rules), use the runOnly option:

.storybook/preview.ts
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
import type { Preview } from '@storybook/your-framework';
 
const preview: Preview = {
  parameters: {
    a11y: {
      options: {
        /*
         * Opt in to running WCAG 2.x AAA rules
         * Note that you must explicitly re-specify the defaults (all but the last array entry)
         * See https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#options-parameter-examples for more details
         */
        runOnly: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'best-practice', 'wcag2aaa'],
      },
    },
  },
};
 
export default preview;

单独规则

¥Individual rules

你还可以启用、禁用或配置单个规则。这可以在 parameters.a11y 对象的 config 属性中完成。例如:

¥You can also enable, disable, or configure individual rules. This can be done in the config property of the parameters.a11y object. For example:

Button.stories.ts
// ...rest of story file
 
export const IndividualA11yRulesExample: Story = {
  parameters: {
    a11y: {
      config: {
        rules: [
          {
            // The autocomplete rule will not run based on the CSS selector provided
            id: 'autocomplete-valid',
            selector: '*:not([autocomplete="nope"])',
          },
          {
            // Setting the enabled option to false will disable checks for this particular rule on all stories.
            id: 'image-alt',
            enabled: false,
          },
        ],
      },
    },
  },
};

测试行为

¥Test behavior

你可以使用 parameters.a11y.test 参数 配置可访问性测试,这决定了使用 Vitest 插件test-runner 运行时,故事的可访问性测试的行为。该参数接受三个值:

¥You can configure accessibility tests with the parameters.a11y.test parameter, which determines the behavior of accessibility tests for a story when run with either the Vitest addon or the test-runner. The parameter accepts three values:

描述
'off'请勿运行可访问性测试(你仍然可以通过插件面板手动验证)
'todo'运行可访问性测试;违反规则会在 Storybook UI 中返回警告
'error'运行可访问性测试;违反规则会在 Storybook UI 和 CLI/CI 中返回失败的测试

与其他参数一样,你可以在 .storybook/preview.js|ts 中的项目级别、故事文件默认导出的组件级别或单个故事级别定义它。例如,要使文件中除一个故事之外的所有故事的可访问性测试失败:

¥Like other parameters, you can define it at the project level in .storybook/preview.js|ts, the component level in the default export of the story file, or the individual story level. For example, to fail on accessibility tests for all stories in a file except one:

Button.stories.ts
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
import type { Meta, StoryObj } from '@storybook/your-framework';
 
import { Button } from './Button';
 
const meta = {
  component: Button,
  parameters: {
    // 👇 Applies to all stories in this file
    a11y: { test: 'error' },
  },
} satisfies Meta<typeof Button>;
export default meta;
 
type Story = StoryObj<typeof meta>;
 
// 👇 This story will use the 'error' value and fail on accessibility violations
export const Primary: Story = {
  args: { primary: true },
};
 
// 👇 This story will not fail on accessibility violations
//    (but will still run the tests and show warnings)
export const NoA11yFail: Story = {
  parameters: {
    a11y: { test: 'todo' },
  },
};

为什么值叫做 "todo" 而不是 "warn"?此值旨在用作代码库中的字面量 TODO。它可以用来标记那些你知道存在可访问性问题但尚未准备好修复的故事。这样,你就可以跟踪它们并在以后解决它们。

¥Why is the value called "todo" instead of "warn"? This value is intended to serve as a literal TODO in your codebase. It can be used to mark stories that you know have accessibility issues but are not ready to fix yet. This way, you can keep track of them and address them later.

'off' 值仅应用于无需进行可访问性测试的故事,例如用于演示组件使用中的反模式的故事。

¥The 'off' value should only be used for stories that do not need to be tested for accessibility, such as one used to demonstrate an antipattern in a component's usage.

禁用单个规则 不适用于你的用例时,你也可以使用它们。

¥You can also disable individual rules when they are not applicable to your use case.

排除的元素

¥Excluded elements

有时,可能需要从可访问性检查中排除某些元素。为此,你可以定义自定义 context 来选择在运行检查时包含(或排除)哪些元素。例如,此故事将忽略带有 no-a11y-check 类的元素:

¥Sometimes, it may be necessary to exclude certain elements from the accessibility checks. For this, you can define a custom context to select which elements are included (or excluded) when running checks. For example, this story will ignore elements with the class no-a11y-check:

Button.stories.ts
// ...rest of story file
 
export const ExampleStory: Story = {
  parameters: {
    a11y: {
      /*
       * Axe's context parameter
       * See https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#context-parameter
       * to learn more.
       */
      context: {
        include: ['body'],
        exclude: ['.no-a11y-check'],
      },
    },
  },
};

禁用自动检查

¥Disable automated checks

禁用自动无障碍检查后,当你导航到故事或执行 使用 Vitest 插件运行测试 操作时,插件将不会运行任何测试。你仍然可以在“辅助功能”插件面板中手动触发检查。这对于不旨在可访问的故事很有用,例如那些演示反模式或特定用例的故事。

¥When you disable automated accessibility checks, the addon will not run any tests when you navigate to a story or when you run the tests with the Vitest addon. You can still manually trigger checks in the Accessibility addon panel. This is useful for stories that are not meant to be accessible, such as those demonstrating an antipattern or a specific use case.

通过将以下全局变量添加到故事的导出或组件的默认导出中,禁用故事或组件的自动可访问性检查:

¥Disable automated accessibility checks for stories or components by adding the following globals to your story's export or component's default export:

MyComponent.stories.ts|tsx
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, nextjs-vite, etc.
import type { Meta, StoryObj } from '@storybook/your-framework';
 
import { MyComponent } from './MyComponent';
 
const meta = {
  component: MyComponent,
} satisfies Meta<typeof MyComponent>;
 
export default meta;
type Story = StoryObj<typeof meta>;
 
export const NonA11yStory: Story = {
  globals: {
    a11y: {
      // This option disables all automatic a11y checks on this story
      manual: true,
    },
  },
};

运行可访问性测试

¥Run accessibility tests

使用 Vitest 插件

¥With the Vitest addon

如果你使用的是 Vitest 插件,则可以将无障碍测试作为组件测试的一部分,通过以下方式运行:

¥If you're using the Vitest addon, you can run your accessibility tests, as part of component tests, in these ways:

要在 Storybook UI 中运行可访问性测试,首先展开侧边栏中的测试小部件,然后选中“可访问性”复选框。现在,当你按下“运行组件测试”按钮时,可访问性测试将与你配置的任何其他测试一起运行。

¥To run accessibility tests in the Storybook UI, first expand the testing widget in the sidebar and check the Accessibility checkbox. Now, when you press the Run component tests button, the accessibility tests will be run along with any other tests you have configured.

Test widget, expanded, with accessibility checked

运行测试后,你将在侧边栏中看到结果,这将在每个已测试的故事旁边添加一个测试状态指示器。你可以点击这些指示器来打开包含辅助功能测试结果的菜单。点击该结果将导航至该故事并打开“辅助功能”面板,你可以在其中查看每个违规行为的详细信息以及修复建议。

¥After running the tests, you will see the results in the sidebar, which will add a test status indicator next to each story that was tested. You can press on these indicators to open a menu with the Accessibility test result. Pressing on that result will navigate to that story and open the Accessibility panel, where you view details about each violation and suggestions toward how to fix them.

Storybook showing a failing accessibility test in both the sidebar story menu and the Accessibility panel

如果你的任何测试出现警告或失败,测试小部件将显示警告和失败的数量。你可以点击这些指示器来过滤侧边栏中的故事,仅显示带有警告或失败的故事。

¥If any of your tests have warnings or failures, the testing widget will show the number of warnings and failures. You can press on these to filter the stories in the sidebar to only show those with warnings or failures.

在 CI 中,当你运行 Vitest 测试时,会自动针对带有 parameters.a11y.test = 'error' 的故事运行可访问性测试。

¥In CI, accessibility tests are run automatically for stories with parameters.a11y.test = 'error' when you run the Vitest tests.

使用 test-runner

¥With the test-runner

如果你使用的是 test-runner,则可以在终端或 CI 环境中运行无障碍测试。

¥If you're using the test-runner, you can run your accessibility tests in the terminal or in CI environments.

当你安装了无障碍插件并将 parameters.a11y.test 设置为 'off' 以外的值时,无障碍测试将包含在你的测试运行中。

¥Accessibility tests are included in your test run when you have the Accessibility addon installed and parameters.a11y.test is set to a value other than 'off'.

调试可访问性违规

¥Debug accessibility violations

运行无障碍测试时,结果将在 Storybook UI 中报告。你可以点击某个违规行为以查看更多详细信息,包括违反的规则以及如何修复的建议。

¥When you run accessibility tests, the results are reported in the Storybook UI. You can click on a violation to see more details about it, including the rule that was violated and suggestions for how to fix it.

你还可以在 Storybook UI 中启用高亮显示,查看哪些元素导致了违规,然后点击高亮显示的元素,在弹出菜单中查看违规详情。

¥You can also toggle on highlighting in the Storybook UI to see which elements are causing the violation, and click on a highlighted element to see the violations details in a popover menu.

Storybook UI with a highlighted element with a popover menu showing accessbility violation details

使用 CI 自动化

¥Automate with CI

使用 Vitest 插件运行可访问性测试时,自动化测试就像在 CI 环境中运行测试一样简单。有关更多信息,请参阅 CI 指南中的测试

¥When you run your accessibility tests with the Vitest addon, automating them is as simple as running them in your CI environment. For more information, please see the testing in CI guide.

如果你将 parameters.a11y.test 设置为 'error',则可访问性测试只会在 CI 中产生错误。如果你将其设置为 'todo',则 CI 中不会出现与可访问性相关的错误、警告或输出,但在本地运行测试时,你仍然可以在 Storybook UI 中看到警告结果。

¥Accessibility tests will only produce errors in CI if you have set parameters.a11y.test to 'error'. If you set it to 'todo', there will be no accessibility-related errors, warnings, or output in CI, but you can still see the results as warnings in the Storybook UI when you run the tests locally.

如果你无法使用 Vitest 插件,你仍然可以使用 test-runner 在 CI 中运行你的测试。

¥If you cannot use the Vitest addon, you can still run your tests in CI using the test-runner.

推荐工作流程

¥Recommended workflow

你可以通过配置通过组合多种测试行为来逐步实现更易于访问的 UI。例如,你可以先从 'error' 开始,以解决可访问性违规问题,然后切换到 'todo' 标记需要修复的组件,最后在所有故事通过可访问性测试后删除待办事项:

¥You can use configuration to progressively work toward a more accessible UI by combining multiple test behaviors. For example, you can start with 'error' to fail on accessibility violations, then switch to 'todo' to mark components that need fixing, and finally remove the todos once all stories pass accessibility tests:

  1. 通过将 parameters.a11y.test 设置为 'error',更新你的项目配置,使其在出现可访问性违规时失败。这可确保所有新故事都经过测试,符合无障碍标准。

    ¥Update your project configuration to fail on accessibility violations by setting parameters.a11y.test to 'error'. This ensures that all new stories are tested to meet accessibility standards.

    .storybook/preview.ts
    // Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
    import type { Preview } from '@storybook/your-framework';
     
    const preview: Preview = {
      // ...
      parameters: {
        // 👇 Fail all accessibility tests when violations are found
        a11y: { test: 'error' },
      },
    };
    export default preview;
  2. 你可能会发现许多组件存在无障碍功能故障(并且可能会感到有点不知所措!)。

    ¥You will likely find that many components have accessibility failures (and maybe feel a bit overwhelmed!).

  3. 记录存在可访问性问题的组件,并通过应用 'todo' 参数值将其故障暂时降低为警告。这可以使可访问性问题保持可见,同时不会阻碍开发。现在也是提交工作作为未来改进基准的好时机。

    ¥Take note of the components with accessibility issues and temporarily reduce their failures to warnings by applying the 'todo' parameter value. This keeps accessibility issues visible while not blocking development. This is also a good time to commit your work as a baseline for future improvements.

    DataTable.stories.ts
    // Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
    import { Meta } from '@storybook/your-framework';
     
    import { DataTable } from './DataTable';
     
    const meta = {
      component: DataTable,
      parameters: {
        // 👇 This component's accessibility tests will not fail
        //    Instead, they display warnings in the Storybook UI
        a11y: { test: 'todo' },
      },
    } satisfies Meta<typeof DataTable>;
    export default meta;
  4. 从刚刚标记为 'todo' 的组件中选择一个合适的起点(我们推荐使用 Button 之类的组件,因为它简单易用,并且很可能在其他组件中使用)。使用插件面板中的建议修复该组件中的问题,确保其通过可访问性测试,然后移除该参数。

    ¥Pick a good starting point from the components you just marked 'todo' (we recommend something like Button, for its simplicity and likelihood of being used within other components). Fix the issues in that component using the suggestions in the addon panel to ensure it passes accessibility tests, then remove the parameter.

    Button.stories.ts
    // Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
    import { Meta } from '@storybook/your-framework';
     
    import { Button } from './Button';
     
    const meta = {
      component: Button,
      parameters: {
        // 👇 Remove this once all stories pass accessibility tests
        // a11y: { test: 'todo' },
      },
    } satisfies Meta<typeof Button>;
    export default meta;
  5. 选择另一个组件并重复此过程,直到你覆盖所有组件,你就是无障碍访问的达人!

    ¥Pick another component and repeat the process until you've covered all your components and you're an accessibility hero!

常见问题

¥FAQ

基于浏览器和基于 linter 的可访问性测试有什么区别?

¥What’s the difference between browser-based and linter-based accessibility tests?

基于浏览器的可访问性测试(如 Storybook 中的测试)会评估渲染的 DOM,因为这可为你提供最高的准确性。审核尚未编译的代码与真实代码相差一步,因此你无法捕捉到用户可能遇到的所有内容。

¥Browser-based accessibility tests, like those found in Storybook, evaluate the rendered DOM because that gives you the highest accuracy. Auditing code that hasn't been compiled yet is one step removed from the real thing, so you won't catch everything the user might experience.

为什么我的测试在不同环境下会失败?

¥Why are my tests failing in different environments?

使用 Vitest 插件,你的测试将使用项目配置和 Playwright 的 Chromium 浏览器在 Vitest 中运行。这可能导致 Storybook UI 或 CLI 中报告的测试结果不一致。不一致可能是由于 axe-core 在不同环境(例如浏览器版本或配置)下报告的结果不同。如果你遇到此问题,我们建议你使用默认沟通渠道(例如 GitHub 讨论Github 问题)与我们联系。

¥With the Vitest addon, your tests run in Vitest using your project's configuration with Playwright's Chromium browser. This can lead to inconsistent test results reported in the Storybook UI or CLI. The inconsistency can be due to axe-core reporting different results in different environments, such as browser versions or configurations. If you encounter this issue, we recommend reaching out using the default communication channels (e.g., GitHub discussions, Github issues).

插件面板未显示预期违规

¥The addon panel does not show expected violations

现代 React 组件通常使用 SuspenseReact 服务器组件 (RSC) 等异步技术来处理复杂的数据获取和渲染。这些组件不会立即渲染其最终的 UI 状态。Storybook 本身并不知道异步组件何时完全渲染。因此,a11y 检查有时会在组件完成渲染之前运行过早,从而导致误报(即使存在违规,也不会报告)。

¥Modern React components often use asynchronous techniques like Suspense or React Server Components (RSC) to handle complex data fetching and rendering. These components don’t immediately render their final UI state. Storybook doesn’t inherently know when an async component has fully rendered. As a result, the a11y checks sometimes run too early, before the component finishes rendering, leading to false negatives (no reported violations even if they exist).

为了解决这个问题,我们引入了一个功能标记:developmentModeForBuild。此功能标志允许你在内置 Storybook 中将 process.env.NODE_ENV 设置为 'development',从而启用通常在生产版本中禁用的开发相关优化。React 的 act 实用程序 是这些开发优化之一,它有助于确保在进行断言(例如 a11y 检查)之前处理并应用与测试相关的所有更新。

¥To address this issue, we have introduced a feature flag: developmentModeForBuild. This feature flag allows you to set process.env.NODE_ENV to 'development' in built Storybooks, enabling development-related optimizations that are typically disabled in production builds. One of those development optimizations is React’s act utility, which helps ensure that all updates related to a test are processed and applied before making assertions, like a11y checks.

要启用此功能,请在你的 .storybook/main.js|ts 文件中添加以下配置:

¥To enable this feature flag, add the following configuration to your .storybook/main.js|ts file:

.storybook/main.ts
// Replace your-framework with the framework you are using, e.g. react-vite, nextjs, vue3-vite, etc.
import type { StorybookConfig } from '@storybook/your-framework';
 
const config: StorybookConfig = {
  framework: '@storybook/your-framework',
  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
  features: {
    developmentModeForBuild: true,
  },
};
 
export default config;

更多测试资源

¥More testing resources