代码之家  ›  专栏  ›  技术社区  ›  rap-2-h

组件安装前的酶模拟功能

  •  1
  • rap-2-h  · 技术社区  · 6 年前

    我可以这样模拟一种成分的功能(使用笑话、酶和反应):

    let wrapper = shallow(<Component />);
    wrapper.instance().load = jest.fn(function(ref) {
      this.setState({ loading: false, notice: {thing: 'thing'} });
    });
    wrapper.update();
    

    我的 load 函数实际上是由 componentWillMount . 它 似乎 组件将安装 被称为 之前 我超负荷工作。

    那么,在实际构建组件之前,有没有一种方法来模拟一个函数呢?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Nicholas Tower    6 年前

    如果修改组件原型,则该组件的实例将继承修改后的函数:

    Component.prototype.load = jest.fn(function(ref) {
      this.setState({ loading: false, notice: {thing: 'thing'} });
    });
    let wrapper = shallow(<Component />);
    
        2
  •  0
  •   Shubham Gupta    6 年前

    还有一种方法,您可以访问包装器实例中的componentwillmount。一旦将加载函数指定为jest.fn,就可以从包装器实例调用componentwillmount。

    wrapper.instance().load = jest.fn();
    wrapper.instance().componentWillMount();
    expect(wrapper.instance().load).toHaveBeenCalled();
    

    这是工作沙盒的链接 https://codesandbox.io/s/6ym0r4z96w