1
votes

I've created a custom component in react-leaflet by extending MapControl. The component doesn't return anything but adds something to the map object it refers to via the props.

Custom Child Component

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);

Parent/Map component

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;

While testing the child component Dashboard, how do I initialise map? (and then check if it contains the dashboard) I'm using Jest and Enzyme

1

1 Answers

2
votes

For Jest the following example demonstrates how to:

  • create an instance of react-leaflet Map component
  • ensure a custom control (Dashboard in your case) is instantiated

Example

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();
});