mardi 28 mars 2017

Testing if an event handler has been called when that event handler is an instance method

Using enzyme to test React components, I would like to set an instance method to a mock function so that I can check when it has been called as a result of an event. For example:

class MyComponent extends Component {
  handleClick = e => {
    // ...
  }

  render() {
    return <button onClick={this.handleClick}>Click Me</button>;
  }
}

And the test:

let wrapper = shallow(<MyComponent />);
let mockFn = jest.fn();
wrapper.instance().handleClick = mockFn;
wrapper.simulate('click');
expect(mockFn).toHaveBeenCalled(); // Fails!

Is there any way to solve this? I realize that I can test for possible state changes resulting from the event, but I'd like to be able to test directly whether the event handler was called.

Aucun commentaire:

Enregistrer un commentaire