You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jest-axe忽略特定元素的axe规则时测试异常问题排查

问题原因与解决方案

问题根源

你当前的配置直接禁用了整个label无障碍规则(rules.label.enabled: false),这会让axe完全跳过所有元素的label缺失检查——不管是ignore-me还是i-should-still-fail的input,都不会被检测到违规,所以测试会直接通过。

正确配置方式

要实现「只忽略指定元素的label规则,其他元素正常检查」的需求,需要保持label规则启用,同时在规则配置中用exclude指定要排除的元素:

it("should have no accessibility violations", async () => {
    const { container } = render(
        <div>
            <input type="text" data-testid="ignore-me" />
            <input type="text" data-testid="i-should-still-fail" />
        </div>
    );

    const results = await axe(container, {
        rules: {
            label: {
                enabled: true, // 保留规则启用状态
                exclude: '[data-testid="ignore-me"]' // 仅排除指定元素的label检查
            },
        },
    });

    expect(results).toHaveNoViolations();
});

补充说明

如果需要忽略某个元素的所有无障碍规则检查,可以使用顶层的exclude配置:

const results = await axe(container, {
  exclude: '[data-testid="ignore-me"]'
});

但这种方式会跳过该元素的所有a11y检测,仅适用于需要完全忽略该元素的场景。

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 15:42:50