【发布时间】:2018-12-15 07:30:26
【问题描述】:
我的应用网址有一个全局属性/变量:
Vue.prototype.$apiUrls = {
root: 'http://localhost:8080/',
api: 'api/v1/'
// etc.
}
我在我的组件中使用它作为 axios 请求:
axios.get(`${this.$apiUrls.root}${this.$apiUrls.api}/users/`)
现在我想测试我的组件的代码,我已经模拟了axios,但我仍然收到错误:
TypeError: Cannot read property '$apiUrls' of undefined
我尝试在每个测试和/或 JEST 的设置文件中定义/模拟此属性,例如
global.$apiUrls = {...}
// or
Vue.prototype.$apiUrls = {...}
// or
Object.defineProperties(Vue.prototype, {$apiUrls: {...}})
我也尝试将其模拟为 window 或 this(是的,这很愚蠢),但没有成功 - 我仍然收到该错误 - 请帮助。
【问题讨论】:
-
你也在用
vue-test-utils吗? -
@Derek 不在此特定项目中,但如有必要,我也愿意在这里开始使用它;)
-
我担心的是文档的一部分是这样说的:
Note some plugins, like Vue Router, add read-only properties to the global Vue constructor. This makes it impossible to reinstall the plugin on a localVue constructor, or add mocks for these read-only properties -
hmn 但我认为如果我想模拟
$router道具,或者如果我使用类似Vue.use(myPluginWithApiUrlProperty)的东西(但不确定) -
你解决了吗?如果您需要任何澄清,请告诉我!
标签: unit-testing vue.js mocking vuejs2 jestjs