Testing Global Vue.prototype.$http method in Jest which uses axios in Vue

1.7k Views Asked by At

I have a global prototype defined in my Vue project in main.js as follows

//main.js

import axios from 'axios';
import Vue from 'vue';

Vue.prototype.$http=axios.create({
   baseURL: 'https://example.com/api/' 
});

Various vue components directly call this.$http.get or this.$http.post for performing requests. How do I test these components in Jest, apparently using mock I can mocks I can do

jest.mock('axios')

but my project is huge and changing every instance of this.$http to axios is not feasible.

How to achieve this using jest.mock?

Also how to test if a single component is doing multiple API calls on different endpoints?

2

There are 2 best solutions below

1
On
axios.defaults.baseURL = "https://example.com/api/";

Vue.prototype.$http = axios;
0
On

You can refer below code that is giving an idea that how i managed to solve this problem in my project In My project i have defined global prototype such as-

//main.js
import axios from 'axios'
Vue.prototype.$http = axios  //global prototype

And now in my components i can use 'axios' by referring this.$http. Now In my jest file have to test axios get request i.e this.$http.get('/url')

// test.spec.js

import axios from 'axios'
    
jest.mock("axios", () => ({
    get: () => Promise.resolve({ data: [{ val: 1 }] })
})); 
    
it('your test name' () => {
    const wrapper = mount('your component name', {
        mocks : {
            $http : axios   
        }   
    })
})