4

i'm using react-testing-library & jest in my project.

My question is: Can i isolate my child component from test when i test my parent component?

here is my component:

export const Parent: FC = ({items}) => {
   return (
      <>
        <ListComponent items={items} />
        <ChildWillBeIsolated /> 
      </>
   )
}

and it's my test:

import React from "react";
import { Parent as Component } from "./";
import { render } from "@testing-library/react";

const items = [
     {
      title: "A"
      id: 1
     },
     {
      title: "B"
      id: 2
     }
]

it("renders without crashing", async () => {
  const wrapper = render(
      <Component items={items} />
  );
  expect(wrapper).toMatchSnapshot();
  wrapper.unmount();
});

so here i wan't to isolate my ChildWillBeIsolated component from test. how i can do that?

1 Answer 1

14

In react-testing-library there is no option for shallow rendering, so technically you can't. But that does not mean that you cannot isolate child components and test them. What you can do is mocking the child component like;

import React from "react";
import { Parent as Component } from "./";
import { ChildWillBeIsolated } from "../ChildWillBeIsolated";
import { render } from "@testing-library/react";

const items = [
     {
      title: "A"
      id: 1
     },
     {
      title: "B"
      id: 2
     }
]

jest.mock("../ChildWillBeIsolated", () => {
  return {
    __esModule: true,
    default: () => { // if you exporting component as default
      return <div/>;
    },
    ChildWillBeIsolated: () => { // if you exporting component as not default
      return <div/>;
    },
  };
});

it("renders without crashing", async () => {
  const wrapper = render(
      <Component items={items} />
  );
  expect(wrapper).toMatchSnapshot();
  wrapper.unmount();
});

This code above should not throw any error since you mocked the child component's return value as <div/>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.