Test if function is called react and enzyme

我是研究僧i 提交于 2019-12-21 03:52:06

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/40393486/test-if-function-is-called-react-and-enzyme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!