You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单元测试中Mock axios.create的问题求助

解决axios.create实例的单元测试Mock问题

核心问题

用axios.create()创建的自定义请求实例,直接mock全局axios不会生效——因为这是独立于全局axios的专属实例,必须针对性mock这个实例才能拦截请求。

解决方案步骤

1. 调整API文件的导出(可选但推荐)

在api.js里把创建的axios实例也导出,方便测试时精准mock:

// api.js
import axios from 'axios';

// 导出自定义axios实例
export const apiClient = axios.create({
  baseURL: 'https://your-api-domain.com',
  timeout: 10000,
  headers: { 'Content-Type': 'application/json' }
});

// 业务请求方法
export const fetchUser = (userId) => {
  return apiClient.get(`/users/${userId}`);
};

2. 两种Mock实现方式

方式一:直接Mock导出的apiClient

适合已经导出实例的场景,直接mock实例的请求方法:

// api.test.js
import { fetchUser, apiClient } from './api';

// 局部mock api模块,保留其他导出,只替换apiClient
jest.mock('./api', () => ({
  ...jest.requireActual('./api'),
  apiClient: { get: jest.fn() }
}));

test('fetchUser 能正确调用API并返回数据', async () => {
  // 模拟接口返回
  const mockUser = { id: 1, name: 'Rizal' };
  apiClient.get.mockResolvedValue({ data: mockUser });

  const result = await fetchUser(1);
  
  // 验证调用参数
  expect(apiClient.get).toHaveBeenCalledWith('/users/1');
  // 验证返回结果
  expect(result.data).toEqual(mockUser);
});

方式二:Mock axios的create方法

如果不想导出apiClient,可以拦截axios.create的调用,让它返回一个mock实例:

// api.test.js
import axios from 'axios';
import { fetchUser } from './api';

// 全局mock axios模块
jest.mock('axios');
// 定义mock实例
const mockApiInstance = { get: jest.fn() };
// 让create返回这个mock实例
axios.create.mockReturnValue(mockApiInstance);

test('fetchUser 能正确触发请求', async () => {
  const mockUser = { id: 1, name: 'Rizal' };
  mockApiInstance.get.mockResolvedValue({ data: mockUser });

  const result = await fetchUser(1);
  
  // 可选:验证create的配置是否符合预期
  expect(axios.create).toHaveBeenCalledWith({
    baseURL: 'https://your-api-domain.com',
    timeout: 10000,
    headers: { 'Content-Type': 'application/json' }
  });
  // 验证请求方法的调用
  expect(mockApiInstance.get).toHaveBeenCalledWith('/users/1');
  expect(result.data).toEqual(mockUser);
});

3. 常见报错排查

  • Cannot read property 'get' of undefined:检查是否给axios.create的mock返回了包含对应请求方法(get/post等)的对象,确保mock实例不是undefined。
  • Mock不生效:确认jest.mock放在测试文件最顶部,没有被其他代码覆盖;同时检查API文件里的请求确实是用axios.create返回的实例发起的,而非全局axios。

内容的提问来源于stack exchange,提问作者Rizal Sidik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 21:57:22