首页 > 解决方案 > 在 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档案中注册?

标签: javascriptapivue.jsjestjsaxios

解决方案


推荐阅读