Unit Test Vuetify v-select @change event?

Viewed 3923

Can't write test which tests Vuetify v-select @change event. Event handler select_change doesn't called inside test.

Demo.vue

    <div>
        <v-select @change="select_change" :items="[1,2,3]" v-model="value"></v-select>
    </div>
    export default {
        data() {
            return {
                value: 1,
            }
        },
        methods: {
            select_change() {
                console.log('inside select_change')
            }
        }
    }

Demo.vue.test.js

    it('v-select@change', () => {
        wrapper = mount(Demo, {
            vuetify: new Vuetify
        })
        wrapper.setMethods({
            select_change: jest.fn(),
        })
        wrapper.find('.v-select').trigger('change', /* {value: 2} */)
        expect(wrapper.vm.select_change).toBeCalled()
    })

test output

Error: expect(jest.fn()).toBeCalled()

Expected number of calls: >= 1 Received number of calls: 0

1 Answers

This is probably not the answer you want, but it's not your job to test the <v-select> component's @change event. This event is already tested by the Vuetify team among the unit tests for this component. FWIW, it's fairly common for people to want to write tests like the one you describe.

However, your job is to make sure that your component (the one that wraps v-select) defines an appropriate interface/contract, and that it abides by it. Some examples of things you might reasonably test:

  1. Does the list of items assigned to the v-select have exactly three elements that are 1, 2, and 3?
  2. Does this component have a method called select_change() and does that function return expected values with given input? (BTW, your select_change() method doesn't currently return any values so is difficult to test)

Your tests might look something like:

import { createLocalVue, mount } from '@vue/test-utils'
import Vue from 'vue'
import Vuetify from 'vuetify'
import Demo from '@/components/Demo'

Vue.use(Vuetify)
const vuetify = new Vuetify()
const localVue = createLocalVue()

describe('A Demo component', () => {
  it('has a `v-select` with 3 items: [1, 2, 3]', () => {
    const wrapper = mount(Demo, { localVue, vuetify })
    const items = wrapper.find('.v-select').props('items')
    expect(items.length).toBe(3)
    expect(items).toStrictEqual([1, 2, 3])
  })

  it('has item 1 selected by default', () => {
    const wrapper = mount(Demo, { localVue, vuetify })
    expect(wrapper.find('.v-select').props('value')).toBe(1)
  })
})

As tempting as it may be to want to test the underlying functionality of the v-select component, you've got to trust that the Vuetify team did their job. :-)

Related