Search code examples
javascriptvue.jsvuejs2jestjsvuex

Unit testing in Vue2 with Jest


For a school project we must write some unit-tests in a Vue2 codebase. I have never used Vue2 nor Jest, but I am familiar with Javascript.

I wanted to start creating a very simple unit-test, just to see how it works. Jest automatically creates a HelloWorld unit-tests that passes message to a component, and checks if the message is rendered correctly;

import { shallowMount } from "@vue/test-utils";
import Login from "@/components/authentication/Login.vue";

describe("Login.vue", () => {
    it("renders props.msg when passed", () => {
        const msg = "new message";
        const wrapper = shallowMount(Login, {
        propsData: { msg }
        });
        expect(wrapper.text()).toMatch(msg);
    });
});

However, i get this error when running the test;

Cannot read properties of undefined (reading 'dispatch')
TypeError: Cannot read properties of undefined (reading 'dispatch')

There seems to be something wrong with the ShallowMount, people with the same error had problems with vuex store, but that doesn't seem to be my problem.

Thank You!


Solution

  • dispatch is usually related to Vuex store actions. You need to add Vuex and your store to the mounted component. You can use createLocalVue if you're using Vue 2.x to install Vuex on it.

    import { shallowMount, createLocalVue } from '@vue/test-utils'
    import Vuex from 'vuex'
    
    const localVue = createLocalVue()
    localVue.use(Vuex)
    
    describe('Login', () => {
        const store = new Vuex.Store({
            actions: {
                // any actions or getters you access in Login.vue
            },
        })
    
        it("renders with message", () => {
            const wrapper = shallowMount(Login, {
                localVue,
                store,
                propsData: { msg: 'Hello' }
            })
            
            // ...
        })
    })