[英]How to test component that contains a component connected to Redux in Enzyme / React?
在測試與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中呈淺色 。
如果您使用淺層渲染,則不會出現此錯誤
'淺呈現對於限制自己將組件作為一個單元進行測試很有用,並確保你的測試不會間接地斷言子組件的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.