3

我正在尝试对(使用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

4

2 回答 2

3

让它工作,但有一种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()方法的原因

于 2018-06-20T17:56:05.863 回答
0

以下代码对我来说可以很好地测试路线导航守卫。

const beforeRouteUpdate = wrapper.vm.$options.beforeRouteUpdate[0];
let nextFun = jest.fn();
beforeRouteUpdate.call(wrapper.vm , "toObj", "fromObj", nextFun); 

测试路线导航守卫 git hub

如何在更新导航守卫之前测试Vue路由器

于 2020-04-16T14:10:57.067 回答