简体   繁体   中英

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?

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."

If you used Create React App to build you app you can use the setupTest.js file like documneted here: https://create-react-app.dev/docs/running-tests/#initializing-test-environment I had the same problem and I just added window.URL.createObjectURL = () => {} to setupTests.js.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM