javascripttestingleafletvitesttesting-library

`Cannot use 'in' operator to search for '_leaflet_id' in null` in testing


I am implementing an integration test with Vitest 1.4.0 and testing-library/react 14.2.1 which renders the main app component. Simply by calling the testing-library render() function, I get this error:

TypeError: Cannot use 'in' operator to search for '_leaflet_id' in null
    at Util.stamp (proj/node_modules/leaflet/src/core/Util.js:55:21)
    at NewClass.hasLayer (proj/node_modules/leaflet/src/layer/Layer.js:203:10)
    at NewClass.getRenderer (proj/node_modules/leaflet/src/layer/vector/Renderer.getRenderer.js:20:13)
    at NewClass.beforeAdd (proj/node_modules/leaflet/src/layer/vector/Path.js:80:24)
    at NewClass.addLayer (proj/node_modules/leaflet/src/layer/Layer.js:169:10)
    at addLayer (proj/node_modules/@react-leaflet/core/lib/layer.js:9:19)

Leaflet runs fine when I run the application both in DEV and PROD mode and has a few points where it addsLayers to leaflet, making a reproduction hard to consider at the moment.


Solution

  • I've fixed this error by adding this when initializing the Map:

    const map = L.map('map', {
      {...}
      preferCanvas: !L.Browser.svg && !L.Browser.vml
    });
    

    Leaflet either uses a canvas or SVG renderer. Your test env does not have an SVG renderer. This tells the map to prefer a canvas renderer only when no SVG renderer is present. So this does not change the app when running in a browser.