在 React 中测试 mapbox-gl 时如何修复“window.URL.createObjectURL 不是函数”?

Ily*_*lya 6 unit-testing reactjs mapbox-gl-js enzyme

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

我有问题:“window.URL.createObjectURL 不是函数”。我读过类似的问题: github.com/uber/react-map-gl/issues/210
github.com/mapbox/mapbox-gl-js/issues/3436
github.com/mapbox/mapbox-gl-js-mock

并试图添加一些东西但没有成功。请解决问题。

代码沙盒

Man*_*Raj 12

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

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

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

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

  setupFiles: [
    '<rootDir>/tests/jest.stub.js',
  ],
Run Code Online (Sandbox Code Playgroud)

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


小智 5

我在使用 Plotly.js 库与 React 和 Jest 运行测试时遇到了同样的问题。

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