16

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?

Munsterberg
  • 758
  • 4
  • 17
  • 37

1 Answers1

11

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
});
user456584
  • 86,427
  • 15
  • 75
  • 107
Alexandr Lazarev
  • 12,554
  • 4
  • 38
  • 47
  • You should be aware, that if you add a spy to the prototype it will change the behaviour for every following test as well. – Jonathan Apr 07 '17 at 17:53
  • 2
    Strictly speaking you should not be testing private methods. You should be spying on the ```handleClone``` prop to test expected behaviour. – Robin Elvin Sep 26 '17 at 09:02
  • I get the following error when I try this "expect(jest.fn())[.not].toHaveBeenCalled() jest.fn() value must be a mock function or spy. Received: function: [Function proxy]" – prasadmsvs Jan 30 '18 at 06:28
  • @Jonathan You can create a sandbox with `sinon.createSandbox` and call `sandbox.restore()` after each test. – Ahmet Can Güven Sep 15 '18 at 13:46