使用 React 测试库测试无线电输入 - 未找到与该标签关联的表单控件

dmi*_*er1 6 reactjs react-testing-library

我正在使用 React 测试库测试表单中的多个无线电输入。他们中的大多数都有是/否的标签,所以我不能使用findByLabelText. 我收到的完整错误是:Found a label with the text of: yes, however no form control was found associated to that label. Make sure you're using the "for" attribute or "aria-labelledby" attribute correctly.

这是我失败的测试之一:

    test('Sealing Properly radio input should exist, be unchecked, and be clickable', async () => {
        render(
            <Component />
        );
        const sealingProperlyRadioGroup = await screen.findByTestId('sealingProperly');
        const sealingProperlyRadio = await within(sealingProperlyRadioGroup).findByLabelText('yes');
        expect(sealingProperlyRadio).toBeInTheDocument();
        expect(sealingProperlyRadio).not.toBeChecked();
        fireEvent.click(sealingProperlyRadio)
        expect(sealingProperlyRadio).toBeChecked();
    });
Run Code Online (Sandbox Code Playgroud)

这是错误后输出的 html:

 <div
      class="radioGroup mb-3"
      data-testid="sealingProperly"
    >
      <label
        class="radio"
        for="sealingProperlyYes"
      >
        <input
          id="sealingProperlyYes"
          name="sealingProperly"
          required=""
          type="radio"
          value="yes"
        />
        Yes
      </label>
      <label
        class="radio ms-5"
        for="sealingProperlyNo"
      >
        <input
          id="sealingProperlyNo"
          name="sealingProperly"
          required=""
          type="radio"
          value="no"
        />
        No
      </label>
    </div>
Run Code Online (Sandbox Code Playgroud)

Avi*_*Avi 3

我认为有几个问题:

  1. 您正在查询的文本是“yes”,而在您的组件中它是大写的。React 测试库中有多种方法可以忽略大小写,但默认情况下它是区分大小写的。您可以在这里了解更多信息
  2. 在 React 中,for属性的编写方式略有不同 -htmlFor="your-id"所以我认为你的标签没有正确地与其输入相关联。来源