Home > OS >  How to mock axios in outer function?
How to mock axios in outer function?

Time:02-25

How to mock HTTP responses from axios in outer function?
I have wrapper function for GET request in axios:

export const getRequest = async (
    url: string,
    queryParams: { [key: string]: string; } = {},
    headers: { [key: string]: string; } = {}
): Promise<IhttpResponse> => {
    const config: AxiosRequestConfig = {
        url: url,
        method: 'get',
        headers: headers,
        params: new URLSearchParams(queryParams)
    };
    const response = await axios(config);
    return {status: response.status, body: response.data};
}

This wrapper function called in other function:

export const getCards = async () => {
    const url = `${backendUrl}/card`;
    const res = await getRequest(url);
    return res;
}

And I have Jest test:

import {getCards} from "@/cards_api";
import axios from "axios";
jest.mock("@/http-methods.ts");

test("test one", async () => {
    (axios.get as jest.Mock).mockImplementation(() =>
        Promise.resolve({status: 200, data: {'key': 'value'} })
    );
    const r = await getCards();
    console.log(r);
});

But it falls with error TypeError: _axios.default.get.mockImplementation is not a function

How to correctly test getCards with mocked data?

CodePudding user response:

you have to mock the axios module itself rather then your api module.

import axios from 'axios';
import { getCards } from '@/cards_api';

jest.mock('axios');

test("test one", async () => {
    axios.mockResolvedValue({ status: 200, data: { 'key': 'value' } });
    const { status } = await getCards();
    expect(status).toBe(200);
});

using the `jest-mock-axios' module might also be an option for you.

  • Related