javascriptreactjstestingreact-testing-library

React test if component contains another component


I have loading page:

const Loading: React.FunctionComponent = () => {
    return (
        <div className="w-screen h-screen overflow-hidden">
            <LoadingBackground />
        </div>
    );
};

How can I test if LoadingBackground is rendered or not?

import { render } from "@testing-library/react";
import Loading from "./Loading";
import LoadingBackground from "../../components/LoadingBackground";

test("Loading", () => {
        const parent = render(<Loading />);
        expect(parent).toContainElement(loadingBackground); <-- Check if LoadingBackground is rendered or not?
});

Solution

  • You need to add something to LoadingBackground that can be used to identify it. If you don't have any unique text or so, you can add data-testid={'loadingBackground'} as an attribute to your element and do something like this:

    import {within} from '@testing-library/dom'
    within(parent).getByTestId('loadingBackground')