Issue with Jest mock function failing to trigger axios instance function causing it to return undefined

I initially found a solution on this StackOverflow thread

However, I wanted to add my own helper function that generates a fresh Axios instance with the user's authentication token.

Here is what I came up with:

import axios from "axios";
const mockAxios: jest.Mocked<typeof axios> = jest.createMockFromModule("axios");

// To resolve the axios.create() undefined error!
mockAxios.create = jest.fn(() => {
  return mockAxios;
});

export const createAuthenticatedInstance = () => {
  return mockAxios.create();
};
export default mockAxios;

Why is mockAxios.create() returning undefined?

Even though the 'mockAxios' object and the create function are defined, calling create returns undefined instead of the expected new instance. I could work around this by simply returning mockAxios, but I'm curious about why it doesn't function as intended from the start. My expectation was to get an identical, new instance similar to mockAxios, but it consistently returns undefined.

Answer №1

Developing an auto-mock (within the __mocks__ directory) involves creating a mock of the module. It is important to note that any helper functions should not be included within the module itself, but rather located elsewhere in your code.

For instance:

src/axios.utils.ts (utility module exporting axios and a function)
import axios from "axios";

export const createAuthenticatedInstance = (
  ...args: Parameters<typeof axios.create>
) => {
  return axios.create(...args);
};

export default axios;
src/__mocks__/axios.ts (implementation of axios mock)
const axios: jest.Mocked<typeof import("axios").default> = jest.createMockFromModule(
  "axios"
);

axios.create.mockReturnThis();

export default axios;
src/api.ts (API implementation using axios.util)

import axios from "axios";
import { createAuthenticatedInstance } from "./axios.utils";

const client = createAuthenticatedInstance({
  baseURL: "http://example.com:80/main",
});

export default {
  makeSomeReq: () => client.get<string>("/path"),
};
src/api.spec.ts (test scenario)

import api from "./api";
import axios, { AxiosResponse } from "axios";

jest.mock("axios");

const { get } = axios as jest.Mocked<typeof import("axios").default>;

describe("api", () => {
    it("should have created an axios instance", () => {
      expect(axios.create).toHaveBeenCalledWith({
        baseURL: "http://example.com:80/main",
      });
    });
})

A working example can be found here

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

Enhance the function for handling AJAX responses

Utilizing this code allows for the handling of responses from an RSS feed. The code efficiently organizes and appends content, separating any embedded videos. While seeking feedback primarily on performance/efficiency, I am also open to other suggestions. ...

Dynamically and asynchronously loading numerous LinkedIn share buttons on a page

On my page, I have a grid of post thumbnails that are fetched via AJAX and can be filtered. When a user clicks on a thumbnail, a carousel opens with the selected post centered. In this carousel, each post has a LinkedIn share button integrated. The issue ...

Unique Input Values in Forms

I'm encountering an issue with a basic HTML form connected to a PHP script for processing values. Despite thorough testing, the form is not functioning correctly. Upon inspecting the form markup, I discovered: <form id="delete_item_3_form" action ...

Click event not triggered when transitioning to Service section in Thinkster tutorial

I've been following a tutorial on MEAN stack development () and I encountered an issue after incorporating Angular Services. For some reason, the function incrementUpvotes stopped working and I'm struggling to identify the cause. Since I'm r ...

What is the best way to manage data in a single-page application and retrieve it after the page has been refreshed?

Lately, I’ve encountered an issue with data storage in a single-page application. I’m seeking some guidance on how to effectively store data and retain it after refreshing the page within a Single Page Application. As an example, let's say I hav ...

The React-Leaflet curly braces positioned on the top left corner of the map

Is there a way to remove the curly braces and symbols near the zoom pane when the map is too far? https://i.stack.imgur.com/eGQCd.png p.s. Here is some provided code for reference: p.s. 2 - I have noticed that adding a condition like {condition1 &a ...

What is the most efficient way to update a large batch of documents in MongoDB?

I need to efficiently update a large number of documents (> 100,000). Initially, I attempted to do this on the JS level by writing scripts that fetch _ids first and then loop through them to invoke updates by _id (full docs or $set patches). However, ...

Is d3 Version pretending to be a superior version?

I have encountered an issue with my project that involved using d3 v5.5.0. After transferring it to a different computer and running npm install, the application now seems to be recognizing d3 as a higher version? A crucial part of my program relies on th ...

Discover the most helpful keyboard shortcuts for Next.js 13!

If you're working with a standard Next.js 13 app that doesn't have the experimental app directory, setting up keyboard shortcuts can be done like this: import { useCallback, useEffect } from 'react'; export default function App() { c ...

What steps can be taken to address the build problem with Angular version 13?

Encountering a problem while working with Angular 13: https://i.sstatic.net/CbAUhh6r.png Attempting to build using ng build --configuration=test, however facing errors as mentioned above. Interestingly, if I remove the reference to bootstrap.min.css in t ...

Error encountered when attempting to use the .save() method on a [mongoose_model_object] - the function contact.save is

In this scenario, the middleware 'auth' is responsible for generating a JWT and authorizing the user. I have also created a Mongoose model called Contact. However, when attempting to execute contact.save(), I encounter an exception stating that c ...

Is it possible to determine if the user is able to navigate forward in browser history?

Is there a way to check if browser history exists using JavaScript? Specifically, I want to determine if the forward button is enabled or not Any ideas on how to achieve this? ...

Overriding a generic property in Typescript allows for a more

I'm troubleshooting an issue with my code: class Base<T> {} class Test { prop: Base<any>; createProp<T>() { this.prop = new Base<T>(); } } const test = new Test(); test.createProp<{ a: number }>(); test.pr ...

How do I programmatically switch the Material-UI/DatePicker to year view in React?

I have a DatePicker component set up in my project, and it works perfectly fine. However, for my specific use case, I only need the year view to be displayed. Within the child component of the DatePicker (Calendar), there is a function called: yearSelect ...

What is the process for transforming a promise outcome into JSON format?

My current challenge involves using axios to retrieve JSON data from an external API in my backend and then passing it to the frontend. The issue arises when I attempt to log the result in the frontend, as all I see is a promise object instead of the actua ...

Is it possible to view newly added text in real-time on a separate client in Node.js without relying on socket.io?

I am in the process of creating a straightforward web application where users can input phrases. The app works fine, except for one issue - it doesn't display new additions from other users instantly. I am aware that socket.io could solve this problem ...

Can a type be created that resolves to either of two specific types?

If I have multiple functions that return either a number or a date, is there a way to define a type that encompasses both? For example, instead of: foo1(): number | Date {} foo2(): number | Date {} Can we do something like this: foo1(): NumberOrDate {} f ...

Discovering the value of a key within a JSON object by utilizing a String with JQuery

Given a JSON object, the challenge is to extract values based on user input. The input format will be similar to "data.location.type" or "data.location.items[1].address.street". Is it achievable using JQuery? { "data": { "location": { ...

Upon the initial rendering, Next.js obtains access to the query { amp: undefined }

When using Next.js 9.3, I encountered an issue where I needed to access the query on initial render and pass the result of the query to next/head in order to change the title and description of the page. The component is receiving the query from the useRo ...

How can I use jQuery to target elements other than the vertical scrollbar when

Here is how I am utilizing the mouseleave jquery event $(document).ready(function(){ $(document).mouseleave(function(event) { //perform a task }); }); Is there any method to prevent this event from triggering when a user scrolls ...