[英]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. 现在我想测试
handleNameInput()
用提供的值调用searchDish
。
In order to do this I would like to create a jest mock function that replaces the component method. 为了做到这一点,我想创建一个替换组件方法的jest模拟函数 。
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
:
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? 所以我的问题是,如何用酶正确模拟组分方法?
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. 您还需要在测试组件的包装器上调用.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. 我的其他问题来自于在
.update()
方法后没有调用.update()
。
Needs to be replaced wrapper.update();
需要替换
wrapper.update();
with wrapper.instance().forceUpdate();
with
wrapper.instance().forceUpdate();
@Miha's answer worked with a small change: @ Miha的回答是一个小改动:
it('handleNameInput', () => {
let wrapper = shallow(<MyComponent/>);
const searchDishMock = jest.fn();
wrapper.instance().searchDish = searchDishMock;
wrapper.update();
wrapper.instance().handleNameInput('BoB');
expect(searchDishMock).toBeCalledWith('BoB');
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.