我们正在使用vuejs,打字稿,vuex和jest。我们目前正在使用test-utils模拟商店。
但是我不知道如何模拟对this。$ parent。$ on
的呼叫这是我们的组成部分之一(非常简化):
AnalysisList.ts:
import Component from 'vue-class-component'
import {Getter} from 'vuex-class'
import {UserVO} from '@/valueObjects/UserVO'
import {Vue} from 'vue-property-decorator'
@Component
export default class AnalysisList extends Vue {
@Getter('getCurrentUser') private currentUser: UserVO
private searchString = ''
public mounted() {
this.$parent.$on('resetAnalyses', this.reset)
}
public reset() {
this.searchString = ''
}
}
AnalysisList.vue:
<template lang="pug">
text test
</template>
<script lang="ts" src="./AnalysisList.ts">
</script>
AnalysisList.spec.ts:
import {shallowMount} from '@vue/test-utils'
import AnalysisList from '@/components/analysis/AnalysisList'
import Vuex from 'vuex'
import {Vue} from 'vue-property-decorator'
import VueRouter from 'vue-router'
Vue.use(Vuex)
Vue.use(VueRouter)
describe('AnalysisList.vue', () => {
const store = new Vuex.Store( {
modules: {
user: {
state: {currentUser: 'test'},
getters: {
getCurrentUser: (state: any) => state.currentUser,
},
},
},
})
it('minimum test', (done) => {
const wrapper = shallowMount(AnalysisList, {store})
done()
})
})
运行测试时,出现以下错误消息,因为未对$ parent进行模拟:
TypeError: Cannot read property '$on' of undefined
at VueComponent.mounted (src/components/analysis/AnalysisList/AnalysisList.vue:73:20)
at callHook (node_modules/vue/dist/vue.runtime.common.js:2919:21)
at mountComponent (node_modules/vue/dist/vue.runtime.common.js:2800:5)
at VueComponent.Object.<anonymous>.Vue.$mount (node_modules/vue/dist/vue.runtime.common.js:7997:10)
at mount (node_modules/@vue/test-utils/dist/vue-test-utils.js:5381:8)
at shallowMount (node_modules/@vue/test-utils/dist/vue-test-utils.js:5414:10)
at Object.done (tests/unit/AnalysisList.spec.ts:20:53)
如果我尝试向shallowMount参数添加新属性:
const wrapper = shallowMount(AnalysisList, {store, parent: {$on: ()=>{}}})
我收到类型错误:
TS2345: Argument of type 'VueConstructor<Vue>' is not assignable to parameter of type 'FunctionalComponentOptions<Record<string, any>, PropsDefinition<Record<string, any>>>'. Property 'functional' is missing in type 'VueConstructor<Vue>'.
您有什么帮我嘲笑this.$parent.$on
的线索吗?谢谢。
答案 0 :(得分:0)
我在vue-test-utils和Jest(在Vue,Vuex和Typescript环境下)遇到了相同的问题
对我来说,vue-test-utils库的createLocalVue()解决了该问题。此功能创建Vue的本地副本,以在安装组件时使用。在此Vue
副本上安装插件可防止污染原始Vue
副本。 (https://vue-test-utils.vuejs.org/api/options.html#localvue)
将此添加到我的测试文件中可解决此问题:
const EventBus = new Vue();
const GlobalPlugins = {
install(v) {
// Event bus
v.prototype.$bus = EventBus;
},
};
// create a local instance of the global bus
const localVue = createLocalVue();
localVue.use(GlobalPlugins);
希望这对其他人有帮助,谢谢:)