我有一个反应组件(为了演示问题而进行了简化):
class MyComponent extends Component {
handleNameInput = (value) => {
this.searchDish(value);
};
searchDish = (value) => {
//Do something
}
render() {
return(<div></div>)
}
}
现在我想测试一下handleNameInput()
calls searchDish
与提供的值。
为了做到这一点,我想创建一个开玩笑模拟功能 https://facebook.github.io/jest/docs/api.html#jestfnimplementation它取代了组件方法。
这是到目前为止我的测试用例:
it('handleNameInput', () => {
let wrapper = shallow(<MyComponent/>);
wrapper.searchDish = jest.fn();
wrapper.instance().handleNameInput('BoB');
expect(wrapper.searchDish).toBeCalledWith('BoB');
})
但我在控制台中得到的只是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)
所以我的问题是,如何使用酶正确模拟组件方法?
该方法可以通过以下方式进行模拟:
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()
在嘲笑该方法之后。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)