When testing axios in Vue with Jest mock, the response is returning as undefined

I've tried numerous solutions to similar issues, but none of them seem to work. (the comments are my attempted fixes, separated by blank lines. I've been stuck on this problem for nearly a week, focusing on improving the coverage by testing the .then part of the Axios request. I just can't seem to pinpoint where things are going wrong.

code snippet

__ mocks __/axios.js:

export default {
    get: jest.fn(() => Promise.resolve({ data: {} })),
    post: jest.fn(() => Promise.resolve())
}

getInfo method that needs testing:

getInfo () {
      axios.get('/')
        .then((response) => {
          this.form.sid = response.data.data.basic_info.username
          this.form.name = response.data.data.basic_info.name
          this.form.tel = response.data.data.basic_info.mobile_number
          this.form.email = response.data.data.basic_info.email
          return response.data
        }).catch(function (error) {
          console.log(error)
        })
    }

test code snippet:

import { shallowMount } from '@vue/test-utils'
import InfoForm from '@/components/InfoForm'

//attempt 1
import axios from 'axios';
jest.mock('axios')

//...
//describe portion is omitted here

    it('tests the getInfo method', async () => {
        const mockAxiosGet = jest.spyOn(axios, "get")
        mockAxiosGet.mockResolvedValue(() =>
            Promise.resolve({
                data: {
                    basic_info: {
                        username: 'aName',
                        name: 'aNAME',
                        mobile_number: '12222222222',
                        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f6979b979f9ab6939bd895999b">[email protected]</a>'
                    }
                }
            })
    )

        const response = await wrapper.vm.getInfo()
        expect(response).toBeDefined() // error message below
    })

Error Message:

Ensure that a variable is not undefined.

InfoForm.vue test > test method: getInfo
-----
Error: expect(received).toBeDefined()

Received: undefined Jest

Any assistance would be greatly appreciated!

Answer №1

fetchData is a common mistake when working with asynchronous code. Promises should not be enclosed within a function and instead should be returned from the function in order to enable chaining them later on. This approach will make it easier for functions to be composed or tested in the future, even if it may not be necessary at present. The only reason one might not follow this practice is if a specific callback signature is required that does not support returning a promise object.

The correct way to implement this is:

fetchData () {
   return fetch('api/data')
   ...

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

Each occurrence of a variable update will result in the storing of its value within an

I'm struggling to include a variable in an array without it changing. Every time I try to push the variable to the array, it seems to alter. i = 10; function addToArray() { let b = []; b.push(i); console.log(b); } addToArray(); The variable n ...

Modify the website address and show the dynamic content using AJAX

$(function(){ $("a[rel='tab']").click(function(e){ //capture the URL of the link clicked pageurl = $(this).attr('href'); $("#Content").fadeOut(800); setTimeout(function(){ $.ajax({url:pageurl+'?rel=tab&apo ...

Custom chunk import splitting with Vue CLI and Webpack: A guide

Uncertain if the title is effective, but here's my attempt to clarify: I have a total of 4 pages: a1.vue, a2.vue, b1.vue, and b2.vue.<br> In my <code>router/index.js: import a1 from '@/components/a1'; import a2 from '@/ ...

Creating evenly spaced PHP-generated divs without utilizing flexbox

My goal is to display images randomly from my image file using PHP, which is working fine. However, I am facing an issue with spacing the images evenly to fill the width of my site. This is how it currently appears: https://i.stack.imgur.com/AzKTK.png I ...

Display drop-down item when selected for the first time and hide it when selected for the same item for the second time

Is there a way to display form input when "C" is selected and hide it when "A", "B", or "D" are selected? If "C" is selected again after initially showing the form input, should it be hidden? For example, if "C" is selected for the first time, the form inp ...

Guidance on creating cookies using Angular

I have been attempting to set a cookie using the method outlined in this post. However, despite following the instructions, I seem to be missing a crucial step as the console only displays "undefined". Below is the complete HTML content that I am using: & ...

The jQuery Deferred feature on Ajax is failing to properly pass the array in the data option as an array, instead converting

I am facing an issue in my application where I want to use jQuery deferred to handle Ajax success and error uniformly from a central location. It works perfectly fine when I pass strings in the data option, but when I try to pass an array, it gets sent as ...

Retrieve JSON data using AngularJS

Can someone guide me on how to make a GET request to my API endpoint and handle the JSON response in my code? Sample Controller.js Code: oknok.controller('listagemController', function ($scope, $http) { $scope.init = function () { ...

Combining strings in a JavaScript object

Can someone help me with concatenating strings within an object in JavaScript? I am parsing through an XML file to create a list of links in HTML. Each time I iterate through the loop, I want to add a new <li> element containing the link. How can I ...

The onClick event handler is triggered on page load instead of waiting for a click

Recently delving into React, I encountered an issue while attempting to call a function set as a prop. Take a look at my component below: class SamplesInnerLrg extends Component { playSampleAction(sample,sampleId) { console.log(sample); } ...

What is the best way to create a carousel component with this particular design?

`I want to enhance my static HTML CSS website by incorporating a slider feature using JavaScript. Looking for guidance on the best approach. Here is the layout. I've attempted various tutorials but they weren't compatible with my layout or reli ...

What could be the reason behind needing to refresh my Express endpoint in order to access req.headers.cookies from the frontend?

I've encountered an issue where I must refresh my express endpoint in order to properly access req.headers.cookie. Without refreshing the endpoint, console.log(req.headers.cookie) returns undefined instead of the expected value. I have attached some i ...

The click event will not be triggered if the element is removed by my blur event

My dropdown list is dynamic, with clickable items that trigger actions when clicked. Upon focus, the list displays suggested items When blurred, the list clears its contents The issue arises when blur/focusout events are triggered, causing my element to ...

Angular Material selectionChanged function is providing the previous step instead of the current step

I need to make a page with two columns: one for a vertical stepper and the other for step descriptions. I want the description to update based on the current step selected. However, I am running into an issue where the selectedIndex shows the previously ch ...

Output the JSON array in JavaScript

I've been struggling to display my JSON response from PHP in the browser console using JavaScript. Despite researching on various websites, I still can't seem to figure it out. Here's a sample of the JSON data: {"0":{"codigo_intervencao":" ...

How to remove a variable definition in Typescript

Is there a way to reset a variable to undefined after assigning it a value? To check, I am using the Underscore function _.isUndefined(). I have attempted both myVariable = undefined and delete myVariable without success. ...

Fixing React lazy components for testing with React Router

When running Jest tests on React lazy components, I encountered an issue where the lazy components did not resolve to React components and instead remained as lazy objects. This led to the error message Invariant Violation: Element type is invalid: expecte ...

Ways to showcase flair in PHP code such as this

I currently have this code snippet: <h2 class="index-single">Tech Categories</h2><?php $args2 = array( 'cat' => 11 , 'posts_per_page' => 9 , 'paged' => $paged ); $the_query2 = new WP_Query( $args2 ); ...

Update the text based on the selected input

Currently, I am working on creating an RFQ interface for an OTC desk. My goal is to retrieve the price for a specific cryptocurrency that is chosen using the <v-select> element. To achieve this, I am attempting to send a GET request to the price endp ...

Unable to update due to outdated response call causing issues

I am currently in the process of updating outdated response calls and have encountered a peculiar issue where the response is not being properly ended. Typically, I would use : res.send(200, {message: 'Location Updated'}); However, this method ...