Ad

How To Test Parent Passing `this` To Children Using Enzyme

- 1 answer

I have below code where Parent Component is passing it's this to Child Component. Child Component will do some work and then do setState in Parent Component.

How Should i go about testing only Child Component. Means how can i create dummy Parent and later on check value in it's state using enzyme & jest.

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state={
            status: '',
        }
    }
    render(){
        return (
            <div>
                <Child 
                    parentThis={this}
                />
            </div>
        );
    }
}

class Child extends React.Component {

    doSomeWork = () => {
        const {parentThis} = this.props;
        parentThis.setState({
            'status': '1'
        })
    }

    render() {
        this.doSomeWork()
        return (<div></div>);
    }
}

I want to do Unit testing of Child Component. I want to make sure that Child is correctly updating state of Parent Component.

Ad

Answer

Well,

I have below code where Parent Component is passing it's this to Child Component. Child Component will do some work and then do setState in Parent Component.

Don't do that. That is never a good pattern for testing purposes - and neither a good pattern in React.

React allows you to pass functions to components, in your case a callback. So instead of passing this, pass a function onChangeStatus. A full example might look like the following:

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state={
            status: '',
        }
    }
    render(){
        return (
            <div>
                <Child onChangeStatus={(status) => this.setState({status})}
                       status={this.state.status}
                />
            </div>
        );
    }
}

class Child extends React.Component {

    doSomeWork = () => {
        const {onChangeStatus} = this.props;
        onChangeStatus({
            status: '1'
        })
    }

    render() {
        this.doSomeWork()
        return (<div></div>);
    }
}

To test it, just test if a function you pass to the child gets called. I seldom use enzyme, but this article looks promising on how to test the function.

Ad
source: stackoverflow.com
Ad