简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM