Test if function is called react and enzyme

Munsterberg picture Munsterberg · Nov 3, 2016 · Viewed 31.6k times · Source

I am trying to test one of the methods in my react component. It is being called after a button click so I have the simulation in place with enzyme

 it('clone should call handleCloneClick when clicked', () => {
        const cloneButton = wrapper.find('#clone-btn');
        cloneButton.simulate('click');
 });

My component method is here:

_handleCloneClick(event) {
    event.preventDefault();
    event.stopPropagation();

    this.props.handleClone(this.props.user.id);
}

The _handleCloneClick is being called when the user clicks on the button thats in the simulation, how can I go about testing that its been called successfully?

Answer

Alexandr Lazarev picture Alexandr Lazarev · Nov 3, 2016

There are two options, either you should spy on _handleCloneClick of component's prototype, before you render the component:

export default class cloneButton extends Component {
  constructor(...args) {
    super(...args);
    this. _handleCloneClick = this. _handleCloneClick.bind(this);
  }

  _handleCloneClick() {
    event.preventDefault();
    event.stopPropagation();

    this.props.handleClone(this.props.user.id);
  }

  render() {
    return (<button onClick={this. _handleCloneClick}>Clone</button>);
  }
}

And in your test:

it('clone should call handleCloneClick when clicked', () => {
  sinon.spy(cloneButton.prototype, '_handleCloneClick');
  const wrapper = mount(<cloneButton/>);
  wrapper.find('#clone-btn').simulate('click');
  expect(spy).toHaveBeenCalled() //adept assertion to the tool you use
});

Or, you can try to set a spy after rendering the component and invoke wrapper.update() afterwards:

it('clone should call handleCloneClick when clicked', () => {      
  const wrapper = mount(<cloneButton/>);
  sinon.spy(wrapper.instance(), "_handleCloneClick");
  wrapper.update();
  wrapper.find('#clone-btn').simulate('click');
  expect(spy).toHaveBeenCalled() //adept assertion to the tool you use
});