VueJS - Unit testing with vue-test-utils gives error - TypeError: _vm.$t is not a function

Karan Rao picture Karan Rao · Feb 14, 2018 · Viewed 13.2k times · Source

Relatively new to Vuejs and testing its components. Using vue-test-utils and jest for testing. Getting following error test log

The .vue file consists of template, component and styling. Below is the part of the SignupLayout.vue that gets error -

Test File -

import Vue from 'vue';
import Vuex from 'vuex'
import SignupLayout from '../src/components/SignupLayout.vue';
import { mount, shallow, createLocalVue } from '@vue/test-utils';

const localVue = createLocalVue()

localVue.use(Vuex)

jest.resetModules()

describe('Signup.test.js', () => {
    let cmp
    let actions
    let store
    let getters
    let state

    beforeEach(() => {


        state = {
            email: '[email protected]'
        }
 
        getters = {
            CURRENT_USER_EMAIL: state => state.email
        }

        store = new Vuex.Store({
            getters
        })


    })

    it('has received ["Login"] as the title property', () => {
        cmp = shallow(SignupLayout, {
            store,
            localVue,
            propsData: {
                title: ['Login']
            },
            data: {
                email: '[email protected]'
            }
        })
        cmp.update()
        expect(cmp.vm.title).toEqual(['Login'])
    })


})

Confused as to what has $t got to do with sass. Any help would be appreciated. Stuck here for a while now. Let me know if more details needed. Thanks in advance

Answer

Dobromir Hristov picture Dobromir Hristov · Mar 15, 2018
const $t = () => {}

shallow(Component, {
 mocks:{ $t }
})

This way you dont have to load the whole i18n library. You can even spy on the function with Sinon or jest.fn() if using Jest.