简体   繁体   中英

How do I test function inside connected component in react?

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);
`

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

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