【问题标题】:Unit testing vue routing with b-button "to"使用 b 按钮“to”对 vue 路由进行单元测试
【发布时间】:2020-03-22 03:04:09
【问题描述】:

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

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

我该如何测试呢?我什至需要吗?我已经简化了我的示例 - 我知道 b-button 自己的单元测试涵盖了“to”功能,但我想测试我是否将正确的 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')

    })

})

【问题讨论】:

    标签: unit-testing vue.js vue-router bootstrap-vue vue-test-utils


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 并且由于&lt;b-button&gt; 呈现&lt;router-link&gt;(进而呈现&lt;a&gt;),您可以检查href 属性以查看它的值是否符合您的预期路线的路径。
    • 有道理-谢谢! “mount”是我忘记更改的完整代码的剩余部分。
    • @Iainure 请考虑通过单击tick 图标来接受此答案,以便帮助社区中的其他人。
    • @AnkitKante - 会的。但我会在几天后接受答复,以便有时间进一步回复
    猜你喜欢
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多