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?

2
  • I'd first suggest making your $http into a proper Vue 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. Commented May 25, 2020 at 18:07
  • You will need to mock responses somehow any way. You can try Moxios. It uses existing Axios instance. Commented May 26, 2020 at 6:33

2 Answers 2

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   
        }   
    })
})
Sign up to request clarification or add additional context in comments.

Comments

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

Vue.prototype.$http = axios;

1 Comment

You need to add and explanation to this answer explaining how it solves the problem. A code only answer is not sufficient to explain why this is a good solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.