ciz30
ciz30

Reputation: 453

Isolate child component in test - react-testing-library & Jest

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?

Upvotes: 4

Views: 6541

Answers (1)

onuriltan
onuriltan

Reputation: 3908

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/>

Upvotes: 14

Related Questions