在一个 React 组件中,我有一个来自 Material UI 的复选框,其标记如下:
我正在尝试遵循指南,并查询标签(在这种情况下是“其他”),而不是使用ID。因此,我想点击带有标签“其他”(
<label class="MuiFormControlLabel-root">
<span class="MuiButtonBase-root MuiIconButton-root PrivateSwitchBase-root-353 MuiCheckbox-root MuiCheckbox-colorPrimary PrivateSwitchBase-checked-354 Mui-checked MuiIconButton-colorPrimary" aria-disabled="false">
<span class="MuiIconButton-label">
<input class="PrivateSwitchBase-input-356" id="citizen-profile-challenge-checkbox-diabetes" type="checkbox" data-indeterminate="false" value="other" checked="">
<svg class="MuiSvgIcon-root" focusable="false" viewBox="0 0 24 24" aria-hidden="true">
<path d="M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"></path>
</svg>
</span>
<span class="MuiTouchRipple-root"></span>
</span>
<span class="MuiTypography-root MuiFormControlLabel-label MuiTypography-body1">Other</span>
</label>
我正在尝试遵循指南,并查询标签(在这种情况下是“其他”),而不是使用ID。因此,我想点击带有标签“其他”(
<span class="MuiTypography-root MuiFormControlLabel-label MuiTypography-body1">Other</span>
)的复选框,并测试复选框值是否更改(<input class="PrivateSwitchBase-input-356" id="citizen-profile-challenge-checkbox-diabetes" type="checkbox" data-indeterminate="false" value="other" checked="">
)。fireEvent.click(getByLabelText('Other', { selector: 'input' }))
const checked1 = (getByLabelText('Other', { selector: 'input' }) as HTMLInputElement).checked
console.log(checked1) // false
fireEvent.click(getByLabelText('Other', { selector: 'input' }))
const checked2 = (getByLabelText('Other', { selector: 'input' }) as HTMLInputElement).checked
console.log(checked2) // false
fireEvent.click(getByLabelText('Other'))
const checked3 = (getByLabelText('Other') as HTMLInputElement).checked
console.log(checked3) // false
fireEvent.click(getByLabelText('Other'))
const checked4 = (getByLabelText('Other') as HTMLInputElement).checked
console.log(checked4) // false
我尝试了不同的方法,但是checked
仍然是false
。似乎我需要获取标签的兄弟节点并搜索该节点中的<input>
元素。但我该如何做呢?