Search code examples
javascriptreactjsenzyme

Testing the async function passed as a prop from parent to child


I have a parent component where I have a handleClick which is passed as a prop to the child.

parent.js

_handleClick = async (buttonName, id) => {
    if(buttonName === 'yes'){
        ... some logic
    }else{
        ... some logic
    }
}

<Child 
  handleClick={(buttonName, id) => this._handleClick(buttonName, id)}
  />

Right now how can I call the _handleClick and run the test cases? How should I call the method?

I have tried below but it didn't work as expected, since it's an arrow function and it expects two parameters.

test.js

const wrapper = shallow(<parent />)
expect(wrapper.find('Child').length).toEqual(1)
wrapper.find('Child').prop('handleClick')

Solution

  • wrapper.find('Child').prop('handleClick') is the function, so you can just call it like this:

    wrapper.find('Child').prop('handleClick')( /* your args here */ );
    

    Here is a simplified working example:

    import { shallow } from 'enzyme';
    import * as React from 'react';
    
    const Child = () => (<div></div>);
    
    class Parent extends React.Component {
      constructor(...args) {
        super(...args);
        this.state = { val: 'initial' };
      }
      _handleClick = async (buttonName, id) => {
        // ... await something ...
        this.setState({ val: buttonName });
      }
      render() {
        return (<Child handleClick={(buttonName, id) => this._handleClick(buttonName, id)} />);
      }
    }
    
    test('click handler', async () => {
      const wrapper = shallow(<Parent />);
      expect(wrapper.find('Child').length).toEqual(1);  // Success!
      await wrapper.find('Child').prop('handleClick')('the button name');  // <= call the handler
      expect(wrapper.state()).toEqual({ val: 'the button name' });  // Success!
    });