首页 > 解决方案 > 如何使用 Enzyme 在 react-leaflet 自定义子组件中测试地图参考?

问题描述

我通过扩展 MapControl 在 react-leaflet 中创建了一个自定义组件。该组件不返回任何内容,而是map通过 props 向它所引用的对象添加一些内容。

自定义子组件

import { MapControl, withLeaflet } from "react-leaflet";
import * as L from "leaflet";

class Dashboard extends MapControl<any, any> {
  public createLeafletElement(props: any) {}

  public addDashboard() {
    const dashboard = L.control({ position: "topright" });

    dashboard.onAdd = function() {
      this._div = L.DomUtil.create("div", "dashboard");
      this._div.setAttribute("data-test", "component-dashboard");
      return this._div;
    };

    const { map } = this.props.leaflet;
    dashboard.addTo(map);
  }

  componentDidMount() {
    this.addDashboard();
  }

  render() {
    return null;
  }
}


export default withLeaflet(Dashboard);

父/地图组件

import React from "react";
import { Map, TileLayer } from "react-leaflet";
import Dashboard from "./Dashboard";

class MapContainer extends React.Component<any> {
  public constructor(props: any) {
    super(props);
  }

  render() {
    return (
      <div data-test="component-map">
        <Map
          center={this.props.center}
          zoomSnap={this.props.zoomSnap}
          zoom={this.props.zoom}
          style={this.props.style}
        >
          <TileLayer
            url={this.props.url}
            attribution={this.props.attribution}
          />
          <Dashboard />
        </Map>
      </div>
    );
  }
}


export default MapContainer;

在测试子组件 Dashboard 时,如何初始化地图?(然后检查它是否包含仪表板)我正在使用 Jest 和 Enzyme

标签: reactjsleafletjestjsenzymereact-leaflet

解决方案


对于Jest,以下示例演示了如何:

  • 创建react-leaflet Map组件实例
  • 确保实例化自定义控件Dashboard在您的情况下)

例子

import React from "react";
import ReactDOM from "react-dom";
import { renderIntoDocument } from "react-dom/test-utils";
import { Map, TileLayer } from "react-leaflet";
import Dashboard from "./Dashboard";


it("Control test", () => {
  class TestComponent extends React.Component {
    constructor() {
      super();
      this.controlRef = React.createRef();
    }

    getControl() {
      return this.controlRef.current.leafletElement;
    }

    render() {
      return (
        <Map center={[0,0]} zoom={10}>
          <Dashboard ref={this.controlRef} />
        </Map>
      );
    }
  }

  const component = renderIntoDocument(<TestComponent />);
  const control = component.getControl();

  expect(control).not.toBeNull();
});

推荐阅读