我在我的项目中使用了反应测试库和玩笑。
我的问题是:当我测试我的父组件时,我能将我的子组件与测试隔离开来吗?
这是我的组成部分:
export const Parent: FC = ({items}) => {
return (
<>
<ListComponent items={items} />
<ChildWillBeIsolated />
</>
)
}
这是我的考验:
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组件与测试隔离开来。我怎么能这么做?
发布于 2020-05-18 07:14:56
在react-testing-library
中,没有浅层渲染的选项,所以在技术上不能,但这并不意味着不能隔离子组件并测试它们。您可以做的是模仿子组件;
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/>
https://stackoverflow.com/questions/61864160
复制相似问题