在 React 中测试 mapbox-gl 时如何修复 'window.URL.createObjectURL is not a function'?

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

我正在使用 Mapbox、material-ui 和自定义样式测试 React 组件。我使用 Jest + Enzyme 进行测试。

我有问题:'window.URL.createObjectURL is not a function'。我读过类似的问题: github.com/uber/react-map-gl/issues/210
github.com/mapbox/mapbox-gl-js/issues/3436
github.com/mapbox/mapbox-gl-js-mock

并尝试添加一些内容但没有成功。请解决问题。

CodeSandbox

我的 jest 测试套件遇到了完全相同的问题。经过一些尝试和搜索,我能够模拟 createObjectURL 方法。

jest.stub.js文件中,我把这个配置:

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

然后,在 jest.config.js 文件中,我添加了对存根文件的引用

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

注意:确保您在 setupFile 定义中获得正确的路径。

  1. 添加包:mapbox-gl-js-mock
  2. 添加要求("mapbox-gl-js-mock");在 jest.mock(

    从 'react' 导入 React; 从'@material-ui/core/test-utils'导入{createShallow};

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

我有同样的问题 运行 使用库 Plotly.js 与 React 和 Jest 进行测试。

我的解决方案是添加一个文件 src/setupTests.js,其中包含 createObjectURL 函数的模拟 window.URL.createObjectURL = function() {};

我也将 React 与 Mapbox-gl 一起使用,@Pablo Jurado 的解决方案效果很好。

刚刚粘贴window.URL.createObjectURL = function() {};

src/setupTest.js 文件

并将 npm 测试脚本修改为:

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

基于 this example