本文介绍了如何用jest和酶模拟React组件方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个反应组件(这是为了证明问题而简化):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>) }}现在我要测试 handleNameInput()使用提供的值调用 searchDish 。Now I want to test that handleNameInput() calls searchDish with the provided value.为了做到这一点,我想创建一个 jest模拟函数,它取代了组件方法。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');})但我在控制台中得到的只是 SyntaxError :But all I get in the console is SyntaxError: SyntaxError $ b 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?推荐答案方法可以是以这种方式嘲笑: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');})您还需要在测试组件的包装器上调用.update,以便正确注册模拟函数。You also need to call .update on the wrapper of the tested component in order to register the mock function properly.语法错误来自错误的分配(您需要将方法分配给实例)。我的其他问题来自于在模拟方法后没有调用 .update()。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. 这篇关于如何用jest和酶模拟React组件方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-18 12:01