How do I mock leaflet for jest tests?

Viewed 2624

I use a custom icon in L.Icon in a CRA project. It keeps saying L is undefined when running jest tests. How would I mock leaflet to avoid this error?

1 Answers

I found this answer on a similar issue in leaflet itself

What I can recommend for testing is the following,
 just mock leaflet using this in your test file,
 that is rendering the map component:
jest.mock('leaflet')

And then you place this leaflet mock you can
find in react-leaflet into the jest mocks folder
 (__mocks__/leaflet.js, download the current file from: 
https://github.com/PaulLeCam/react-leaflet/blob/master/__mocks__/leaflet.js)

That should be enough in most cases.

ref: https://github.com/Leaflet/Leaflet/issues/6297#issuecomment-499809735

Related