3

Let's say I have a mapbox map. The mapbox map has an onclick handler, and within the onclick handler's callback, a function is called:

import { Map } from 'mapbox-gl'

const map = new Map({
  container: someContainer,
  center, 
  zoom
})

map.on('click', e => {
  const { lng, lat } = e.lngLat
  runSomeFunction(lat, lng).   // <---- i want to test this function
})

I want to test my map using jest. There's already a lot of questions out there surrounding the fact that the mapbox-gl fails pretty hard outside the browser environment. While some people have tried to find workarounds (fixing the window.URL. createObjectURL problem, using the defunct mapbox-gl-js-mock repo, overcoming the lack of GL in the jest envinroment), I've been going down that rabbit hole for about 2 days. Its time for another approach.

Many talk about mocking mapbox, like this:

jest.mock('mapbox-gl', () => ({
  Map: jest.fn(() => ({
    on: jest.fn(),
    otherMethods: jest.fn(),
  })),
}));

I can use this method and get my tests to pass. But I can't really test any interesting behavior. How can I mock the behavior of a user clicking on the map, and test that I expect(runSomeFunction).toHaveBeenCalledWith(whatever)?

I really don't know where to start, as I can't find a single example of a jest unit test that actually tests map behavior or events. In hopes of finding something parallel, I've also looked into how to test leaflet map events in jest, but I haven't found anything helpful.

Seth Lutske
  • 9,154
  • 5
  • 29
  • 78
  • I know it's been a while, but curious if you found any good resources for this. I'm starting down a similar rabbit hole. – MikeTheReader Nov 17 '21 at 19:13
  • Unfortunately no, I was never able to overcome this. Its funny because this question was inspired by a take-home interview question for an interview - with mapbox. In that interview, the interviewer told me their team was very intense about unit testing and that they unit test everything. In trying to solve the challenge, I (think I) left no stone unturned, and I found almost no examples in the mapbox docs or elsewhere outlining how to unit test a mapbox map. Maybe that's changed in the last 6 months? Good luck! – Seth Lutske Nov 17 '21 at 23:29
  • Ha, hasn't changed! I'm now also trying to find the best way to test functions inside of mapbox events... – Greg McKelvey Mar 23 '22 at 23:11

0 Answers0