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

依然范特西╮ 提交于 2020-01-16 09:02:29

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/57943736/how-to-fix-window-url-createobjecturl-is-not-a-function-when-testing-mapbox-gl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!