27
votes

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?

3
Maybe expect(wrapper).toContain('ChildComponent')? - A Jar of Clay

3 Answers

10
votes

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();
});
3
votes

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'); 
1
votes

I used React Test Renderer for that purpose:

import TestRenderer from 'react-test-renderer';

import ItemList from 'components/ItemList';
import LoadingIndicator from 'components/LoadingIndicator';

test('renders loading indication', () => {
    const testRenderer = TestRenderer.create(
        <ItemList items={[]} isLoading={true}/>
    );
    const testInstance = testRenderer.root;
    testInstance.findByType(LoadingIndicator);
});

I don't think that it's "testing implementation details", quite the opposite - LoadingIndicator component can be modified without need to fix the test case.