我正在尝试使用Jest + Enzyme测试组件,确保将组件呈现为我的消费者的子代。当我这样做时,类似的测试会起作用:
<FormContextConsumer>
{({ ...props }) => (
<Footer
...
/>
)}
</FormContextConsumer>
像这样模拟上下文:
jest.mock("../../context/FormContext", () => ({
FormContextConsumer: props => props.children()
}));
并进行如下测试:
it(`should render a 'Footer' component inside the 'FormContextConsumer'`, () => {
expect(
shallowTestComponent()
.find(FormContextConsumer)
.dive()
.find(Footer).length
).toBe(1);
});
但是当我解构上下文道具时,是这样的:
<FormContextConsumer>
{({ handleSubmit, handleReset }) => (
<Drawer
...
>
{children}
</BaseEntityDrawer>
)}
</FormContextConsumer>
并对此进行测试:
it(`should always render 'Drawer' inside 'FormContextConsumer'`, () => {
expect(
shallowTestComponent()
.find(FormContextConsumer)
.dive()
.find(Drawer).length
).toBe(1);
});
我收到此错误:
TypeError: Cannot destructure property `handleSubmit` of 'undefined' or 'null'.
我假设它与我如何模拟模块有关,但是我不清楚如何使它适应这种情况。我该如何处理?
答案 0 :(得分:0)
感谢斯蒂芬威尔在这里的回答:https://stackoverflow.com/a/51152120/5858391
我将模拟的上下文更改为:
jest.mock("../../../forms/context/FormContext", () => {
const handleSubmit = jest.fn();
const handleReset = jest.fn();
return {
FormContextConsumer: props => props.children({ handleSubmit, handleReset })
};
});
我的测试正在工作!