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?
You can use @testing-library/jest-dom library.
To enable it, go to "Profiler" >> click the "Cog wheel" on the right side of the top bar >> "General" tab >> Check the "Highlight updates when components render." checkbox.
find('ChildComponent'); const child1 = element.at(0); const child2 = element.at(1); expect(element. length). toBe(2); expect(child1.name()). toBe('ChildComponent'); expect(child1.
By using enzyme you can check if a parent component rendered its child component. For this use containsMatchingElement (). You can also test the child component to be sure that it is rendered by simply referencing it by its displayName. So for that, you have to set displayName to your child Component.
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
For this, you can use Enzyme for testing your react components. By using enzyme you can check if a parent component rendered its child component. For this use containsMatchingElement (). You can also test the child component to be sure that it is rendered by simply referencing it by its displayName.
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(); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With