I agree with everyone who said, that checking for either text or a test-id inside a child component is testing implementation details.
But we could use mocking, to get rid of the implementation details of the child component.
The code to test:
import { ChildComponent } from 'child-from-somewhere';
export function Parent() {
return (
<div className="App">
<ChildComponent />
</div>
);
}
The test code that checks, if ChildComponent was rendered:
import { render } from "@testing-library/react";
import React from "react";
import { Parent } from "./parent";
jest.mock("child-from-somewhere", () => ({
ChildComponent: () => <div data-testid="ChildComponent">ChildComponent</div>,
}));
describe("ChildComponent component", () => {
it("should be in the document", () => {
const { getByTestId } = render(<Parent />);
expect(getByTestId("ChildComponent")).toBeInTheDocument();
});
});
That way, the test stays independent of changes that are made inside of ChildComponent
.
expect(wrapper).toContain('ChildComponent')
? – Home