Beginner
Beginner

Reputation: 9095

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')

Upvotes: 1

Views: 214

Answers (2)

Brian Adams
Brian Adams

Reputation: 45800

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!
});

Upvotes: 1

ljolz
ljolz

Reputation: 216

Well, you may need to render the parent component with the mount method as opposed to shallow. This will render the child element, otherwise just a placeholder will be rendered. Then, you you may want to trigger the actual click event by clicking the button or whatever triggers the event in the child component.

Upvotes: 0

Related Questions