简体   繁体   中英

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 . 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 :

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?

The component is being shallow rendered in the latest version of 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.'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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