如何在JEST测试中模拟全局Vue.js变量

luk*_*ups 6 unit-testing mocking vue.js jestjs vuejs2

我的应用程序网址具有全局属性/变量:

Vue.prototype.$apiUrls = {
  root: 'http://localhost:8080/',
  api: 'api/v1/'
  // etc.  
}
Run Code Online (Sandbox Code Playgroud)

我根据axios请求在组件内部使用它:

axios.get(`${this.$apiUrls.root}${this.$apiUrls.api}/users/`)
Run Code Online (Sandbox Code Playgroud)

现在,我想测试组件的代码,已经进行了模拟axios,但仍然收到错误:

TypeError: Cannot read property '$apiUrls' of undefined
Run Code Online (Sandbox Code Playgroud)

我试图在每个测试中和/或在JEST的安装文件中定义/模拟此属性,例如

global.$apiUrls = {...}
// or
Vue.prototype.$apiUrls = {...}
// or
Object.defineProperties(Vue.prototype, {$apiUrls: {...}})
Run Code Online (Sandbox Code Playgroud)

我也曾尝试将其嘲笑为windowor this(是的,这很愚蠢),但没有成功-我仍然收到该错误-请帮助。

xen*_*ics 8

有两种方法可以实现这一点。一种是使用该Config选项,如@Aldarund 所述。你可以在这里阅读它。

如果您使用 Jest,我建议您在jest.init.js文件中执行此操作:

import { config } from '@vue/test-utils'

config.mocks['$apiUrls'] = {
  'some/endpoint'
}
Run Code Online (Sandbox Code Playgroud)

然后将此添加到jest您的部分package.json

"setupFiles": [
  "<rootDir>/jest.init.js"
]
Run Code Online (Sandbox Code Playgroud)

现在它被全球嘲笑。如果您想在每个测试的基础上执行此操作,您可以使用mocks安装选项:

const wrapper = shallowMount(Foo, {
  mocks: {
    $apiUrls: 'some/endpoint'
  }
})
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助!

如果您有兴趣,我正在编译有关如何在此处测试 Vue 组件的简单指南集合。它正在开发中,但如果您在测试 Vue 组件的其他相关方面需要帮助,请随时提出问题。