3

I use mapbox-gl, specifically mapbox-gl-leaflet, in React to create a map:

import Leaflet from 'leaflet'
import 'mapbox-gl/dist/mapbox-gl.css'
import {} from 'mapbox-gl-leaflet'
import 'leaflet/dist/leaflet.css'

const Map = () => {
    const map = useRef(null)

    useEffect(() => {

        Leaflet.mapboxGL({
            accessToken: token,
            style: 'mapbox://styles/mapbox/outdoors-v11',
        }).addTo(map.current)
    })
}

In the test it already fails when I try to mount <Map /> with this error:

Failed to initialize WebGL.

There are also two other Error messages:

Error: Not implemented: HTMLCanvasElement.prototype.getContext (without installing the canvas npm package) ...

This page appears to be missing CSS declarations for Mapbox GL JS, which may cause the map to display incorrectly. Please ensure your page includes mapbox-gl.css, as described in https://www.mapbox.com/mapbox-gl-js/api/.

But as you can see I import the CSS file. I think the problem is that in Jest there is no WebGL available. I also installed the canvas npm package, but it didn't seem to help. Is it possible to somehow mock WebGL? I already tried it with jest-canvas-mock. I importet it in the test file: import {} from 'jest-canvas-mock'. But I still get the Error: Not implemented: HTMLCanvasElement.prototype.getContext ... error.

Juuro
  • 1,487
  • 5
  • 16
  • 27
  • Use [puppeteer](https://jestjs.io/docs/en/puppeteer)? – gman Aug 11 '20 at 02:10
  • These are mapbox and/or leaflet that need to be mocked. Jest uses fake DOM that can't and won't behave like a real thing and falls apart as soon as you do something complex. Third-party libs that deeply rely on how real browsers work should be mocked. – Estus Flask Aug 11 '20 at 08:07
  • Error: Not implemented: HTMLCanvasElement.prototype.getContext ... This error I solved adding window.HTMLCanvasElement.prototype.getContext = () => {} before mount the component. – Stiven Ramírez Arango Sep 24 '20 at 17:33
  • Currently I have the same error of WebGL. – Stiven Ramírez Arango Sep 24 '20 at 17:34

0 Answers0