如何修复'窗口。URL.createObjectURL 在 React 中测试 mapbox-gl 时不是一个函数?



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

我有问题:"窗口。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

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

代码沙盒

我的笑话测试套件也遇到了完全相同的问题。经过一些试验和搜索,我能够模拟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',
],

注意:请确保在安装程序文件定义中获取正确的路径。

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

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

我也在 Mapbox-gl 中使用 React @Pablo Jurado 的解决方案运行良好。

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

src/setupTest.js文件

并且还修改了 npm 测试脚本以:

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

基于 这个例子

  1. 添加包:mapbox-gl-js-mock
  2. add require("mapbox-gl-js-mock"(; 在 jest.mock(

    从"反应"导入反应; 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();
    });
    });
    

最新更新