首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在测试反应测试库和Jest中分离子组件

在测试反应测试库和Jest中分离子组件
EN

Stack Overflow用户
提问于 2020-05-18 07:08:00
回答 1查看 4.5K关注 0票数 2

我在我的项目中使用了反应测试库和玩笑。

我的问题是:当我测试我的父组件时,我能将我的子组件与测试隔离开来吗?

这是我的组成部分:

代码语言:javascript
运行
复制
export const Parent: FC = ({items}) => {
   return (
      <>
        <ListComponent items={items} />
        <ChildWillBeIsolated /> 
      </>
   )
}

这是我的考验:

代码语言:javascript
运行
复制
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();
});

因此,这里我不打算将我的ChildWillBeIsolated组件与测试隔离开来。我怎么能这么做?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-18 07:14:56

react-testing-library中,没有浅层渲染的选项,所以在技术上不能,但这并不意味着不能隔离子组件并测试它们。您可以做的是模仿子组件;

代码语言:javascript
运行
复制
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();
});

以上代码不应引发任何错误,因为您将子组件的返回值模拟为<div/>

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61864160

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档