Reactjs React,酶,Redux单元测试React 16和x2B中的连接成分;
我试图升级到react 16+并且我现有的单元测试失败了。应用程序运行正常,只有单元测试失败 连接的组件:Reactjs React,酶,Redux单元测试React 16和x2B中的连接成分;,reactjs,redux,enzyme,Reactjs,Redux,Enzyme,我试图升级到react 16+并且我现有的单元测试失败了。应用程序运行正常,只有单元测试失败 连接的组件: const componentsWrapper = (Components, selectData) => { class BaseComponent extends Component { constructor(props) { super(props); this.state = {
const componentsWrapper = (Components, selectData) => {
class BaseComponent extends Component {
constructor(props) {
super(props);
this.state = {
saveMode: false,
updateMode: false
};
this.foo = () => { };
}
render() {
return (
<Components
{...this.props}
/>
);
}
}
}
const mapDispatchToProps = dispatch => {
return selectData.getDispatch(dispatch);
};
const mapStateToProps = state => {
return selectData.getStore(state);
};
return connect(mapStateToProps, mapDispatchToProps)(BaseComponent);
};
export default componentsWrapper;
const componentsWrapper=(组件,选择数据)=>{
类BaseComponent扩展了组件{
建造师(道具){
超级(道具);
此.state={
保存模式:false,
updateMode:false
};
this.foo=()=>{};
}
render(){
返回(
);
}
}
}
const mapDispatchToProps=调度=>{
返回selectData.getDispatch(dispatch);
};
常量mapStateToProps=状态=>{
返回selectData.getStore(状态);
};
返回连接(mapStateToProps、mapDispatchToProps)(基本组件);
};
导出默认组件Rapper;
单元测试:
class MockListComponent extends Component {
render() {
return (<div>Fake List</div>);
}
}
Components = componentsWrapper(MockListComponent, selectComponents);
wrapper = shallow(<Components store={store} />).dive();
instance = wrapper.instance()
// Here instance is null hence the rest will fail.
instance.foo = jest.fn();
类MockListComponent扩展组件{
render(){
退货(假名单);
}
}
Components=componentsWrapper(MockListComponent,selectComponents);
包装器=浅();
instance=wrapper.instance()
//此处实例为空,因此其余实例将失败。
instance.foo=jest.fn();
实例
为空,因为“连接”组件是功能性的或无状态的
注意:对于React 16及更高版本,instance()为无状态功能组件返回null
我不知道如何使实例不为null,或者重构代码。我感谢任何帮助或暗示
以下是我尝试使用的库版本:
react@16.2.9
enzyme@3.3.0
redux@4.0.5我不确定您试图测试的确切行为是什么,但在许多情况下,除非您计划进行集成测试或功能测试,否则无需明确“测试”整个连接的组件 要解决您面临的问题,我建议您导出子组件(注意
BaseComponent
上的export
):
然后,在您的测试文件中,我们使用enzyme的.find()
来匹配选择器的节点。在本例中,我们的选择器是BaseComponent
const wrapper = shallow(<Components store={store} />)
const wrapperInstance = wrapper.dive().find(BaseComponent).instance();
const wrapper=shallow()
const wrapperInstance=wrapper.dive().find(BaseComponent.instance();
从那里,您将可以访问BaseComponent
的类实例,并可以使用它调用其方法,或监视其方法
您面临问题中所述错误的原因解释如下: 对于React 16及更高版本,instance()为无状态返回null 功能组件
因此,您只能对组件本身而不是整个连接的组件调用
.instance()
。嘿,我的解决方案解决了您的问题吗?@wentjun是的,诀窍是分别导出它们(组件和连接的组件)。这不起作用,原因如下:
const wrapper = shallow(<Components store={store} />)
const wrapperInstance = wrapper.dive().find(BaseComponent).instance();