首页 > 解决方案 > 如何在 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 来模拟它,但最终这只是将问题转移到另一个仍然无法测试的文件

如何模拟组件中的值,或者如何将代码重构为可测试?

标签: javascriptunit-testingvue.jsjestjsvue-test-utils

解决方案


问题是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() {} }
}

推荐阅读