【发布时间】:2019-03-10 04:03:17
【问题描述】:
在 Enzyme 中测试连接到 Redux 的 React 组件 时有一个熟悉的问题。你可能遇到了这个错误:
Invariant Violation: Could not find "store" in either the context or props of "Connect(YourComponent)
通过两次导出被测组件解决:
export class YourComponent extends Component {}
export default connect(mapStateToProps, mapDispatchToProps)(YourComponent);
在您的测试中将 YourComponent 作为对象导入:
import { YourComponent } from '../pathToYourComponent'
我遇到了一个关于这个问题的新场景。 我正在测试一个连接组件,并且我正在使用上面的解决方案来解决该问题,但是在该组件内部还有另一个连接组件会在某些道具存在时呈现。
import React, { Component } from 'react';
export class YourComponent extends Component {
constructor(props) {
super(props)
}
render() {
const { arrayOfObjects } = this.props;
let nestedConnectedComponent;
if (arrayOfObjects.length) {
nestedConnectedComponent = arrayOfObjects.map((ele, idx) => (
<NestedConnectedComponent
key={idx}
/>
))
}
return (
<div> {arrayOfObjects} </div>
)
}
}
function mapStateToProps(){}
function mapDispatchToProps(){}
export default connect(mapStateToProps, mapDispatchToProps)(YourComponent);
在测试包含连接到 redux 的组件的组件时,如何避免“找不到存储”错误?
组件在最新版本的 Enzyme 中被 shallow 渲染。
【问题讨论】:
标签: javascript reactjs sinon enzyme