简体   繁体   English

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

[英]How to test component that contains a component connected to Redux in Enzyme / React?

There's a familiar gotcha when testing React components that are connected to Redux in Enzyme . 在测试与Enzyme中的 Redux连接的React 组件时 ,有一个熟悉的问题。 You may have run into this error: 您可能遇到过此错误:

Invariant Violation: Could not find "store" in either the context or props of "Connect(YourComponent)

This is resolved by exporting the component under test twice: 通过将测试的组件导出两次来解决问题

export class YourComponent extends Component {}
export default connect(mapStateToProps, mapDispatchToProps)(YourComponent);

And in your test import YourComponent as an object : 在您的测试中将YourComponent导入为对象

import { YourComponent } from '../pathToYourComponent'

I've run into a novel scenario regarding this issue. 关于这个问题,我遇到了一个新的场景。 I'm testing a connected component, and I'm using the solution above to resolve that issue, however inside that component there is another connected component that gets rendered when certain props are present. 我正在测试一个连接组件,我正在使用上面的解决方案来解决这个问题,但是在该组件内部还有另一个连接组件,当存在某些道具时会被渲染。

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);

How do you avoid the "could not find store" error when you are testing a component that contains a component that is connected to redux? 当您测试包含连接到redux的组件的组件时,如何避免“找不到存储”错误?

The component is being shallow rendered in the latest version of Enzyme. 该组件在最新版本的Enzyme中呈浅色

You won't get this error if you use shallow rendering, from docs 如果您使用浅层渲染,则不会出现此错误

'Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that your tests aren't indirectly asserting on behavior of child components.' '浅呈现对于限制自己将组件作为一个单元进行测试很有用,并确保你的测试不会间接地断言子组件的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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