You need to enable JavaScript to run this app. 集成测试中Mock axios GET请求仍报接口连接错误如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

集成测试中Mock axios GET请求仍报接口连接错误如何解决?

问题根因

你遇到的报错主要由以下几个常见原因导致:

  1. mock注册时机晚于组件渲染:你在测试用例中先执行了组件渲染,再注册/institution-types的接口mock,组件挂载时触发的请求没有被mock拦截,直接向外网发出导致连接拒绝报错。
  2. mock对象不匹配:如果你的项目中使用的是封装了拦截器、baseURL的自定义axios实例,直接mock全局axios对象无法匹配到业务代码发出的请求。
  3. mock返回值结构不符合预期:你通过jest.spyOnmock的getInstitution方法返回的mockAxiosResponse没有和真实接口对齐,缺少data字段,导致业务代码访问res.data时抛出 undefined 错误。

修复方案

1. 调整mock注册顺序

所有接口mock规则必须在组件渲染前完成注册,同时每个测试用例执行前重置mock,避免用例间互相影响:

describe('InstitutionFormPage', () => {
  beforeEach(() => {
    // 先重置axios mock的所有规则
    mock.reset();
    createInstitution = jest.spyOn(institution, 'createInstitution').mockResolvedValue(mockAxiosResponse());
    jest.spyOn(institution, 'getInstitution').mockResolvedValue(mockAxiosResponse());
  });

  it('Should submit Institution Form', async () => {
    // 先注册接口mock,再渲染组件
    mock.onGet('/institution-types').reply(200, mockData);
    const { container } = renderComponent();

    // 原有测试逻辑保持不变
    await waitFor(() => expect(screen.queryByText('loading')).not.toBeInTheDocument());
    // ... 其余代码
  });
});

2. 适配自定义axios实例

如果你的业务代码使用的是封装后的自定义axios实例(通常在services/request.ts这类文件中导出),需要将axios-mock-adapter绑定到这个实例上,而非全局axios:

// 导入业务代码中实际使用的axios实例
import customAxios from 'services/request';
import MockAdapter from 'axios-mock-adapter';

// 绑定mock到实际使用的实例
const mock = new MockAdapter(customAxios);

3. 对齐mock返回值结构

检查你的mockAxiosResponse方法返回值,保证包含业务代码需要的data字段,避免访问属性时报错:

// 示例:mockAxiosResponse需要和真实接口返回结构对齐
const mockAxiosResponse = (data = {}) => ({
  data,
  status: 200,
  statusText: 'OK',
  headers: {},
  config: {}
});

临时屏蔽错误日志(可选)

如果确认测试逻辑正确,只是要消除不必要的报错输出,可以在测试文件顶部加入日志过滤逻辑:

const originalError = console.error;
beforeAll(() => {
  console.error = (...args) => {
    if (
      args[0]?.includes?.('Error on institution get') ||
      args[0]?.includes?.('ECONNREFUSED')
    ) return;
    originalError.apply(console, args);
  };
});

afterAll(() => {
  console.error = originalError;
});

内容的提问来源于stack exchange,提问作者Matheus Salles Blanco

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 17:36:10