8

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

Ilya
  • 93
  • 1
  • 1
  • 4

4 Answers4

17

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.

Manish
  • 4,903
  • 1
  • 29
  • 39
  • Thanks, but how to find jest.stub.js and jest.config.js [in my sandbox](https://codesandbox.io/s/react-enzyme-mapbox-test-qobf0)? – Ilya Sep 16 '19 at 10:03
  • 1
    Finally solution :) May universe server you well, sir. – Seinfeld Sep 27 '19 at 18:17
5

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() {};

Pablo Jurado
  • 91
  • 1
  • 4
1

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

Altivo
  • 21
  • 5
0
  1. Add package: mapbox-gl-js-mock
  2. add require("mapbox-gl-js-mock"); before jest.mock(

    import React from 'react'; import { createShallow } from '@material-ui/core/test-utils';

    import App from './App';
    require("mapbox-gl-js-mock");
    
    jest.mock('mapbox-gl/dist/mapbox-gl', () => ({
      App: () => ({}),
    }));
    
    describe('<App />', () => {
      let shallow;
    
      beforeEach(() => {
        shallow = createShallow({ dive: true });
      });
    
      it('renders without crashing', () => {
        const wrapper = shallow(<App />);
        expect(wrapper.find('.MapBox')).toExist();
      });
    });
    
Oleg
  • 3,580
  • 1
  • 7
  • 12
  • Thanks, but it didn't help. [CodeSandbox with your changes](https://codesandbox.io/s/react-enzyme-mapbox-test-qobf0) – Ilya Sep 16 '19 at 09:59