Test initial checked state of checkbox

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.

>Solution :

You need to check checkedproperty(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

Leave a Reply