材料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');
});由物料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>发布于 2018-11-13 07:51:02
由于复选框正在呈现一个input,所以我将使用它,而不是聚焦于图像。
你可以这样做:
const checkbox = getByTestId('checkbox-1234').querySelector('input[type="checkbox"]')
expect(checkbox).toHaveProperty('checked', true)发布于 2020-07-16 20:33:48
找到复选框的最简单方法是向复选框中添加一个标签。
<FormControlLabel
htmlFor="first-checkBox"
label="First Checkbox"
control={ <Checkbox
checked={checked}
onChange={handleChange}
inputProps={{ 'aria-label': 'primary checkbox' }}
/>
}
/>稍后在测试用例中
const checkboxEl = screen.getByLabelText('First Checkbox') as HTMLInputElement
expect(checkboxEl).toBeChecked()如果测试失败是因为不承认toBeChecked是可用断言的一部分,那是因为您需要导入
导入“@jest库/jest-dom/extend-expect”
发布于 2018-11-13 17:18:59
弄明白了。需要在DOM上使用checked getter,而不是尝试检查checked属性。找到了解释它的问题:https://github.com/facebook/react/issues/7051#issuecomment-334018747
这个代码演示了所检查的属性在React中是如何不改变的:https://codepen.io/gaearon/pen/wgedvV?editors=0010
像这样:expect(checkbox.checked).toBe(true)
https://stackoverflow.com/questions/53271663
复制相似问题