我有一个 React 组件(这是为了演示问题而简化的):
class MyComponent extends Component {
handleNameInput = (value) => {
this.searchDish(value);
};
searchDish = (value) => {
//Do something
}
render() {
return(<div></div>)
}
}
现在我想测试 handleNameInput()
使用提供的值调用 searchDish
。
为了做到这一点,我想创建一个 jest mock function替换组件方法。
到目前为止,这是我的测试用例:
it('handleNameInput', () => {
let wrapper = shallow(<MyComponent/>);
wrapper.searchDish = jest.fn();
wrapper.instance().handleNameInput('BoB');
expect(wrapper.searchDish).toBeCalledWith('BoB');
})
但我在控制台中得到的只是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)
所以我的问题是,如何使用 enzyme 正确模拟组件方法?
最佳答案
这个方法可以这样模拟:
it('handleNameInput', () => {
let wrapper = shallow(<MyComponent/>);
wrapper.instance().searchDish = jest.fn();
wrapper.update();
wrapper.instance().handleNameInput('BoB');
expect(wrapper.instance().searchDish).toBeCalledWith('BoB');
})
您还需要在被测组件的包装器上调用 .update 以正确注册模拟函数。
语法错误来自错误的分配(您需要将方法分配给实例)。我的其他问题来自于在模拟方法后没有调用 .update()
。
关于javascript - 如何用 jest 和 enzyme 模拟 React 组件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41830165/