在测试中隔离子组件 - react-testing-library & Jest
Isolate child component in test - react-testing-library & Jest
我在我的项目中使用了 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();
});
上面的代码不应抛出任何错误,因为您将子组件的 return 值模拟为 <div/>
我在我的项目中使用了 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();
});
上面的代码不应抛出任何错误,因为您将子组件的 return 值模拟为 <div/>