测试复选框的初始选中状态
Test initial checked state of checkbox
我有一个(简化的)组件:
function Checkbox(initialState) {
const myRef = useRef();
useEffect(() => {
myRef.current.checked = initialState;
}, [initialState]);
return (
<input ref={myRef} />
);
}
我想在 React 测试库中测试复选框的初始选中状态等于 initialState
的值
it('has a checked state', () => {
render(<Checkbox initialState={true} />);
const checkbox = screen.getByRole('checkbox');
expect(checkbox.getAttribute('checked')).toBe(true);
});
测试失败,因为 checkbox
有一个 checked
属性为空,不正确。
您需要检查 checked
属性(js 属性) 而不是属性(初始 HTML 标记中的声明...如果它是静态的 HTML)
it('has a checked state', () => {
render(<Checkbox initialState={true} />);
const checkbox = screen.getByRole('checkbox');
expect(checkbox.checked).toBe(true);
});
PS 我还建议您使用 defaultChecked
prop 而不是通过 .current.checked = true
使用命令集
我有一个(简化的)组件:
function Checkbox(initialState) {
const myRef = useRef();
useEffect(() => {
myRef.current.checked = initialState;
}, [initialState]);
return (
<input ref={myRef} />
);
}
我想在 React 测试库中测试复选框的初始选中状态等于 initialState
it('has a checked state', () => {
render(<Checkbox initialState={true} />);
const checkbox = screen.getByRole('checkbox');
expect(checkbox.getAttribute('checked')).toBe(true);
});
测试失败,因为 checkbox
有一个 checked
属性为空,不正确。
您需要检查 checked
属性(js 属性) 而不是属性(初始 HTML 标记中的声明...如果它是静态的 HTML)
it('has a checked state', () => {
render(<Checkbox initialState={true} />);
const checkbox = screen.getByRole('checkbox');
expect(checkbox.checked).toBe(true);
});
PS 我还建议您使用 defaultChecked
prop 而不是通过 .current.checked = true