Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock React component methods with jest and enzyme

I have a react component(this is simplified in order to demonstrate the issue):

class MyComponent extends Component {
    handleNameInput = (value) => {
        this.searchDish(value);
    };

    searchDish = (value) => {
      //Do something
    }

    render() {
        return(<div></div>)
    }
}

Now I want to test that handleNameInput() calls searchDish with the provided value.

In order to do this I would like to create a jest mock function that replaces the component method.

Here is my test case so far:

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

But all I get in the console is SyntaxError:

SyntaxError

  at XMLHttpRequest.open (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:458:15)
  at run_xhr (node_modules/browser-request/index.js:215:7)
  at request (node_modules/browser-request/index.js:179:10)
  at DishAdmin._this.searchDish (src/main/react/components/DishAdmin.js:155:68)
  at DishAdmin._this.handleNameInput (src/main/react/components/DishAdmin.js:94:45)
  at Object.<anonymous> (src/main/react/tests/DishAdmin.test.js:122:24)

So my question is, how do I properly mock component methods with enzyme?

like image 556
Miha Šušteršič Avatar asked Jan 24 '17 14:01

Miha Šušteršič


People also ask

How do you mock React a component function?

To mock a React component, the most straightforward approach is to use the jest. mock function. You mock the file that exports the component and replace it with a custom implementation. Since a component is basically a function, the mock should also return a function.

How do you test a component function in Jest?

To check if a component's method is called, we can use the jest. spyOn method to check if it's called. We check if the onclick method is called if we get the p element and call it.


2 Answers

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.

like image 174
Miha Šušteršič Avatar answered Oct 13 '22 03:10

Miha Šušteršič


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

like image 23
Aleh Avatar answered Oct 13 '22 04:10

Aleh