1

I'm trying to test some components with Jest in Vue. I'm doing it with shallowMount so it renders the whole component. I have read a couple of texts of how to mock or test axios but I don't find any that does it like I do in the main.js

I'm getting this error:

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 |               }

I call that method with window.api = axios because I use a couple of API's in my main.js

window.api = axios.create({
  baseURL: 'apiLink'
})

I'll show my test.js because that possible duplicate is not what I'm even trying.

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);
    });

});

I have also tried with:

const api = jest.fn()
Object.defineProperty(window, 'api', api);

How can I register window.api in my Component.test.js file?

Jalil
  • 1,167
  • 11
  • 34
  • OK? You're not doing what the duplicate suggests, so I guess it stands. – jonrsharpe May 27 '19 at 13:01
  • 3 of those answers are doing something I'm not. And t have tried the last one – Jalil May 27 '19 at 13:04
  • `jest.mock('axios')` alone is not enough. You will also need `global.api` as well - jest runs in a node env, where `window` does not exist. It will fallback to `global`, so you need `global.api` before you tests. You can also consider defining the `get` method on your axios mock: `jest.mock('axios', () => ({ get: () => new Promise(res => res) }))` or something like that. – lmiller1990 Sep 17 '19 at 01:03

0 Answers0