javascript - 如何在 vue.js 单元测试中模拟 window.google
问题描述
我正在尝试测试一个显示谷歌地图的 vue 组件
google include script 元素位于父组件中的某个位置,而我尝试测试的组件是全局引用它:
const googleInstance = window.google
当我看到它是全球性的时,我的警钟响了,但它是给我的代码,我需要提高我的覆盖率!
组件中的代码在这里获取实例:
this.map = new googleInstance.maps.Map(mapElement, this.options)
我从以下开始收到很多错误:
TypeError: Cannot read property 'maps' of undefined
我尝试在浅层安装包装器时将 googleInstance 和 google 添加到 mocks 参数
const wrapper = shallowMount(Map, {
mocks: {
google: {
maps: () => {}
}
}
})
两者都不起作用,我得到了相同的回应:
TypeError: Cannot read property 'maps' of undefined
我试过了:
global.google = {
maps: () => {}
}
那也不起作用
这是我正在尝试测试的地图组件的简化版本:
<template>
<div>
<div refs="mapLayer" :id="mapName" class="mapLayer" />
</div>
</template>
<script>
const googleGlobal = window.google
export default {
name: 'Map',
props: {
name: {
type: String,
required: true
}
},
mounted () {
this.initMap()
},
methods: {
initMap () {
const mapElement = document.getElementById(this.mapName)
this.map = new googleGlobal.maps.Map(mapElement)
}
}
}
</script>
代码已经过重构,之前谷歌实例是通过 Vuex 商店来的,我的测试有效
我的另一个想法是从一个单独的文件中返回 googleInstance,然后我可以使用 jest 来模拟它,但最终这只是将问题转移到另一个仍然无法测试的文件
如何模拟组件中的值,或者如何将代码重构为可测试?
解决方案
问题是const googleGlobal = window.google
在您在测试文件中引入模拟之前,您的句子正在执行。
因此,googleGlobal
常数等于undefined
。对此的解决方案可能是在您的组件中定义一个返回全局变量的方法google
,并通过调用此方法获取引用。
<script>
export default {
name: 'Map',
props: {
name: {
type: String,
required: true
}
},
mounted () {
this.initMap()
},
methods: {
getGoogle() {
return window.google
},
initMap () {
const googleGlobal = this.getGoogle()
const mapElement = document.getElementById(this.mapName)
this.map = new googleGlobal.maps.Map(mapElement)
}
}
}
</script>
然后,在您的测试文件中,您可以模拟window.google
如下:
window.google = {
maps: { Map: function() {} }
}
推荐阅读
- flutter - Flutter Complex Parsing Json Undefined getter "List
' - amazon-web-services - 无法将弹性 IP 重新分配给 EC2 扩展组
- fabricjs - 如何在自由绘图中重复路径?
- sql-server - “服务器”在嵌入式服务器 dbms 中的作用是什么?- 在寻找合适的 rdbms 时出现的许多与“服务器”相关的术语感到困惑
- python-3.x - 如何使用 for 循环将键和值对添加到新的空字典?
- flutter - 在没有互联网的情况下连接两部智能手机 (Flutter)
- reactjs - setState 钩子没有正确更新,即使在异步处理之后
- php - 167289889 字节的 POST 内容长度超过了 41943040 字节的限制
- python - 不使用 Selenium 渲染整个页面
- python - Django runserver 命令失败