jeudi 26 décembre 2019

Yields "TypeError: Cannot read property 'xxxx' of undefined" after running jest with Vue

I'm trying to make a test using jest with Vue.

the details below.

Problem:

  • Can't mount using shallowMount option.

Situation:

  1. Run the test after mounting the component using shallowMount option that provides in Vue-test-utils.
  2. Throw error "Cannot read property 'XXXX' of undefined

This is my test code.

import myComponent from '@/~';
import Vuex from 'vuex';
import Vuelidate from 'vuelidate';
import { shallowMount, createLocalVue } from '@vue/test-utils';

const localVue = createLocalVue();
localVue.use(Vuex);
localVue.use(Vuelidate);

describe('myComponent~', () => {
  let store;

  beforeEach(() => {
    store = new Vuex.Store({
      modules: {
        user: {
          namespaced: true,
          getters: {
            profile: () => {
              const profile = { name: 'blahblah' };
              return profile;
            },
          },
        },
      },
    });
  });

  describe('profile.name is "blahblah"', () => {
    it('return something~', () => {
      const wrapper = await shallowMount(myComponent, {
        localVue,
        store,
        mocks: {
          $api: {
            options: {
              testMethod() {
                return new Promise((resolve, reject) => {
                  resolve('test');
                });
              },
            },
          },
          $i18n: {
            t() {
              return {
                EN: 'EN',
                KO: 'KO',
                JP: 'JA',
                SC: 'zh-CN',
                TC: 'tw-CN',
              };
            },
          },
        },
      });
      expect(wrapper.find('.profile').text()).toBe('blahblah');
    });

I think the problem is that property isn't set as a specified value or an empty value like an array or object.

But how I set properly the properties in my logic.

For example,

when the error yields "Cannot read property 'images' of undefined",

I add to a wrapper in the relevant method like this.

exampleMethod() {
 this.something = this.something.map(item => {
  if (item.detailContent.images) { // <-- the added wrapper is here
   ~~~logic~~~~
  }
 })
}

But the undefined properties are so many, I also think this way is not proper.

How I do solve this problem?

Aucun commentaire:

Enregistrer un commentaire