Search code examples
unit-testingvue.jsvue-routerbootstrap-vuevue-test-utils

Unit testing vue routing with b-button "to"


I have a component that contains a b-button component from Vue Bootstrap. In my the unit test, I want to check that when I click that button within the component, I get routed to the url I specified in the "to" prop I'm passing to b-button.

My problem is the routing is not being triggered in my unit test. Or b-button / router-link within it aren't using the my router instance.

How can I test this? Do I even need to? I've simplified my examples - I know that the "to" functionality is covered by b-button's own unit tests, but I wanted to test that I'm passing the correct url to it.

Demo component

<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>

Unit test

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')

    })

})

Solution

  • Just test that the to prop set on b-button is the expected value.

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

    As you said, tests for routing to a given path should already be covered by unit tests of b-button component.

    Side Note: Please consider using shallowMount instead of mount in your unit tests.