Vue.js 在组件导航卫士中测试Vue路由器
我正在尝试单元测试(使用Vue.js 在组件导航卫士中测试Vue路由器,vue.js,vue-router,vue-test-utils,Vue.js,Vue Router,Vue Test Utils,我正在尝试单元测试(使用vue test utils)一个组件,它在组件导航保护中有一个beforeRouteUpdate,如下所示: <template> ... </template> <script> export default { computed: { ... } ... beforeRouteUpdate(to, from, next) { // code to be test
vue test utils
)一个组件,它在组件导航保护中有一个beforeRouteUpdate
,如下所示:
<template>
...
</template>
<script>
export default {
computed: {
...
}
...
beforeRouteUpdate(to, from, next) {
// code to be tested
this.$store.dispatch('setActiveTask')
}
}
</script>
it('test', () => {
const beforeRouteUpdate = wrapper.vm.$options.beforeRouteUpdate
const $store = {
dispatch: () => {
}
}
spyOn($store, 'dispatch').and.returnValue({ then: (arg) => arg() })
let next = jasmine.createSpy('next')
render()
beforeRouteUpdate.call({ $store }, {
params: {
taskID: 1
}
}, {}, next)
expect($store.dispatch).toHaveBeenCalledWith('setActiveTask', 1)
expect(next).toHaveBeenCalled()
})
有人对此有什么想法吗
更新:
我用
@vue/cli
和Mocha+Chai作为单元测试工具创建了一个简单的示例,可以在这里找到:让它工作了,但使用了一种黑客解决方案。
我的测试现在如下所示:
<template>
...
</template>
<script>
export default {
computed: {
...
}
...
beforeRouteUpdate(to, from, next) {
// code to be tested
this.$store.dispatch('setActiveTask')
}
}
</script>
it('test', () => {
const beforeRouteUpdate = wrapper.vm.$options.beforeRouteUpdate
const $store = {
dispatch: () => {
}
}
spyOn($store, 'dispatch').and.returnValue({ then: (arg) => arg() })
let next = jasmine.createSpy('next')
render()
beforeRouteUpdate.call({ $store }, {
params: {
taskID: 1
}
}, {}, next)
expect($store.dispatch).toHaveBeenCalledWith('setActiveTask', 1)
expect(next).toHaveBeenCalled()
})
导航卫士在
wrapper.vm.options.beforeUpdate
中可用,但调用它时我丢失了this
的上下文,因此我无法在组件导航卫士中调用this.$store.dispatch
,这就是为什么我需要使用.call()
方法以下代码对我测试路线导航卫士非常有效
const beforeRouteUpdate = wrapper.vm.$options.beforeRouteUpdate[0];
let nextFun = jest.fn();
beforeRouteUpdate.call(wrapper.vm , "toObj", "fromObj", nextFun);