繁体   English   中英

如何在 vue.js 单元测试中模拟 window.google

[英]How to mock window.google in a vue.js unit test

我正在尝试测试一个显示谷歌地图的 vue 组件

google include 脚本元素位于父组件中的某个位置,我尝试测试的组件在全局范围内引用它:

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>

代码已经重构,之前 google 实例来自 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() {} }
}

通过尝试上述解决方案,我收到了错误

> google.maps.map 不是构造函数

但这种嘲讽奏效了。

    window.google = {
      maps: {
        Map: jest
          .fn()
          .mockImplementationOnce(success => Promise.resolve(success))
      }
    };

在为您的组件定义包装器之前,向全局对象添加一个属性

let google = <some object>;

Object.defineProperty(global, 'google', {
    value: google
})

const wrapper = ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM