Home > Enterprise >  Jest axios mock returning undefined in expected response
Jest axios mock returning undefined in expected response

Time:03-09

It seems mocking is not working for me via axios as it does seem to implement mock function. I am not sure why am I not able to mock axios.Can anyone point out the mistake I am making?I have ben trying this for the past 3 days.

index.test.ts

import axios from "axios"; // Imported from node module jest.mock("axios");

describe("compositeScore()", () => {

    it("Mock Fetch API for Composite Score Response", async () => {
        
        axios.post = jest.fn().mockResolvedValue(mockResponse);
        const response = await dateFilter(platform);
        expect(axios.post).toHaveBeenCalledTimes(1);
        expect(response).toEqual(mockFetchCompositeScoreResponse);
    });
});

index.ts

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


export async function fetchWrapper(
    queryName: string,
    platform: string,
    queryParams?: {}
) {
   
    const headers = {
        Accept: "application/json",
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
     
    };
    const config: AxiosRequestConfig = {
        method: "post",
        url,
        headers,
        data: {
            db: dbName,
            csl: queryParams
                ? substituteQueryParameters(queries[queryName], queryParams)
                : queries[queryName],
        },
    };

    return axios(config);
}

I am getting error as Expected number of calls: 1 Received number of calls: 0

and also Received : undefined and expected stores the mockResponse.

CodePudding user response:

The HTTP request made by axios function, NOT axios.post method.

E.g.

index.ts:

import axios, { AxiosRequestConfig } from 'axios';

const token = '123';
const url = 'http://localhost:8080/api';
const dbName = 'arena';

export const dateFilters = async (platform) => {
  return fetchWrapper(platform.toLowerCase().concat('DateFilters'), platform, {});
};

export async function fetchWrapper(queryName: string, platform: string, queryParams?: {}) {
  const headers = {
    Accept: 'application/json',
    Authorization: `Bearer ${token}`,
    'Content-Type': 'application/json',
  };
  const config: AxiosRequestConfig = { method: 'post', url, headers, data: { db: dbName, csl: queryParams } };
  return axios(config);
}

index.test.ts:

import { dateFilters } from './';
import axios from 'axios';

jest.mock('axios');
const mAxios = axios as jest.MockedFunction<typeof axios>;

describe('71387289', () => {
  test('should pass', async () => {
    const mockResponse = { data: 'fake data', status: 200, statusText: 'ok', headers: {}, config: {} };
    mAxios.mockResolvedValueOnce(mockResponse);
    const platform = 'awesome';
    const actual = await dateFilters(platform);
    expect(axios).toHaveBeenCalledTimes(1);
    expect(actual).toEqual(mockResponse);
  });
});

Test result:

 PASS  stackoverflow/71387289/index.test.ts (7.78 s)
  71387289
    ✓ should pass (4 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.ts |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        7.906 s, estimated 10 s
  • Related