我有一个React组件,它有一个文本input作为主包装器中的一个子元素。当input获得焦点时,它通过其onFocus属性调用一个函数。因此,组件的结构如下所示:
<div className="main-wrapper"> <input type="text" onFocus={this.focusHandler} /> </div>
在这个类的其他地方有一个名为focusHandler的方法,它看起来像这样
focusHandler = () => { //Do whatever it is that focus handlers do. //In this case that involves changing the local state, so there is something like this.setState({ fieldHasFocus: true }); }
我想做的是做一个测试(在Jest中),它将验证当输入获得焦点时,focusHandler()方法是否被调用。但是,我不知道如何在focusHandler()测试中加入模拟,以及如何在输入字段上执行simulate('focus')操作时检查是否调用了模拟。
发布于 2018-03-28 18:59:07
您可以在呈现组件之前侦测。您不需要强制更新组件的实例。在spec/describe代码块之前,在文件的顶部声明间谍函数。
const focusHandlerSpy = jest.spyOn(YourComponent.prototype, 'focusHandler');然后..。
describe('When the input field is focused', () => {
beforeEach(() => {
component.find('input').simulate('focus');
});
it('should invoke the focusHandlerSpy function', () => {
expect(focusHandlerSpy).toHaveBeenCalled();
});
});发布于 2018-03-28 18:46:39
尝试如下所示:
const wrapper = shallow(<YourComponent />);
const focusHandlerSpy = jest.spyOn(wrapper.instance(), 'focusHandler');
wrapper.instance().forceUpdate();现在,您的focusHandlerSpy将在focus上调用。
https://stackoverflow.com/questions/49523798
复制相似问题