Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading