繁体   English   中英

如何在Enzyme / React中测试包含连接到Redux的组件的组件?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM