Jest mocked spy function, not being called in test
Found great help from the answer here: Jest spyOn function called
This was the important step I was missing:
const instance = wrapper.instance()const spy = jest.spyOn(instance, 'yearOnChange')
Updated working test with 2 working expects
.
it('yearOnChange method is called', function() { const instance = wrapper.instance(); // <-- Needed to do this here const spy = jest.spyOn(instance, 'yearOnChange'); // <-- Then use instance here wrapper.instance().forceUpdate(); const event = { target: { value: '1999' } }; wrapper.instance().yearOnChange(event); wrapper.simulate('change', event); const result = wrapper.state('year'); console.log('result', result); // result = 1999 expect(result).toEqual('1999'); expect(spy).toHaveBeenCalled();});
You are spying and calling yearOnChange manually.
Try not calling wrapper.instance().yearOnChange(event);
Call the wrapper.instance().onChange
event, or like you did, run the simulate('change') will be enough.
You could also try VehiclePicker.prototype.yearOnChange = jest.fn()
expect(VehiclePicker.prototype.yearOnChange).toBeCalled();