VueComponent.mount:TypeError:无法读取已安装的挂钩中未定义的属性“ get”

问题描述

我正在使用jest在nuxt js中进行单元测试 我已经像这样安装了钩子

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

当我对其进行单元测试时,我的代码是。 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()
    })
  })   
})

我收到此警告,结果中没有数据

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

我怎么知道这里是什么问题,这是我无法访问单元文件中的axios吗?是否有任何特定的方法可以在挂接的钩子中测试Axios

解决方法

该错误表示this.$axios.get不可用,axios.get不可用。该组件依赖于Axios插件,该插件通常安装在Vue应用程序入口点或Nuxt配置中。

它可以为测试中的localVue Vue实例安装,或直接提供给组件:

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

此外,如果Axios在某处用作axios(),则模拟将失败,因为默认导入是函数:

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

axios.get是Jest间谍,每次测试都会根据用途对实现进行模拟,并且不仅限于模拟中提供的硬编码Promise.resolve({ data: ... })