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

如何Mock OpenAPI Generator生成的API接口返回值?

解决axios Mock失效:实例不一致问题

核心原因

你猜的没错——测试中mock的axios和生成的API代码里使用的axios不是同一个实例。大概率是因为本地安装的API代码文件夹里自带了独立的axios依赖,或者API代码内部创建了自定义的axios实例,导致jest.mock('axios')只mock了项目根目录的axios,没覆盖到API里的那个。

解决方案

方案1:Mock API代码中实际导入的axios路径

如果API代码是从自身依赖目录导入axios,直接mock这个具体路径:

// 假设API代码的路径是 ./src/api-generated
jest.mock('./src/api-generated/node_modules/axios', () => {
  const mockAxios = jest.createMockFromModule('axios');
  mockAxios.request = jest.fn();
  return mockAxios;
});

然后在测试中导入这个mock的axios实例,用你的setupAxiosMock配置:

import axios from './src/api-generated/node_modules/axios';
import setupAxiosMock from './setupAxiosMock';
import { getCaseSuccess, CASE_ID_SUCCESS } from './stubs';

const stubs = [
  {
    method: 'GET',
    path: `/cases/${CASE_ID_SUCCESS}`,
    response: getCaseSuccess,
    isSuccessResponse: true,
  }
];

beforeEach(() => {
  jest.clearAllMocks();
  setupAxiosMock(axios, stubs);
});

方案2:直接Mock生成的API模块(更推荐)

不用纠结axios实例,直接Mock整个API模块的方法,简单可靠:

// 假设生成的API模块路径是 ./src/api-generated/cases.js
jest.mock('./src/api-generated/cases', () => ({
  getCase: jest.fn(() => Promise.resolve(getCaseSuccess))
}));

测试中导入API方法,验证调用逻辑:

import { getCase } from './src/api-generated/cases';
import YourVueComponent from './YourVueComponent.vue';

test('fetch case data successfully', async () => {
  const wrapper = mount(YourVueComponent);
  await wrapper.vm.fetchCase();
  
  expect(getCase).toHaveBeenCalledWith(CASE_ID_SUCCESS);
  expect(wrapper.text()).toContain(getCaseSuccess.title);
});

方案3:统一项目中的axios实例

如果API代码允许修改,让它复用项目根目录的axios:

  • 删除API代码文件夹里的node_modules/axios和package-lock.json
  • 在API代码的package.json中把axios设为peerDependencies,确保它使用项目的axios依赖

这样jest.mock('axios')就能覆盖所有地方的axios实例了。

额外排查点

  • 检查API代码的axios导入方式:如果是import axios from 'axios'但它的node_modules里有axios,就是依赖重复导致实例不一致
  • 分别在测试和API代码里打印console.log(axios),对比是否为同一个对象(看toString()输出或内存地址)

内容的提问来源于stack exchange,提问作者Ricardo de Vries

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 04:35:22