如何在外部函数中模拟 axios?

How to mock axios in outer function?

如何在外部函数中模拟来自 axiosHTTP 响应?
我在 axios:

中有 GET 请求的包装函数
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};
}

此包装函数在其他函数中调用:

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

我有 Jest 测试:

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);
});

但是报错TypeError: _axios.default.get.mockImplementation is not a function

如何使用模拟数据正确测试 getCards

你必须模拟 axios 模块本身而不是你的 api 模块。

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);
});

使用“jest-mock-axios”module 可能也是您的一个选择。