在 React & 中使用 Enzyme 测试嵌套组件终极版 [英] Nested components testing with Enzyme inside of React & Redux
问题描述
我有一个组件 SampleComponent
安装另一个连接组件"(即 container
).当我尝试通过 mount
ing 测试 SampleComponent
时(因为我需要 componentDidMount
),我收到错误:
I have a component SampleComponent
that mounts another "connected component" (i.e. container
). When I try to test SampleComponent
by mount
ing (since I need the componentDidMount
), I get the error:
Invariant Violation:无法在上下文或Connect(ContainerComponent)"的道具.要么包装根组件在 a 中,或明确地将商店"作为道具传递给连接(容器组件)".
Invariant Violation: Could not find "store" in either the context or props of "Connect(ContainerComponent)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(ContainerComponent)".
最好的测试方法是什么?
What's the best way of testing this?
推荐答案
我本质上所做的是引入我的 redux
存储(和 Provider
)并将其封装在一个实用组件如下:
What I essentially did was bring in my redux
store (and Provider
) and wrapped it in a utility component as follows:
export const CustomProvider = ({ children }) => {
return (
<Provider store={store}>
{children}
</Provider>
);
};
然后,我挂载
SampleComponent
并针对它运行测试:
then, I mount
the SampleComponent
and run tests against it:
it('contains <ChildComponent/> Component', () => {
const wrapper = mount(
<CustomProvider>
<SampleComponent {...defaultProps} />
</CustomProvider>
);
expect(wrapper.find(ChildComponent)).to.have.length(1);
});
这篇关于在 React & 中使用 Enzyme 测试嵌套组件终极版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!