代码之家  ›  专栏  ›  技术社区  ›  me-me

如何测试由另一个方法调用的React组件方法

  •  1
  • me-me  · 技术社区  · 6 年前

    我有一个类,当它初始化时,它调用另一个方法,该方法调用另一个方法 .我正在测试是否调用了pan方法。这门课比那门课复杂,但我想测试的是 被叫来。

    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.pan = this.pan.bind(this);
      }
    
      componentDidMount() {
        initExternals();
      }
    
      initExternals() {
        .. bla bla
       this.pan();
      }
    
      pan() {
       console.log('Function was called');
      }
    
    }
    

    这是我的测试课

    test('component should call initMap', () => {
      const spy = jest.spyOn(WhereWeAreMap.prototype, 'pan');
      const component = mount(<WhereWeAreMap />);
      expect(spy).toHaveBeenCalled();
    });
    
    I have also tried.
    test('component should call initMap', () => {
      const component = mount(<WhereWeAreMap />);
      const spy = jest.spyOn(component.instance(), 'pan');
      wrapper.instance().forceUpdate();
      expect(spy).toHaveBeenCalled();
    });
    

    我的测试有什么问题,因为它不能测试组件方法 被调用 期望(间谍).tohavebencalled() . 日志显示它被调用,但我的测试显示不同。

    应调用模拟函数,但未调用它。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Dimitar Christoff    6 年前

    第一种测试方法肯定对我有用,很快就将它添加到我运行ATM的测试中,而且很好:

      it('adds the correct scroll blocking class to document.body', () => {
        const spy = jest.spyOn(BlockUI.prototype, 'foo');
        const instance = mount(<BlockUI />).instance();
        // some suggest you need to do this but works without it.
        // instance.forceUpdate();
    
        const body = instance.document.body;
        expect(body.className).toMatchSnapshot();
        expect(spy).toHaveBeenCalled();
      });
    

    这个 BlockUI.prototype.foo 添加对的引用 document.body 并向实例中添加卸载时需要删除的类。

    上述设置适用于:

    "enzyme": "3.7.0",
    "enzyme-adapter-react-16": "1.7.1",
    "enzyme-to-json": "3.3.4",
    "jest": "23.6.0",
    

    我以前很难用这种酶或旧版本的酶来工作,但现在可以了。

    异步的东西也有可能导致问题的异常-我建议不要使用间谍,而是检查您想要确保被调用的方法的结果,不管它是什么。在酶中不使用浅渲染器时,可以保证调用生命周期方法。

    你在改变 pan 方法在构造函数中的实例上,通过从原型中保存它的本地绑定副本-但它仍应调用原型,间谍应捕获它。我想你在看旧版本的东西。

        2
  •  -1
  •   Dave Keane    6 年前
       class MyComponent extends React.Component {
    
          constructor(props) {
            super(props);
            this.pan = this.pan.bind(this);
    
          }
    
          componentDidMount() {
            this.initExternals();
          }
    
          initExternals() {
           this.pan();
          }
    
          pan() {
           console.log('Function was called');
          }
        }
    

    在componentdidmount方法中应用mycomponent的范围

    initExternals应为this.initExternals

    我对window对象的意图是说其他作用域可以绑定到函数

    例如,如果使用窗口范围ie window.initexternals调用函数,则此关键字将引用window

    那么,那就是窗户了。