使用酶装置测试具有连接的子组件的反应组件

时间:2017-08-22 06:58:10

标签: reactjs testing redux react-redux enzyme

我使用酶装载测试反应组分(因为我正在测试它的生命周期方法)。我的问题是我的组件有一个redux连接子组件,它给了我错误:

Invariant Violation: Could not find "store" in either the context or props of "Connect(Popup)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(Popup)

我怎样才能解决这个问题? 谢谢!
URI

2 个答案:

答案 0 :(得分:1)

如错误所述,您需要为您的组件提供商店。

通过道具传递它:

const wrapper = mount(<PopupContainer store={store} />)

或者将其包装在<Provider>

const wrapper = mount(
    <Provider store={store}>
        <PopupContainer />
    </Provider>
)

现在,如果您正在使用Jest并且不希望包装的组件干扰您的测试,您可以模拟它:

jest.mock('./Popup', () => 'Popup');

答案 1 :(得分:0)

不,你不必嘲笑商店。只需提取包装组件:

const WrappedPopup = Popup.WrappedComponent;

使用模拟道具和动作测试它,就像普通组件一样:

const wrapper = mount(<WrappedPopup connectPropA={...} actionB={...} />);

包装组件是一个静态属性,connect添加到包装器组件以访问原始组件。

相关问题