Varsha Varsha - 1 year ago 107
React JSX Question

Unit testing using Jest for React/Redux Component

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 {
this.onButtonClick = this.onButtonClick.bind(this);

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.

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download