22

In enzyme you can check for the existence of child component like this:

expect(wrapper.find(ChildComponent)).toHaveLength(1)

What is the equivalent to this test in react testing library? All the online examples I find just cover very simple tests looking for dom elements - none include examples of that render child components. How do you find a child component?

Flip
  • 4,701
  • 5
  • 32
  • 63
riscos3
  • 1,037
  • 2
  • 6
  • 13

2 Answers2

6

You shouldn't check if your child component is rendered or not, because it's testing implementation details (which testing library doesn't encourage you to do).

You can check some text from your child component is rendered or you can give data-testid to your wrapper element in child and then use .toBeInTheDocument from @testing-library/jest-dom

expect(getByText(/some text/i)).toBeInTheDocument();

or

expect(getByTestId('your-test-id')).toBeInTheDocument();

Updated: Example

// Child Component
function ChildComponent() {
    return <div>Child Element</div>;
};

// Parent
export default function Parent() {
    return (
        <div className="App">
            <ChildComponent />
        </div>
    );
}

Test:

import { render } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import Parent from "./App";

test("test child component", () => {
  const { getByText } = render(<Parent />);
  expect(getByText(/child element/i)).toBeInTheDocument();
});
Amit Chauhan
  • 3,990
  • 1
  • 15
  • 30
2

since query* return null if element is not found you may just

expect(queryByTestId('test-id-you-provided')).toEqual(null);
expect(queryByTestId('some-other-test-id-you-provided')).not.toEqual(null);

Also getBy* throws if element is not find. So next one should work as well

getByTestId('test-id-you-provided'); 
skyboyer
  • 15,149
  • 4
  • 41
  • 56