How to Unit Test React-Redux Connected Components? How to Unit Test React-Redux Connected Components? reactjs reactjs

How to Unit Test React-Redux Connected Components?


A prettier way to do this, is to export both your plain component, and the component wrapped in connect. The named export would be the component, the default is the wrapped component:

export class Sample extends Component {    render() {        let { verification } = this.props;        return (            <h3>This is my awesome component.</h3>        );    }}const select = (state) => {    return {        verification: state.verification    }}export default connect(select)(Sample);

In this way you can import normally in your app, but when it comes to testing you can import your named export using import { Sample } from 'component'.


The problem with the accepted answer is that we are exporting something unnecessarily just to be able to test it. And exporting a class just to test it is not a good idea in my opinion.

Here is a neater solution without the need of exporting anything but the connected component:

If you are using jest, you can mock connect method to return three things:

  1. mapStateToProps
  2. mapDispatchToProps
  3. ReactComponent

Doing so is pretty simple. There are 2 ways: Inline mocks or global mocks.

1. Using inline mock

Add the following snippet before the test's describe function.

jest.mock('react-redux', () => {  return {    connect: (mapStateToProps, mapDispatchToProps) => (ReactComponent) => ({      mapStateToProps,      mapDispatchToProps,      ReactComponent    }),    Provider: ({ children }) => children  }})