The axios test in jest successfully passes despite encountering a Network Error advisory

Within my utils class, I have implemented axios for handling basic REST calls. While running a jest unit test, the tests pass successfully but an advisory error pops up:

C:/home/dev/node_modules/axios/lib/core/createError.js:16
var error = new Error(message);

Error: Network Error
    at createErrorC:/home/dev/node_modules/axios/lib/core/createError.js:16
    config: {
        // ....
        header: { Accept: 'application/json, text/plain, */*' },
        withCredentials: true,
        responseType: 'json',
        method: 'get',
        url: 'http://mock.rest.server.com:1234/rest/user/data/adam',
        data: undefined
    },
    request: XMLHttpRequest {},
    response: undefined,
    isAxiosError: true,
    toJSON: [Function: toJSON]

utility.ts

import axios, { AxiosResponse } from 'axios'

axios.defaults.withCredentials = true;
axios.defaults.responseType = 'json';

export class UserUtils {

    public getUserConfig(userName: string): Promise<AxiosResponse> {
        if(!userName) {
            return;
        }

        return axios.get('http://mock.rest.server.com:1234/rest/user/data/' + userName);
    }

}

utility.test.ts

import axios from 'axios';
import { UserUtils } from '../../utility';

describe("Utility test", () => {
    const utils = new UserUtils();

    jest.mock('axios', () => {
        return {
          post: jest.fn(),
          get: jest.fn()
        }
    }

  // clear all mocks
    beforEach(() => {
        jest.clearAllMocks();
        jest.restoreAllMocks();
    });

    test("get user data",() => {
        jest.spyOn(axios, 'get');

        utils.getUserConfig('adam')
          .then(repsonse => {
            expect(axios.get).toHaveBeenCalledWith('http://mock.rest.server.com:1234/rest/user/data/adam');
        });
     });
});

Answer №1

If you're looking for some assistance, check out this thread:

Personally, I find jest manual mocks (docs) to be quite helpful.

In one of my projects, I've implemented the following:

// src/__mocks__/axios.ts
import axios from 'axios';

const mockAxios = jest.genMockFromModule<typeof axios>('axios');

// To resolve the axios.create() undefined error, use this key!
mockAxios.create = jest.fn(() => mockAxios);

// eslint-disable-next-line import/no-default-export
export default mockAxios;
// src/.../test.ts
import mockAxios from 'axios';

const mockedPost = mockAxios.post as jest.Mock;

beforeEach(() => {
  jest.clearAllMocks();
});

...

expect(mockedPost).toHaveBeenCalledWith(route, payload);

I hope this information proves useful to you!

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

Is there a way I can ensure the values are loaded when the page loads, rather than displaying NaN?

I've recently created a car rental calculator for a client, and it's almost complete. Everything is working smoothly, from the calculations to the conditions. However, I'm facing an issue where the price isn't calculated on page load. I ...

How to eliminate unnecessary space when the expansion panel is opened in material-ui

Is there a way to eliminate the additional space that appears when clicking on the second accordion in material UI? When I open the second accordion, it shifts downward, leaving a gap between it and the first accordion. Any suggestions on how to remove thi ...

Determining the readiness of a node.js express server for use

Is there a way to automatically start a browser on the same machine as soon as a Node Express server is up and running? I'm looking for a method to check if the server is ready without having to wait an excessive amount of time. It would be ideal to h ...

Implementing image max-width and maintaining aspect ratios for responsiveness

Within the code snippet below and utilizing Bootstrap, a grid layout is defined with several .block components, each comprising an image and a title. The images are designed to be larger than the column size so that they can expand to full width for respon ...

Create a fresh instance of an object in node.js by utilizing the require/new method

I am encountering a beginner problem with node.js where I cannot seem to create objects using the 'new' operator in the index.js file. My goal is to define a simple Person object within a Person.js file, located in the same directory as my index ...

Unable to fix the MongoDB/Express issue

I am encountering an issue with my React, Redux, and MongoDB application. I have a users collection where each user has a favorites array. I want to update this array with a patch request whenever a user adds a new favorite element. However, I keep receivi ...

Animate the expansion and shrinkage of a div instantly using jQuery

I am trying to create an animation effect using jQuery animate on a div element where it starts large and then becomes smaller. Here is the code I have written: $(this).animate({ opacity: 0, top: "-=100", width: "38px", height: "32px" }, 1 ...

Is there a method to enclose a Grafana row with a border?

I recently created a Grafana dashboard using JavaScript and I realized that adding a border around each row would enhance readability. Here is how the current view looks like: https://i.stack.imgur.com/itKYR.png However, it can be difficult to differenti ...

Achieving asynchronous results in the parent function with TypeScript: a guide

The code structure provided is as follows: import {socket} from './socket'; class A{ Execute(...args[]){ //logic with Promises SomeAsyncMethod1().then(fulfilled1); function fulfilled1(){ SomeAsyncMethod2(args).then(fulfilled2); ...

Guide to designing a system for transferring information from a server to express routes without relying on a database?

Currently, my node.js application executes a fetch call upon startup to retrieve data from an external API (not owned by me) regarding devices I possess. Once this data is obtained, I initialize an express server located in a separate file 'server.js& ...

Scripting issues detected in Safari and Microsoft Edge browsers

I recently finished developing an AngularJs Application that works flawlessly on Google Chrome and Mozilla Firefox. However, upon testing it on Safari and IE-11, I encountered errors in the console. One particular piece of code that causes issues is used ...

What is the best way to arrange items by utilizing the Array index in JavaScript?

Currently, I am attempting to make the elements within this angular component cascade upon loading. The goal is to have them appear in a specific layout as shown in the accompanying image. I'm seeking guidance on how to write a function in the TypeSc ...

Developed a query, seeking information for populating a dropdown menu

I am currently in the process of editing a webpage that utilizes both PHP and HTML. Essentially, I have a dynamic list of items being generated where the number of values can vary based on the row length. Next to each item in the list, there is a "delete ...

Loading complex models with Three.js

Whenever I attempt to load a significantly large file utilizing the appropriate loaders provided by the library, the tab in which my website is running crashes. Despite trying to implement the Worker class, it doesn't seem to resolve the issue. Here i ...

The process of retrieving request data from axios.get and storing it in the Redux store

Recently delving into Redux, I'm curious about how to retrieve request data from a GET method. Upon mounting the component, you can use axios to send a GET request to '/api/v3/products', passing in parameters like pageNumber and pageSize. ...

Error encountered with Vuetify stepper simple component wrapper and v-on="$listeners" attribute

I'm working on developing a custom wrapper for the Vuetify Stepper component with the intention of applying some personalized CSS styles to it. My aim is to transmit all the $attrs, $listeners, and $slots. I do not wish to alter any functionality or ...

Utilizing CSS and JQUERY for Styling Border radius

Is there a way in jQuery to select specific parts and apply a "border radius"? I've been struggling to use a jQuery selector to achieve this. Is there another method using CSS? I don't want to manually add a "CLASS" to the HTML code to solve th ...

Is there a way to have the collapsible content automatically expanded upon loading?

I came across a tutorial on w3school (https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_collapsible_symbol), which demonstrates collapsible content hidden by default. The code snippet from the link is provided below. Can someone assist me in cha ...

Angular dynamic multi-select dropdown box

Exploring Choices In my quest to enhance user experience, I am working on creating a dynamic system involving two selection (drop-down) boxes. The idea is for the options in the second box to change based on the selection made in the first box. For insta ...

Creating a Dojo HTML template involves incorporating repetitive sections of HTML code within the template structure

I am working with a custom Dojo widget that is based on a template and has an HTML template stored in a separate .html file. Here is the Dojo Widget code snippet: define("dojow/SomeWidgetName",[ "dojo/_base/declare", "dijit/_WidgetBase", "dijit/_Templat ...