【问题标题】:How to spy on refs in React?如何在 React 中监视 refs?
【发布时间】:2018-01-04 21:04:52
【问题描述】:

我有一个组件具有来自react-native-mapsMapView。我想测试我在组件的componentDidUpdate 内调用MapView.fitToSuppliedMarkers()

我正在使用enzymejest 进行测试。

我的测试代码:

componentDidUpdate() {
    //some other code
    this.refs.map.fitToSuppliedMarkers(/* some parameters */);
}

但我很纠结如何使用enzymejest 访问和监视this.refs

【问题讨论】:

    标签: reactjs react-native jestjs enzyme


    【解决方案1】:

    问题是我依赖于不推荐使用的不允许测试的字符串引用。有一次,我升级到callback refs,我可以使用原型对象来监视 refs。

    待测代码

    componentDidUpdate() {
        //some other code
        this.map.fitToSuppliedMarkers(/* some parameters */);
    }
    
    render() {
      return (
        <MapView
          ref={(map) => { this.map = map; }}
        >
        </MapView>
      );
    }
    

    单元测试

    it('zooms in on markers when receiving new data', () => {
      Map.prototype.map = {
        fitToSuppliedMarkers: function () { }
      };
    
      const spy = spyOn(Map.prototype.map, 'fitToSuppliedMarkers');
    
      const testee = shallow(
        <Map markers={[]} />
      );
    
      const withAnimation = true;
    
      testee.setProps({ markers: markers });
    
      expect(spy).toHaveBeenCalledWith(markers, withAnimation);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      • 2020-08-10
      • 2017-11-04
      • 1970-01-01
      • 2021-12-02
      相关资源
      最近更新 更多