Accepted answer

the first block fails because wrapper.instance().handlesubmit is not a jest mock function; it is whatever the class method defines it as.

the second block fails because handlesubmit, while it is a jest mock function, is not tied to your wrapper component at all. it is a local variable. when you simulate the click, it is again calling the actual implementation.

in order to accomplish what you are trying to do, you have to do something like this

it('handlessubmit when submit button is clicked', () => {
  const handlesubmit = jest.fn();
  wrappercomponent.prototype.handlesubmit = handlesubmit;
  const wrapper = shallow(<wrappercomponent />);

where wrappercomponent is the component you are testing.

the above ought to work, but you can sometimes accomplish something similar in a nicer way. depending on your component's implementation, it is oftentimes easier to test that the functionality in your handlesubmit method is called rather than the handlesubmit method itself. for instance, if my component was something like

class testcomponent extends react.component {
  constructor(props) {
    this.state = { clicked: false }
    this.onclick = this.onclick.bind(this)

  onclick() {
   this.setstate({ clicked: true })

  render() {
    return (
      <button onclick={ this.onclick }>
        { 'click me' }

i could test it by doing

it('calls onclick props and sets clicked state to true when clicked', () => {
  const onclick = jest.fn();
  const testcomp = shallow(<testcomponent onclick={ onclick } />);

i generally prefer this type of test because i don't have to overwrite prototype, and it is actually testing that the click triggers the logic i expect. the original test really only covers that i am passing this.handlesubmit as an onclick prop to a button component and nothing more.

Related Query

More Query from same tag