1

I have a component which is connected to store. And I have to test a function inside the react component. How can I reach to that function?

Eg:

var newReactComponent = React.createClass({
    functionToBeTested: function(){
        this.props.actions.fetchAll();
    }
});
var mapStateToProps = function (state) {
        return {
            cars: state.carReducer.cars
        }
    };

    var mapDispatchToProps = function (dispatch) {
        return {
            actions: bindActionCreators(_.assign({}, carActions, apiActions), dispatch)
        }
    };

    module.exports = connect(mapStateToProps, mapDispatchToProps)(newReactComponent);
`
Anton Sarov
  • 3,712
  • 3
  • 31
  • 48

1 Answers1

0

You can mock connect function to return you the required object(s) so that you can access them in the test environment.

This way, you will be able to access newReactComponent and then you can mount the react component(using shallow from enzyme).

After mounting you will be able to access the class methods.

Something like this:

const actions = {fetchAll: jest.fn()}
const wrapper = shallow(<newReactComponent actions={actions} />);
wrapper.instance().functionToBeTested();
expect(actions.fetchAll).toBeCalled();

I have answered a similar question here

Rahul Gaba
  • 460
  • 4
  • 6