vue.js - 在组件导航防护中测试 Vue Router
问题描述
我正在尝试对(使用vue-test-utils
)一个组件进行单元测试,该组件具有这样beforeRouteUpdate
的组件导航保护:
<template>
...
</template>
<script>
export default {
computed: {
...
}
...
beforeRouteUpdate(to, from, next) {
// code to be tested
this.$store.dispatch('setActiveTask')
}
}
</script>
我确实在测试文件中渲染了组件,shallowMount
并模拟了$store
.
beforeEach(() => {
cmp = shallowMount(Task, {
mocks: {
$store: store,
$route: {
params: {
taskID: 12,
programID: 1
}
}
},
i18n: new VueI18N({
silentTranslationWarn: true
}),
stubs: {
'default-layout': EmptySlotComponent,
'nested-router': EmptySlotComponent,
RouterLink: RouterLinkStub
}
})
})
it('has beforeRouteUpdate hook', () => {
// how do i call beforeRouteUpdate now?
// cmp.vm.beforeRouteUpdate(...)
}
有人对此有什么想法吗?
更新:我用 Mocha + Chai 作为单元测试工具创建了一个最小的例子@vue/cli
,可以在这里找到:https ://github.com/BerniWittmann/vue-test-navigation-guard-reproduction
解决方案
让它工作,但有一种hacky解决方案。我的测试现在看起来像这样:
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.beforeRouteUpdate
,但是调用它我丢失了上下文,this
所以我无法调用this.$store.dispatch
组件导航守卫,这就是我需要使用该.call()
方法的原因
推荐阅读
- android - 从 AsyncTask doInBackground 返回时应用程序崩溃
- sharepoint - 使用 Graph API 添加共享点自定义字段
- python - Python Selenium:元素未附加到页面文档错误行为奇怪
- android - Android 设备无法连接到 firebase DebugView
- facebook - 在浏览器之间导出 cookie 的安全问题
- r - R:从 3.5 降级到 3.4 后无法安装软件包。dyn.load 中的错误(文件,DLLpath = DLLpath,...)
- sql - 创建 XML 数据集的组合
- python-3.x - 计算数值列 Pandas 中的字符串值
- firebase - Firebase 云存储安全规则和 Firebase 数据库连接
- python - 在卷积网络中共享滤波器权重