How to mock React component methods with jest and enzyme How to mock React component methods with jest and enzyme reactjs reactjs

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.


Needs to be replaced wrapper.update(); with wrapper.instance().forceUpdate();


@Miha's answer worked with a small change:

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