Skip to content
Advertisement

Jest | TypeError: window.URL.createObjectURL is not a function

This issue happens due to be using mapbox-gl in a React project.

I’m aware that there are solutions like this but due to me being a junior I fail to completely comprehend what I should do to solve.

I don’t have any setupTest.js or jest.stubs.js

Creating them appears to do nothing for my test suites. I’m using ftw-hourly for this project and I added mapbox-gl and @mapbox/mapbox-gl-geocoder as dependencies.

Can someone guide me on how to solve this?

Advertisement

Answer

There’s an important distinction here. This issue is happening because your tests are invoking mapbox-gl, but it is not because you can’t test things that use mapbox-gl.

The issue is that you need to properly mock your dependencies so that they don’t interfere with the behavior you’re actually trying to test. I encourage you to read up on Jest’s documentation about it’s support for this: https://jestjs.io/docs/en/mock-functions

Just to briefly state, your problem and the solution as I understand it:

  1. you are currently testing a function that invokes mapbox-gl within it
  2. when your test runner (jest) gets to this function, it invokes mapbox-gl
  3. because you are testing an isolated function, it’s likely that it does not have all the context necessary for your mapbox-gl invocation to work properly – thus it is throwing an error and your test is failing

So how do you solve this? By creating some stand-in logic for mapbox-gl so your test doesn’t attempt to use the real thing.

The good news is that this is a common issue that devs run into when writing tests, and most testing tools (jest especially) support this concept called mocking / stubbing where you can tell jest “hey, instead of invoking mapbox-gl when this test runs, use this little stand-in function instead.”

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement