用React测试库测试无线电输入-没有发现与该标签相关的表单控件



我正在使用React测试库测试我的表单中的几个无线电输入。大多数都有yes/no的标签,所以我不能使用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();
});

这是错误后输出的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>

我认为有几个问题:

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

最新更新