首页 文章

如何使用Jest和Enzyme模拟组件方法

提问于
浏览
0

我有一个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中),该测试将验证当输入增益聚焦时_1142082_方法被调用 . 但是,我无法弄清楚如何将模拟放入我的 focusHandler() 测试中,并检查输入字段上是否调用它 simulate('focus') .

2 回答

  • 1

    在渲染组件之前,您可以监视它 . 您无需强制更新组件的实例 . 在spec / describe 块之前声明文件顶部的 Spy 功能 .

    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();
      });
    });
    
  • 0

    尝试这样的事情:

    const wrapper = shallow(<YourComponent />);
    const focusHandlerSpy = jest.spyOn(wrapper.instance(), 'focusHandler');
    wrapper.instance().forceUpdate();
    

    现在你的 focusHandlerSpy 将被调用焦点 .

相关问题