React testing library – how to get all instances of rendered components?

I want to get an access to all components that were rendered in the test. I need it, to read the props of those components.

Consider a ui with checkboxes. Each checkbox can be: checked/unchecked, have some background color and a dynamic size. It doesn’t make sense to add data-testid attribute to the dom nodes just to check if they are rendered correctly. I would end up with a lot of data-testid attributes, like:

data-testid="green-checked-12"
data-testid="green-checked-8"
data-testid="green-unchecked-10"
data-testid="blue-checked-16"
data-testid="yellow-unchecked-8"
...etc

Ideally I would like to get all instances of Checkbox component and check the props:

test("Checkbox", () => {
  it("renders correctly", () => {
    render(<Checkbox />);

    const checkboxComponents = findComponent(Checkbox); // unfortunately there is no such function exposed by testing-library

    expect(checkboxComponents).toEqual([
      { color: "green", checked: true, size: 12 },
      { color: "green", checked: true, size: 8 },
      { color: "green", checked: false, size: 10 },
      { color: "blue", checked: true, size: 16 },
      { color: "yellow", checked: false, size: 8 }
    ]);
  });
});

I’m not sure if that’s possible with react-testing library, or if there is any way to traverse the tree myself and check it.

1 thought on “React testing library – how to get all instances of rendered components?”

  1. I assume that your <Checkbox /> component renders an <input type="checkbox" />. If yes, then :

    getAllByRole('checkbox')
    

    might be what you’re looking for.

    Then, instead of checking what props are passed to your component (which is actually useless because you want to test your UI, not whether React works correctly or not) you can use toBeChecked from testing-library/jest-dom to verify whether a specific checkbox is checked or not :

    import { screen } from '@testing-library/react';
    
    ...
    
    const checkboxes = screen.getAllByRole('checkbox');
    expect(checkboxes[0]).toBeChecked();
    

    NB : you will have to add testing-library/jest-dom to your node modules if it not already the case.

    Reply

Leave a Comment