Testing a Vue mixin in a Vue component

September 06, 2023

Have you ever needed to test a Vue component that contains a Vue mixin? Let’s say you need to test that the a function inside of the mixin fires correctly.

Prerequisites

  • Vue project
  • vue-test-utils

Creating the test

First of all we, need to set up the test. This can be done by creating a wrapper.

import { createLocalVue, mounth } from '@/vue/test-utils'
import VueComponent from '@/component/VueComponent.vue'

describe('VueComponent.vue', () => {
    const localVue = createLocalVue()
    const createWrapper = () => {
        return mount(VueComponent, {
            localVue,
        })
    }

    it('should test the mixin', () => {
        const wrapper = createWrapper()
        // Let's add some more
    })
})

This function helps you set up the component in subsequent tests.

Adding the test for the method

Now we have the boilerplate for the test, lots easier to just add the mixin test. The premise for this is that we have a component method, that calls a subsequent mixin function. For this, we’ll need to spy on the mixin function.

import { createLocalVue, mounth } from '@/vue/test-utils'
import VueComponent from '@/component/VueComponent.vue'
import VueMixin from '@/mixins/VueMixin.js'

describe('VueComponent.vue', () => {
    const localVue = createLocalVue()
    const createWrapper = () => {
        return mount(VueComponent, {
            localVue,
        })
    }

    it('should call mixin method when calling component method', () => {
        const functionNameSpy = jest.spyOn(VueMixin.methods, 'functionName')
        const wrapper = createWrapper()
        wrapper.componentFunction()
        expect(functionNameSpy).toHaveBeenCalledWith()
    })
})

And now finally, we have a test that check that the function is actually called inside of the component.

Wrap-up

There we go, a perfect test for your Vue component.


Profile picture

Written by An anonymous coder who lives and works building useful things. Mostly focusing on Django, Vue and overall Python examples.