使用 b 按钮对 vue 路由进行单元测试 "to"

Unit testing vue routing with b-button "to"

我有一个包含来自 Vue Bootstrap 的 b 按钮组件的组件。在我的单元测试中,我想检查当我在组件中单击该按钮时,我是否被路由到我在传递给 b 按钮的 "to" 道具中指定的 url。

我的问题是在我的单元测试中没有触发路由。或者其中的 b-button / router-link 没有使用我的路由器实例。

我该如何测试?我什至需要吗?我简化了我的示例 - 我知道 "to" 功能包含在 b-button 自己的单元测试中,但我想测试我是否将正确的 url 传递给它。

演示组件

<template>
    <b-card
        header="Button demo"
    >
        <b-button
            class="test"
            v-bind:to="toPath"
        >Test</b-button>
    </b-card>
</template>

<script>
export default {

    name: 'ButtonDemo',

    data(){
        return {
            toPath: '/expected/path'
        }
    }

}
</script>

单元测试

import { mount, createLocalVue } from '@vue/test-utils'
import ButtonDemo from '@/path/to/ButtonDemo'
import BootstrapVue from 'bootstrap-vue'
import Vuex from 'vuex'
import VueRouter from 'vue-router'

const localVue = createLocalVue()

localVue.use(VueRouter)
const router = new VueRouter()

localVue.use(BootstrapVue)

describe('List', () => {

    let $wrapper

    test('Clicking "new" takes you to the create flow', async () => {

        $wrapper = mount(ButtonDemo, { localVue, router })

        $wrapper.find('.test').trigger('click')

        expect($wrapper.vm.$route.path).toBe('/expected/path')

    })

})

只需测试 b-button 上设置的 to 属性是否为预期值。

let button = $wrapper.find('.test')
expect(button.props('to')).toBe('/expected/path')

正如您所说,b-button 组件的单元测试应该已经涵盖了路由到给定路径的测试。

旁注:请考虑在单元测试中使用 shallowMount 而不是 mount