3
votes

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.

1

1 Answers

0
votes

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