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?”

Leave a Comment