Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue unit tests - cannot read property 't' of undefined

I'm using jest to run vue unit tests to check the output of individual components. The component uses vuetify.

I create an instance of vue to mount the component:

import myComponent from './MyComponent.vue';
import VueRouter from 'vue-router';
import Vuetify from 'vuetify';

describe('Component', () => {
    let wrapper;

    const router = new VueRouter({
        base: '/ui/',
        routes: [
            {
                name: 'myRoute',
                path: '/route-to-my-component',
                component: myComponent
            },
        ]
    });

    beforeEach(() => {
        const localVue = createLocalVue();
        localVue.use(VueRouter);
        localVue.use(Vuetify);

        wrapper = mount(myComponent, {
            localVue: localVue,
            router
        });
    });



    it('contains a container', () => {
      expect(wrapper.contains('v-container')).toBe(true);
    })
});

I expect this test to pass, but instead I'm getting TypeError: Cannot read property 't' of undefined.

For reference, I was following https://fernandobasso.github.io/javascript/unit-testing-vue-vuetify-with-jest-and-vue-test-utils.html.

like image 776
Shobhit Srivastava Avatar asked Mar 03 '23 12:03

Shobhit Srivastava


1 Answers

A couple of (somewhat random) things are needed in order to run vue unit test on top of vuetify:

  1. Avoid using createLocalVue(), per this comment.

  2. Some components (like Autocomplete) need $vuetify.lang and $vuetify.theme to be mocked

Your spec should look like:

import Vuetify from 'vuetify';
import Vue from 'vue';

Vue.use(Vuetify);

it('contains a container', () => {
  const wrapper = mount(FreeAutocomplete, {
    created() {
      this.$vuetify.lang = {
        t: () => {},
      };
      this.$vuetify.theme = { dark: false };
    }
  });

  expect(wrapper.contains('v-container')).toBe(true);
})
like image 95
golfadas Avatar answered Mar 11 '23 17:03

golfadas