如何在 React 中监视引用



我有一个组件,它有一个来自react-native-mapsMapView。我想测试我是否在组件componentDidUpdate内部调用MapView.fitToSuppliedMarkers()

我正在使用enzymejest进行测试。

我测试的代码:

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

但是我很难使用enzymejest访问和监视this.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);
});

最新更新