2

I am testing my connected component using Jest. This is how the component looks:

import React, {Component, PropTypes} from 'react';
import { connect } from 'react-redux';

class MyComponent extends Component {
  constructor(){
    super();
    this.onButtonClick = this.onButtonClick.bind(this);
  }

  onButtonClick(id) {
    dispatch(actions.onButtonClick(id));
  }

  render() {
    return (
      <div onClick={this.onButtonClick} />
    )
  }
}

function mapStateToProps(state) {
  something: state.something
}

MyComponent.propTypes = {
  dispatch: PropTypes.func.isRequired
}

export default connect(mapStateToProps)(MyComponent)

I am not sure how to test 'onButtonClick' since it dispatches an action. How to I expect dispatch to have been called with correct parameters using jest.

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
Varsha
  • 53
  • 6

1 Answers1

2

What you can do is export your component in addition to the default export. So change it to:

export class MyComponent extends Component

In your test, you can now import your actual component instead of the connected component. As you have dispatch as a prop of your component, you can supply a mock function or a spy (using something like jasmine or sinon) for dispatch in your test, and you can test if that gets called with the correct parameters.

Check out more on redux testing here: http://redux.js.org/docs/recipes/WritingTests.html

0xRm
  • 1,259
  • 8
  • 11