VueComponent.mounted : TypeError: Cannot read property 'get' of undefined in mounted hook
VueComponent.mounted : TypeError: Cannot read property 'get' of undefined in mounted hook
我在 nuxt js 中使用 jest 进行单元测试
我已经安装了这样的钩子
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有没有具体的方法可以在mounted hook中测试axios
错误意味着 this.$axios.get
不可用,而不是 axios.get
。该组件依赖于通常安装在 Vue 应用程序入口点或 Nuxt 配置中的 Axios 插件。
它可以在测试中为 localVue
Vue 实例安装,或者直接提供给组件:
var wrapper = mount(file, { mocks: { $axios: axios } });
此外,如果 Axios 在某处用作 axios()
,模拟将失败,因为默认导入预计是一个函数:
jest.mock("axios", () => Object.assign(
jest.fn(),
{ get: jest.fn() }
));
axios.get
是 Jest 间谍,根据用途模拟每个测试的实现,不限于模拟中提供的 hard-coded Promise.resolve({ data: ... })
。
我在 nuxt js 中使用 jest 进行单元测试 我已经安装了这样的钩子
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有没有具体的方法可以在mounted hook中测试axios
错误意味着 this.$axios.get
不可用,而不是 axios.get
。该组件依赖于通常安装在 Vue 应用程序入口点或 Nuxt 配置中的 Axios 插件。
它可以在测试中为 localVue
Vue 实例安装,或者直接提供给组件:
var wrapper = mount(file, { mocks: { $axios: axios } });
此外,如果 Axios 在某处用作 axios()
,模拟将失败,因为默认导入预计是一个函数:
jest.mock("axios", () => Object.assign(
jest.fn(),
{ get: jest.fn() }
));
axios.get
是 Jest 间谍,根据用途模拟每个测试的实现,不限于模拟中提供的 hard-coded Promise.resolve({ data: ... })
。