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

当aria-invalid="false"时toBeValid测试失败的原因咨询

问题

我正在编写测试,验证当满足若干条件时按钮的有效状态。以下是代码片段:

it("some conditions are met -> button shows valid", async () => {
    // some conditions are met;
    render(
      <Provider>
        <MyComponent />
      </Provider>
    );
    const button = screen.getAllByRole("button")[0];

    fireEvent.click(button);

    await waitFor(() => expect(button).toBeValid());
});

测试失败,错误信息如下:

expect(element).toBeValid()

    Received element is not currently valid:
      <button aria-disabled="false" aria-expanded="true" aria-haspopup="listbox" aria-invalid="false" aria-labelledby="topics-label topics-toggle-button" aria-required="true" class="css-1rryzs9" id="toggle-button" type="button" />

明明aria-invalid="false",测试为何失败?

可能的原因分析
  • toBeValid() 依赖原生表单验证而非ARIA属性:Testing Library的toBeValid()断言基于元素的原生checkValidity()方法,和aria-invalid属性无关。哪怕aria-invalid="false",只要元素原生表单验证不通过,断言就会失败。
  • 关联的必填项未满足:按钮带有aria-required="true",且aria-haspopup="listbox"说明它关联了一个列表框。点击按钮后,若列表框未选中任何选项,关联的表单控件会未通过原生验证,导致按钮的checkValidity()返回false。
  • 异步状态未同步完成:虽然用了waitFor,但条件满足后的状态更新、表单验证同步可能存在延迟,断言时原生验证状态还没切换为有效。
  • 表单上下文绑定问题:如果按钮未正确关联到表单上下文,或者MyComponent内部的验证逻辑没绑定到按钮状态,toBeValid()无法正确识别有效状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 07:50:29