无法在Jest中模拟axios调用

bmvo0sr5  于 2023-09-28  发布在  Jest
关注(0)|答案(3)|浏览(171)

看起来mocking不适合我通过axios,因为它似乎使actual API调用(可见,因为我得到401状态代码时运行jest测试)我不知道为什么我不能mock axios.有人能指出我犯的错误吗?
index.test.ts

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

    it("Mock Fetch API for Composite Score Response", async () => {
        
        const mock = jest.spyOn(axios, "post");
        mock.mockReturnValueOnce(mockResponse);
        const response = await dateFilter(platform);
        expect(mock).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);
}
dphi5xsq

dphi5xsq1#

您正在使用axios函数,而不是axios.post()方法。所以你应该模仿axios函数而不是axios.post()jest.mock()是选择。
例如
index.ts

import axios, { AxiosRequestConfig } from 'axios';

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 token = '123';
  const url = 'http://localhost:3000/api';
  const dbName = 'test';

  const headers = {
    Accept: 'application/json',
    Authorization: `Bearer ${token}`,
    'Content-Type': 'application/json',
  };
  const config: AxiosRequestConfig = {
    method: 'post',
    url,
    headers,
    data: {
      db: dbName,
    },
  };

  return axios(config);
}

index.test.ts

import axios, { AxiosResponse } from 'axios';
import { dateFilters } from '.';

jest.mock('axios');

const mAxios = axios as jest.MockedFunction<typeof axios>;

describe('71351319', () => {
  it('Mock Fetch API for Composite Score Response', async () => {
    const mockResponse = { data: {}, status: 200, statusText: 'ok' } as AxiosResponse;
    mAxios.mockResolvedValue(mockResponse);
    const response = await dateFilters('DateFilters');
    expect(mAxios).toHaveBeenCalledTimes(1);
    expect(response).toEqual({ data: {}, status: 200, statusText: 'ok' });
  });
});

软件包版本:

"axios": "^0.21.1",
"jest": "^26.6.3",
wko9yo5t

wko9yo5t2#

尝试

import axios from 'axios';

jest.mock('axios');

在SystemUnderTest中执行import之前,您需要首先模拟模块。
https://jestjs.io/docs/mock-functions#mocking-modules

lstz6jyr

lstz6jyr3#

对于任何想嘲笑Axios的人来说,这可能会有帮助!
https://www.npmjs.com/package/jest-mock-axios
它应该大大简化模拟过程。

相关问题