Sky*_*Sky 2 testing checkbox material-ui react-testing-library
我想测试一个没有标签的复选框。关键是还有其他复选框,所以我不能使用 getByRole。
我尝试过使用 data-testid,但显然它不起作用。
我应该如何检查该复选框是否已选中(toBeChecked())?
<Checkbox
data-testid={item?.id}
key={item?.id}
id={item?.id.toString()}
color="secondary"
checked={item?.checked}
disabled={hasAll}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
if (item) {
item.checked = e.target.checked;
setFinalData(updateItemInArray(finalData, {
item,
index,
}));
}
}}
/>
Run Code Online (Sandbox Code Playgroud)
执行此操作的正确方法是aria-label
向您的复选框添加一个,以便屏幕阅读器正确朗读:
<Checkbox inputProps={{ 'aria-label': 'Select row 1' }} />
Run Code Online (Sandbox Code Playgroud)
这样,您就可以在测试中使用 来选择它getByLabelText
。
如果您想使用data-testid
,可以将其放在复选框上,类似于aria-label
:
<Checkbox inputProps={{ 'data-testid': 'checkbox1' }} />
Run Code Online (Sandbox Code Playgroud)
请注意,如果您使用 Typescript,则必须将 inputProps 转换为,React.InputHTMLAttributes<HTMLInputElement>
因为数据属性不是 InputHTMLAttributes 的一部分:
<Checkbox inputProps={{ 'data-testid': 'checkbox1' } as React.InputHTMLAttributes<HTMLInputElement>} />
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3024 次 |
最近记录: |