我在我的项目中使用react-testing-library和jest。
我的问题是:我可以在测试父组件时将子组件与测试隔离吗?
这是我的组件:
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组件。我该怎么做?
在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/>