Search code examples
reactjssinonsimulate

How to spy on function from specific button click using sinon?


I'm making test for my first react app and I have two problems that I'm stuck on. Problem one when I look for a button to simulate click on I get button with id='callA' and not get button with a different id. My second problem is I'm trying to use sinon to spy on A() that button with id="callA" calls.

my react App

class ReactPage extends React.Component {
  constructor(props) {
      super(props)
      this.B = this.B.bind(this)
      this.C = this.C.bind(this)
  }

  //other functions

  A = () => {
    //stuff that I don't want to run on button click
  }

  render(){
    return(
      <button id="callA" type="submit" onClick={this.A}>Submit</button>
      <button id="callB" type="submit" onClick={(e) => this.B(e.target.value)} value={7}>Call B</button>
      <button id="callC" type="submit" onClick={(e) => this.C(e.target.value)} value={1}>Call C</button>
      <button id="callD" type="submit" onClick={(e) => this.D(e.target.value)} value={2}>Call D</button>
    );
  }
}

this is my attempt to make a test for button that calls A()

import {shallow, mount, configure} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import sinon from 'sinon';
import ReactPage from './App';

configure({ adapter: new Adapter() });

it('submit button call A()', () => {
  const spy = sinon.spy(ReactPage.prototype, "A");
  const rendered = shallow(<ReactPage />);
  rendered.find("#callA").simulate('click');
  expect(spy.calledOnce).toEqual(true);
});

Solution

  • You could use jest to spy on your instance of ReactPage.

    it('submit button call A()', () => {
      const rendered = shallow(<ReactPage />);
      const spyOn = jest.spy(rendered.instance(), "A");
      rendered.find("#callA").simulate('click');
      expect(spyOn).toHaveBeenCalled();
    });