似乎 Material UI 的工作方式是在单击复选框时呈现不同的 SVG,并且不会更改实际输入元素上的属性或任何内容。那么我如何实际测试该元素是否符合react-testing-library
哲学?
这是一个粗略的例子
复选框组件使用
export const CheckBoxContainer = () => (
<Checkbox inputProps={{ 'data-testid': `clickable-checkbox-1234` }} data-testid={`checkbox-1234`} />
);
测试
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');
});
由 Material UI 生成的 HTML
<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>