How to mock React component methods with jest and enzyme

The method can be mocked in this way:

it('handleNameInput', () => {
   let wrapper = shallow(<MyComponent/>);
   wrapper.instance().searchDish = jest.fn();
   wrapper.update();
   wrapper.instance().handleNameInput('BoB');
   expect(wrapper.instance().searchDish).toBeCalledWith('BoB');
})

You also need to call .update on the wrapper of the tested component in order to register the mock function properly.

The syntax error was coming from the wrong assingment (you need to assign the method to the instance). My other problems were coming from not calling .update() after mocking the method.

Leave a Comment