编程技术网

关注微信公众号,定时推送前沿、专业、深度的编程技术资料。

 找回密码
 立即注册

QQ登录

只需一步,快速开始

极客时间

在React中测试mapbox-gl时如何解决"window.URL.createObjectURL不是函数"?:How to fix 'window.URL.createObjectURL is not a function' when testing mapbox-gl in React?

rikbrowning 面向对象 2022-5-11 10:26 8人围观

腾讯云服务器
在React中测试mapbox-gl时如何解决"window.URL.createObjectURL不是函数"?的处理方法

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

I'm testing React component with Mapbox, material-ui and custom styles. I use Jest + Enzyme for testing.

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

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

问题解答

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

I had faced exactly same issue with my jest test suite. After some trial and searching, I was able to mock the createObjectURL method.

jest.stub.js 文件中,我放置了以下配置:

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

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

Then, in jest.config.js file, I added a reference to the stub file

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

注意:请确保您在setupFile定义中正确获得了路径.

Note: make sure you get the path right in setupFile defintion.

这篇关于在React中测试mapbox-gl时如何解决"window.URL.createObjectURL不是函数"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程技术网(www.editcode.net)!

腾讯云服务器 阿里云服务器
关注微信
^