Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...