javascript - 在 Vue 的 window.api 中用 axios 开玩笑
问题描述
我正在尝试在 Vue 中使用 Jest 测试一些组件。我正在使用 shallowMount 来渲染整个组件。我已经阅读了几篇关于如何模拟或测试 axios 的文章,但我没有找到任何像我在main.js
我收到此错误:
TypeError: Cannot read property 'get' of undefined
71 | getInterventions(){
72 | this.isLoading = true;
> 73 | window.api.get('route/' + this.$store.state.user.id + '/restOfTheRoute', {
| ^
74 | headers: {
75 | 'X-Auth-Token': this.$store.state.user.apiToken
76 | }
我调用该方法是window.api = axios
因为我在我的main.js
window.api = axios.create({
baseURL: 'apiLink'
})
我会展示我的test.js
,因为我什至没有尝试过这种可能的重复。
import { mount, shallowMount, createLocalVue } from '@vue/test-utils'
import Carte from '@/views/Carte.vue'
import HereMap from "@/components/HereMap.vue"
import SideBar from "@/components/Sidebar.vue"
import Vuex from 'vuex';
import vuetify from "vuetify"
import axios from 'axios'
jest.mock('axios');
const localVue = createLocalVue();
localVue.use(vuetify);
localVue.use(Vuex);
const mutations = {
testMutation: jest.fn()
}
const store = new Vuex.Store({ mutations })
const wrapper = shallowMount(Carte, {
store, localVue
});
describe('Carte.vue', () => {
it('needs to render the component', () => {
expect(shallowMount(Carte).isVueInstance()).toBe(true);
});
it('check if HereMap exists', ()=>{
expect(wrapper.contains(HereMap)).toBe(true);
});
it('check if SideBar component exists', ()=>{
expect(wrapper.contains(SideBar)).toBe(true);
});
});
我也尝试过:
const api = jest.fn()
Object.defineProperty(window, 'api', api);
如何window.api
在我的Component.test.js
档案中注册?
解决方案
推荐阅读
- google-sheets - 从 Google 表格中的一列术语中查找每个唯一的 2 个单词配对
- javascript - 如何使用 javascript 按元素的类添加所有值?
- c# - 根据字段的值跳过字段的序列化
- python - 如何在不多次引用变量“分数”的情况下创建问题函数?
- autodesk-forge - 如何删除站点、项目、审批工作流、协调空间、合作伙伴卡、自定义属性等?
- jquery - 使用带有复选框的 jsTree 从 Json 数据创建树
- python - Noob试图通过python中的Modbus RTU RS485从他的EnergyMeter获取值
- reporting-services - SSRS 来宾用户权限
- unix - unix - sed 替换带有错误未定义标签的文件
- python - 查找用户是否同时观看了 2 个视频