Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fixing react-leaflet testing error: Cannot read property '_layerAdd' of null

I'm having some issues with the basic rendering tests from create-react-app and the Polyline component from react-leaflet. Whenever I try to add the Polyline as a child to my Map, I get the test error message: TypeError: Cannot read property '_layerAdd' of null. The map and polyline both still show in the browser just fine, but this test error is getting a little annoying.

Has anyone faced the same issue? If so, how did you resolve it?

I've seen a few similar questions asked, but no real answer yet for when using react-leaflet. I've tried tying the map rendering to componentDidMount, but without luck.

Here's my render for my map:

render() {
    return (
      <Map
        animate={this.state.animate}
        center={this.state.latlng}
        length={4}
        onClick={this.handleClick}
        zoom={13}
      >
        <TileLayer
          attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.se/hydda/full/{z}/{x}/{y}.png"
        />
        <Marker position={pathPoints[0]} />
        <Marker position={pathPoints[pathPoints.length - 1]} />
        <Polyline color="red" positions={pathPoints} />
      </Map>
    );
  }
}

Thanks!

like image 311
wilcoxmd Avatar asked Jan 26 '19 20:01

wilcoxmd


1 Answers

In fact, it has nothing to do with react-leaflet library. Leaflet Polyline uses SVG renderer (by default) but JSDOM which comes with Jest test runner for Create React App, does not support SVG to a full extent (in particular createSVGRect is not supported). That's basically the reason why the specified error occurs.

How to configure Create React App to pass tests?

It rather needs to be considered as a workaround but the idea is to extend JSDOM SVGSVGElement by introducing createSVGRect as an empty function. This technique will allow to emulate SVG support in JSDOM in order to pass Jest tests for vector overlays such as Polygon

Under src directory create a file named setupTests.js and provide the following code:

var createElementNSOrig = global.document.createElementNS
global.document.createElementNS = function(namespaceURI, qualifiedName) {
  if (namespaceURI==='http://www.w3.org/2000/svg' && qualifiedName==='svg'){
    var element = createElementNSOrig.apply(this,arguments)
    element.createSVGRect = function(){}; 
    return element;
  }
  return createElementNSOrig.apply(this,arguments)
}
like image 80
Vadim Gremyachev Avatar answered Nov 06 '22 05:11

Vadim Gremyachev