1

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?

Anand Thakkar
  • 43
  • 1
  • 5
  • I'd first suggest making your `$http` into a proper [Vue Plugin](https://vuejs.org/v2/guide/plugins.html#Writing-a-Plugin). That will enable mocking the plugin more easily than the current setup, and the interface will not change for your components that currently expect `this.$http` to exist. – Ross Allen May 25 '20 at 18:07
  • You will need to mock responses somehow any way. You can try Moxios. It uses existing Axios instance. – Estus Flask May 26 '20 at 06:33

2 Answers2

1

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   
        }   
    })
})
Anil kumar
  • 11
  • 2
0
axios.defaults.baseURL = "https://example.com/api/";

Vue.prototype.$http = axios;