![](/img/trans.png)
[英]How to test component that contains a component connected to Redux in Enzyme / React?
[英]How to test a component with a nested container with React and Redux?
由于我正在处理的应用程序的复杂性,我决定使用嵌套的redux容器,而不是将一个动作作为prop传递给子组件。 然而,当使用jsdom结合mocha
, chai
和sinon
渲染OuterContainer
时,这证明对于单元测试是有问题的。
这是一个人为的视图结构示例:
<OuterContainer>
<div>
<InnerContainer />
</div>
</OuterContainer>
其中OuterContainer
和InnerContainer
用连接包裹。 例如:
export connect(<mapStateToProps>)(<Component>)
运行测试时,我得到的错误是: Invariant Violation: Could not find "store" in either the context or props of "Connect(Component)". Either wrap the root component in a `<Provider>`, or explicitly pass "store" as a prop to "Connect(Component)".
Invariant Violation: Could not find "store" in either the context or props of "Connect(Component)". Either wrap the root component in a `<Provider>`, or explicitly pass "store" as a prop to "Connect(Component)".
有没有办法解开或存根InnerContainer
进行单元测试而不必使用浅层渲染?
测试时将组件包装在<Provider>
。 是否提供真实商店或带有{ dispatch, getState, subscribe }
取决于您。 在<Provider store={store}>
包装最外层组件也将使存储可用于任何嵌套级别的子组件 - 就像在应用程序本身中一样。
const store = createStore(reducer) // can also be a mock
ReactTestUtils.renderIntoDocument(
<Provider store={store}>
<OuterContainer />
</Provider>
)
另一种方法是导出要连接的组件和容器。 当然,容器是默认的。
export const Comp = (props) => (<p>Whatever</p>)
export default connect(...)(Comp)
因此,您可以单元测试Comp
。
不确定这是不是你的问题,但我相信这可能会帮助那些看这个饲料的人。
我有同样的错误,这是一个简单的修复:
我忘了在我的条目文件中传递我的组件我的商店对象(使用webpack)。
我刚刚在Root组件“store = {store}”中添加了一个属性,如下所示:
document.addEventListener("DOMContentLoaded", () => {
const store = configureStore();
ReactDOM.render(<Root store={store} />,
document.getElementById('content'));
});
这是我的根文件代码以供参考:
import React from 'react';
import { Provider } from 'react-redux';
import App from './app';
const Root = ({ store }) => (
<Provider store={ store }>
<App />
</Provider>
);
export default root;
希望有人帮助!
模拟Provider
组件以返回子组件。
在describe()
之前添加它。
jest.mock('Provider', () => ({children}) => children);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.