Dal*_*ace 5 material-ui react-testing-library
似乎Material UI的工作方式是单击复选框时呈现了一个不同的SVG,而不更改属性或实际输入元素上的任何内容。那么,我该如何实际测试该元素是否按照react-testing-library哲学进行了检查?
这是一个粗略的例子
// Checkbox component usage
export const CheckBoxContainer = () =>
<Checkbox
inputProps={{ 'data-testid': `clickable-checkbox-1234` }}
data-testid={`checkbox-1234`}
/>
// test
test('check the box', async () => {
const { getByTestId } = render(<CheckBoxContainer />);
await waitForElement(() => getByTestId(`checkbox-1234`));
const checkbox = getByTestId(`checkbox-1234`);
fireEvent.click(getByTestId(`clickable-checkbox-1234`));
expect(checkbox).toHaveAttribute('checked');
});
// Generated HTML by Material UI
<span class="MuiButtonBase-root-54 MuiIconButton-root-48 MuiSwitchBase-root-231 MuiCheckbox-root-225 MuiCheckbox-colorSecondary-230 MuiSwitchBase-checked-232 MuiCheckbox-checked-226" data-testid="checkbox-1234">
<span class="MuiIconButton-label-53">
<svg class="MuiSvgIcon-root-57" focusable="false" viewBox="0 0 24 24" aria-hidden="true" role="presentation">
<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>
<input class="MuiSwitchBase-input-234" type="checkbox" data-indeterminate="false" data-testid="clickable-checkbox-1234" value="">
</span>
<span class="MuiTouchRipple-root-66">
</span>
</span>
Run Code Online (Sandbox Code Playgroud)
由于该复选框正在渲染a,input所以我将使用它而不是专注于图像。
您可以执行以下操作:
const checkbox = getByTestId('checkbox-1234').querySelector('input[type="checkbox"]')
expect(checkbox).toHaveProperty('checked', true)
Run Code Online (Sandbox Code Playgroud)
我发现找到复选框的最简单方法是为其添加标签
<FormControlLabel
htmlFor="first-checkBox"
label="First Checkbox"
control={ <Checkbox
checked={checked}
onChange={handleChange}
inputProps={{ 'aria-label': 'primary checkbox' }}
/>
}
/>
Run Code Online (Sandbox Code Playgroud)
稍后在测试用例中
<FormControlLabel
htmlFor="first-checkBox"
label="First Checkbox"
control={ <Checkbox
checked={checked}
onChange={handleChange}
inputProps={{ 'aria-label': 'primary checkbox' }}
/>
}
/>
Run Code Online (Sandbox Code Playgroud)
如果测试失败是因为无法将 toBeChecked 识别为可用断言的一部分是因为您需要导入
导入'@testing-library/jest-dom/extend-expect'
| 归档时间: |
|
| 查看次数: |
2233 次 |
| 最近记录: |