I have a (simplified) component:
function Checkbox(initialState) {
const myRef = useRef();
useEffect(() => {
myRef.current.checked = initialState;
}, [initialState]);
return (
<input ref={myRef} />
);
}
I want to test in React Testing Library that the initial checked state of the checkbox equals the value of initialState
it('has a checked state', () => {
render(<Checkbox initialState={true} />);
const checkbox = screen.getByRole('checkbox');
expect(checkbox.getAttribute('checked')).toBe(true);
});
The test fails because checkbox
has a checked
attribute of null, not true.
CodePudding user response:
You need to check checked
property(js property) instead of attribute(declaration in initial HTML markup... If it was static HTML)
it('has a checked state', () => {
render(<Checkbox initialState={true} />);
const checkbox = screen.getByRole('checkbox');
expect(checkbox.checked).toBe(true);
});
PS I'd also suggest you to use defaultChecked
prop instead of using imperative set through .current.checked = true