Enzyme simulate an onChange event Enzyme simulate an onChange event reactjs reactjs

Enzyme simulate an onChange event


You can simply spy to the method directly via the prototype.

it("responds to name change", done => {  const handleChangeSpy = sinon.spy(New.prototype, "handleChange");  const event = {target: {name: "pollName", value: "spam"}};  const wrap = mount(    <New />  );  wrap.ref('pollName').simulate('change', event);  expect(handleChangeSpy.calledOnce).to.equal(true);})

Alternatively, you can use spy on the instance's method, but you have to make a forced update because the component is already rendered after mount is called, which means the onChange is already bound to its original.

it("responds to name change", done => {  const event = {target: {name: "pollName", value: "spam"}};  const wrap = mount(    <New />  );  const handleChangeSpy = sinon.spy(wrap.instance(), "handleChange");  wrap.update(); // Force re-render  wrap.ref('pollName').simulate('change', event);  expect(handleChangeSpy.calledOnce).to.equal(true);})