An effective way to simulate an axios call within a method

I'm attempting to simulate an axios call inside a vuejs method. Can this be achieved?

Below is my vue component (SomeObj):

 methods:{
        callAxiosMethod() { 
          const callApi= axios.create();
          callApi.defaults.timeout = 10000;
          callApi.get(mockedUrl)
          .then(response => {
             console.log('response is ' + response);
          })
          .catch(e => {});
        }
    }

And here is my spec.js

let mockData = {};
beforeEach(() => {
        jest.spyOn(axios, 'get').mockReturnValue(Promise.resolve(mockData));
    });

    let wrapper = shallowMount(SomeObj, {
        stubs: [], localVue, mocks: {
            mockUrl: mockUrl,
            $route: {
                params: { testId: "123" }
            }
        }
    });
    it('is a Vue instance', () => {
        expect(wrapper.isVueInstance()).toBeTruthy();
        axios.get.mockResolvedValue(mockData);
        wrapper.vm.callAxiosMethod();
    })

When reviewing the coverage report, it indicates that the callApi is not covered. Any suggestions on how I can properly mock the axios call within the function?

Answer №1

Your code utilizes axios.create, hence you will need to mock the function in order to return a simulated callApi object.

For further clarity, see the following operational example:

app.js

import * as axios from 'axios';

const mockedUrl = 'http://mock-url';

export const callAxiosMethod = () => {
  const callApi = axios.create();
  callApi.defaults.timeout = 10000;
  return callApi.get(mockedUrl);  // <= ensuring Promise is returned for subsequent awaiting
}

app.test.js

import { callAxiosMethod } from './app';

jest.mock('axios', () => ({
  create: jest.fn().mockReturnValue({
    defaults: {},
    get: jest.fn().mockResolvedValue('mocked data')
  })
}));

test('callAxiosMethod', async () => {  // <= defining the asynchronous test function
  const response = await callAxiosMethod();  // <= await the Promise resolution
  expect(response).toBe('mocked data');  // Test Passed!
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are some methods to manage the timing of sending socket connection requests from the client to the backend server?

Currently using vue-socket.io, my frontend initiates a Socket.io connection request to the backend when the app is first being built or whenever the page is refreshed. This poses an issue for me because the page is initially constructed on the landing page ...

Incorporating Vue Component According to URL Parameters Dynamically

Is there a way to dynamically import a vue component based on a path provided in the URL parameters? For example, if <host>/<path> is entered into the browser, I would like to load a vue component located at <path>.vue. In my routes.js f ...

Just initiate an API request when the data in the Vuex store is outdated or missing

Currently, I am utilizing Vuex for state management within my VueJS 2 application. Within the mounted property of a specific component, I trigger an action... mounted: function () { this.$store.dispatch({ type: 'LOAD_LOCATION', id: thi ...

Unsupported Media Type: 415 Error during MultipartFile Upload

When trying to upload a file using spring boot and vue, I encountered an error '415 : Unsupported MediaType'. This is the snippet of my spring boot controller. @PostMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}, produces = {MediaType. ...

Vue - Troubleshooting why components are not re-rendering after data updates with a method

Check out this simple vue component I created: <template> <div class="incrementor"> <p v-text="counter"></p> <button v-on:click="increment()">Increment</button> </div> </template> <script lan ...

Toggle button with v-bind in Nativescript Vue

Hey there, I'm just starting out with nativescript vue and I have a question regarding a simple "toggle" feature that I'm trying to implement. Essentially, when a button is pressed, I want the background color to change. <template> < ...

Utilize Vue CLI 3 to enable popups in arcgis API JS

I've been attempting to enable popups from the ArcGIS API JS to show using the Vue-CLI 3 framework. Unfortunately, even with a simple sample code, I'm unable to make it function properly. Below is the code initially written in vanilla JS: <!DO ...

Is there a way to eliminate the legend symbol for just one legend in Highcharts?

Looking to customize a legend in Highcharts but facing limitations due to Plot Lines and Bands not having legends. To work around this, I have added an empty series that acts as a toggle for showing/hiding plot lines. Since my plot lines are vertical, I im ...

Guide on accessing a nested array within a JSON object using JavaScript

I'm currently faced with a json object that contains nested arrays and names with spaces like Account ID. My goal is to only display the Account ID's within my Vue.js application. While I can access the entire response.data json object, I'm ...

The performance problem of calling a method in a Vue 2 v-for loop

Can someone help me understand why my code is calling someFunction() four times instead of just once? This is the structure: <div id="app"> <div v-for="item in items" :key="item.id"> <input v-model=" ...

I'm having trouble launching the Vue UI after successfully installing the Vue CLI - any ideas why?

After installing the following versions: node 8.11.2 npm 6.3.0 I proceeded to install the Vue CLI (@vue/[email protected]): npm i -g @vue/cli However, upon running the command below: vue ui An error message was displayed as follows: Error: Cann ...

What is the best way to set the v-model property to an object that is constantly changing

I'm in the process of creating a dynamic form that allows users to add additional fields by simply clicking on a button labeled "adicionar condição." The concept is similar to what can be seen in the screenshot below: https://i.stack.imgur.com/Mpmr6 ...

In a Vue project, classes are not being applied by TailwindCSS

Two Vue 3 projects were developed using Vite - a Design System and the main project that will make use of the Design System. Each project has its own repository. The design system is imported into the main project by referencing it in the package.json as ...

Add the scss file to the vuejs component npm package only if certain conditions specified in the project are met

Creating css/scss themes for my Vue Components Npm package has been a focus of mine lately. This particular package is local and currently being tested using npm link. Both the Package and Project are utilizing webpack. index.js of Package import "./src ...

What is the process for creating a unit test case for a button's onClick event with Jest?

In my attempt to unit test the onClick event of a button in a component, I encountered some challenges. Specifically, I am unsure how to properly test the onClick event when it triggers a function like Add(value). App.js function App(){ const[value,set ...

How can you identify when a Vuetify radio button is re-selected?

Currently, I am developing a wizard that involves triggering navigation when a radio button is selected. Users should also be able to go back and change their previous choices. However, one issue I have encountered is the difficulty in detecting a re-selec ...

Server experienced 405 error during production usage, not during local testing

Upon testing my application on the live server, I encountered a 405 error when attempting to delete records: Request URL: http://ijsbrekerz.xxx/api/cards/10 Request Method: DELETE Status Code: 405 Method Not Allowed Remote Address: 185.xx.xx.xx:80 Referrer ...

Switching the Vue image on Routerlink's isExactActive feature

Is there a way to display different images based on whether a link is active or not? <router-link to="/"> <img src=" :active = isExactActive ? pic_active.png : pic_inactive.png}}" /> //Something along these lines ...

What is the reason for a JavaScript comment being inserted into the DOM instead of the Vue component?

Currently, I am experimenting with BootstrapVue and attempting to dynamically generate components after the site has been rendered. The goal is to utilize asynchronous data for the generation process at a later stage using Vue, and then adding them to the ...

Calling components may result in a race condition

I have integrated 2 components into my "App" that work together seamlessly. The first component is responsible for resolving the external IP address to a geographical location by making 2 axios.get calls and then passing them back to App.vue using emit. F ...