Search code examples
unit-testingvue.jsjestjsnuxt.jsvue-test-utils

VueComponent.mounted : TypeError: Cannot read property 'get' of undefined in mounted hook


I am using jest for unit testing in nuxt js I have mounted hook like this

async mounted(){
  
  try{
     var response = await this.$axios.get("api_url here");
     this.result = response.data;
  } catch(e){
    console.log("Exception: ",e)
  }
}

when i do unit test for it my code is . utnit.spec.js

jest.mock("axios", () => ({
   get: () => Promise.resolve({ data: [{ val: 1 }] })
}));


import { mount } from '@vue/test-utils';
import file from '../filefile';
import axios from "axios";


describe('file', () => {
  test('check comp. working correctly', () => {
    var wrapper = mount(file);
    afterEach(() => {
      wrapper.destroy()
    })
  })   
})

I am getting this warn there and there is no data in the results

Exception:  TypeError: Cannot read property 'get' of undefined
          at VueComponent.mounted

how do I know what is the problem here, is this I can not access axios in the unit file Is there any specific way to test Axios in mounted hook


Solution

  • The error means that it's this.$axios.get that is not available, not axios.get. The component relies on Axios plugin that is commonly installed in Vue application entry point or Nuxt configuration.

    It can be installed for localVue Vue instance in tests, or be supplied directly to the component:

    var wrapper = mount(file, { mocks: { $axios: axios } });
    

    Also, the mock will fail if Axios is used as axios() somewhere because default import is expected to be a function:

    jest.mock("axios", () => Object.assign(
      jest.fn(),
      { get: jest.fn() }
    ));
    

    axios.get is Jest spy, the implementation is mocked per test depending on the use and isn't limited to hard-coded Promise.resolve({ data: ... }) supplied in the mock.