Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix 'window.URL.createObjectURL is not a function' when testing mapbox-gl in React?

I'm testing React component with Mapbox, material-ui and custom styles. I use Jest + Enzyme for testing.

I have problem: 'window.URL.createObjectURL is not a function'. I read similar questions: github.com/uber/react-map-gl/issues/210
github.com/mapbox/mapbox-gl-js/issues/3436
github.com/mapbox/mapbox-gl-js-mock

and tried to add something but without success. Please, fix the issue.

CodeSandbox

like image 589
Ilya Avatar asked Sep 15 '19 11:09

Ilya


3 Answers

I had faced exactly same issue with my jest test suite. After some trial and searching, I was able to mock the createObjectURL method.

In jest.stub.js file, I put this config:

if (typeof window.URL.createObjectURL === 'undefined') {
  window.URL.createObjectURL = () => {
    // Do nothing
    // Mock this function for mapbox-gl to work
  };
}

Then, in jest.config.js file, I added a reference to the stub file

  setupFiles: [
    '<rootDir>/tests/jest.stub.js',
  ],

Note: make sure you get the path right in setupFile defintion.

like image 161
Manish Avatar answered Oct 27 '22 20:10

Manish


I had the same issue running tests using the library Plotly.js with React and Jest.

My solution was to add a file src/setupTests.js with a mock for the createObjectURL function window.URL.createObjectURL = function() {};

like image 4
Pablo Jurado Avatar answered Oct 27 '22 21:10

Pablo Jurado


I also was using React with Mapbox-gl and @Pablo Jurado's solution worked perfectly.

Just pasted window.URL.createObjectURL = function() {};

to src/setupTest.js file

and also modified npm test script to:

"scripts": { "test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!your-module-name)/\"", },

based on this example

like image 1
Altivo Avatar answered Oct 27 '22 21:10

Altivo