简体   繁体   中英

How do you test a redux connected react component by exporting it as a PureComponent?

I've been looking for a solution that I know works but syntax is tripping me up. Here's the scenario:

You have a redux connected component that is exported like so:

export default connect(mapStateToProps, mapDispatchToProps)(componentToExport);

You need to test that component and not see this error in Enzyme:

Could not find "store" in either the context or props of "Connect(componentToExport)"

The solution looks something like the following.

At the bottom of the component being tested you have:

export default connect(mapStateToProps, mapDispatchToProps)(componentToExport);
export default componentToExport as PureComponentToExport

I've tried using:

import from React, { PureComponent } 

and then creating the component with

extends PureComponent 

but that's not working as expected. Enzyme should really have this covered in the docs :/

Any help is greatly appreciated. I don't want to include an external library, or pass the store into the component being tested etc. I'd like to be able to use this syntax that I've seen work before.

thanks :)

The way to do it is to also export the unconnected component, eg by adding export to its definition or by using an explicit export:

export default connect(mapStateToProps, mapDispatchToProps)(YourComponent);
export YourComponent;

And then import it in your test with a named import like so

import { YourComponent } from '../YourComponent';

There's some more information about testing connected components in the redux docs .

import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import ChildComponent from './ChildComponent';


export class YourComponent extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <ChildComponent/>
    );
  }
}

function mapStateToProps(state, ownProps) {
  return {
    state,
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    {
    yourActionsGoHere,
    },
    dispatch
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(YourComponent);

In your Enzyme test you'll want:

import { YourComponent } from '../YourComponent';

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