Having trouble simulating a custom Axios Class in JavaScript/TypeScript

Here are the function snippets that I need to test using jest, but they require mocking axios. My attempt at doing this is shown below:

// TODO - mock axios class instance for skipped Test suites
describe("dateFilters()", () => {
    beforeEach(() => {
        jest.resetAllMocks();
    });
    it("Mock Fetch API for Date Options Response", async () => {
        const mockFn = jest.fn();
        setUpMockResponse(mockFn, mockFetchDateOptionsResponse);
        const response = await dateFilters(Workload.WIN32);
        expect(mockFn).toHaveBeenCalledTimes(1);

        expect(response?.data).toEqual(mockFetchDateOptionsResponse);
    });
});

I am encountering the following error: Error: "Exceeded timeout of 5000 ms for a test. Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test." It appears that the axios mocking is not working as expected.

Below are all the necessary function definitions:

export const dateFilters = async (platform) => {
    const dates = await getKustoResponse({
        queryName: platform.toLowerCase().concat("DateFilters"),
        platform,
        queryParams: {},
    });
    return dates;
};


export const getKustoResponse = async ({
    queryName,
    platform,
    queryParams,
    cluster = "Default",
}: QueryDetail) => {
    const dbName = getClusterValue({ platform, cluster, key: "db" });
    const url = getClusterValue({ platform, cluster, key: "kustoUrl" });
    const postBody = {
        db: dbName,
        csl: queryParams
            ? substituteQueryParameters(queries[queryName], queryParams)
            : queries[queryName],
    };

    const apiClient = ApiClient.getInstance();
    const response = await apiClient.post(url, postBody, {
        headers: {
            ...kustoApiRequestDefaultConfiguration.headers,
            "x-ms-kql-queryName": queryName,
        },
        timeout: kustoApiRequestDefaultConfiguration.timeout,
    });
    return response;
};

import Axios, { AxiosInstance } from "axios";
import axiosRetry from "axios-retry";
export class ApiClient {
    private static instance: AxiosInstance;

    public static getInstance = (): AxiosInstance => {
        if (!ApiClient.instance) {
            ApiClient.createInstance();
        }

        return ApiClient.instance;
    };

    private constructor() {
        ApiClient.getInstance();
    }

    protected static createInstance = () => {
        const responseType = "json";
        const client = Axios.create({
            responseType,
        });
        axiosRetry(client, apiRetryConfiguration);
        client.interceptors.request.use(requestInterceptor);
        client.interceptors.response.use(responseInterceptor, errorInterceptor);

        ApiClient.instance = client;
    };
}


export const requestInterceptor = async (
    request: AxiosRequestConfig
): Promise<AxiosRequestConfig> => {
    const token = await getKustoToken();
    request.headers = { ...request.headers, Authorization: `Bearer ${token}` };
    return request;
};

Answer №1

You won't find a fetch call in the code you provided. Perhaps it resides in the apiClient? If so, consider implementing this:

jest.spyOn(apiClient, 'post').mockImplementation();
expect(apiClient.post).toHaveBeenCalled();

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

A step-by-step guide on uploading a CSV file in Angular 13 and troubleshooting the error with the application name "my

I am currently learning angular. I've generated a csv file for uploading using the code above, but when I try to display it, the screen remains blank with no content shown. The page is empty and nothing is displaying Could it be that it's not ...

trouble encountered when attempting to integrate typeahead functionality in AngularJS using jQuery

Greetings! I am brand new to using AngularJS and currently exploring the implementation of typeahead functionality. I decided to utilize an existing library by including the following script: <script src="lib/xyz/typeahead.bundle.js"></script> ...

The md-select search filter currently functions according to the ng-value, but it is important for it to also

I am using a md select search filter with multiple options available. For instance: id: 133, label:'Route1' id: 144, label:'Route2' id: 155, label:'Route3' id: 166, label:'Route4' If I input '1' ...

Do these two JavaScript statements behave the same under the principles of functional programming in a React environment?

Is there a rule in functional programming that states these two approaches are equivalent? When working on a React application, I initially passed a function as an attribute using the second version where the first parameter is also passed. Out of curiosi ...

Running on Node.js, the Promise is activated, yet there remains an issue with the function

I've encountered a strange issue that I can't seem to diagnose. It's showing a TypeError: My code is returning 'function is undefined', which causes the API call to fail. But oddly enough, when I check the logs and breakpoints, it ...

Adjusting the height of one element based on the height of another element in multiple cases using jQuery

I am currently using jQuery to retrieve the height of one div and apply that value as a CSS property to another. Let's take a look at a sample layout: <div class="row"> <div class="column image"> <img src="image.jpg" /> < ...

Using Rails AJAX to dynamically load partials without the need to submit

Imagine creating a dynamic page layout with two interactive columns: | Design Your Pizza Form | Suggested Pizzas | As you customize your pizza using the form in the left column, the right column will start suggesting various types of pizzas based on your ...

When utilizing React, I generated an HTML page with a distinct .js file, however, encountered two unexpected errors

Update : Gratitude to everyone who has helped me in tackling this issue. One user suggested using a web server, but my intention was to find a solution using just a single HTML and JS file. Even though I tried following the steps from a similar question o ...

Adding curly braces around values when using Angular's form group patchValue method

I have been working on a dynamic form using form builder in order to update form data dynamically. I have created a function that iterates through keys in an object and patches the form values based on matching key names. While this approach works for most ...

Utilizing jQuery to pinpoint the exact position within a Flexbox container

I have a unique setup with multiple boxes arranged using Flexbox as the container and list tags as individual boxes inside. These boxes are responsive and change position as the width is resized. My goal is to use jQuery to detect which boxes are touching ...

Creating elegant Select Dropdown Box in AngularJS without relying on images

I am currently working on an angular page and have implemented a dropdown with ng-Options to fetch and set values successfully. However, I am now looking to enhance the appearance of this dropdown. After exploring options like ui-select, I realized that be ...

What are some ways to get Angular2 up and running in a newly created distribution directory?

Trying to setup my own Angular2+Typescript (+SystemJS+Gulp4) starter project has hit a roadblock for me. I encountered issues when transitioning from compiling TypeScript in the same folder as JavaScript with access to the node_modules folder, to organizin ...

Retrieving information selectively using useSWRImmutable

Having issues fetching data using useSWRImmutable. The problem arises when attempting to display the fetched data inside the UserRow component. Even though I can successfully print the data outside of the UserRow component, any console.log() statements wi ...

Create duplicates of both the array and its individual elements by value

I'm having trouble figuring out how to properly copy an array along with all its elements. In my model, I have a name and options, both of which are strings. This is what I currently have: const myArrayToDuplicate = [myModel, myModel, myModel] My ...

Prisma Date and Time Formatting Challenge

Exploring Nest Js and prisma led me to the need to store DateTime data in my database based on my timezone preferences. joining DateTime @db.Timestamptz(5) ` I found that using @db.Timestamptz resolved my timezone storage issue, but upon retriev ...

Utilizing imported components to set state in React

In my project, I created a functional component named Age and imported it into another functional component called Signup. This was done in order to dynamically display different divs on a single page based on the authentication status of the user. By sett ...

Learn how to render a dynamic checkbox that is connected with AJAX and PHP for seamless functionality

I need to showcase a dynamic checkbox that can be bound using ajax and php. Here is my code: <?php include 'dbconnect.php'; $result = mysqli_query($link, "SELECT * FROM city where district_id='$dist' "); while($city_row=mysqli_fe ...

How can you direct a user to a specific page only when certain conditions are met?

Currently using React in my single page application. I have a good grasp on how Routes function and how to create a PrivateRoute. The issue arises when I need to verify the user's identity before granting access to a PrivateRoute. My attempt at imple ...

Leveraging redux within your NEXT.JS project

While working on my Next.js application, I have integrated Redux and Redux Saga. I am trying to incorporate server-side rendering for making HTTP requests: export const getStaticProps = wrapper.getStaticProps(async ({ store }) => { store.dispatch(g ...

Press the button to reveal the hidden Side Menu as it gracefully slides out

I'm interested in creating a navigation menu similar to the one on m.facebook.com, but with a unique animated slide-out effect from the left side of the website. Here's the flow I have in mind: Click a button > (Menu is hidden by default) Men ...