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

如何用Jest测试React类组件中的fetch().then逻辑?

测试CModel.fetch的Jest实现方案

方案一:Mock整个CModel模块

直接mock导入的CModel类,让它返回带有mock fetch方法的实例,覆盖原始实现:

// 测试文件
import CModel from "xxxx";

// Mock整个CModel类
jest.mock("xxxx", () => {
  return jest.fn().mockImplementation(() => ({
    fetch: jest.fn().mockResolvedValue({ errCode: 0 })
  }));
});

test("验证fetch成功逻辑", async () => {
  const cModel = new CModel();
  // 调用包含目标fetch逻辑的业务函数(比如getData)
  await getData();
  
  // 断言fetch调用参数是否正确
  expect(cModel.fetch).toHaveBeenCalledWith(xxxxxx, { body: { type: 1 } });
  // 可添加更多业务逻辑的断言,比如成功分支的处理动作
});

test("验证fetch错误捕获逻辑", async () => {
  const mockError = new Error("请求失败");
  const cModel = new CModel();
  // 重新mock fetch为reject状态
  cModel.fetch.mockRejectedValue(mockError);
  
  await getData();
  
  // 断言错误处理逻辑是否执行
  const consoleSpy = jest.spyOn(console, "log");
  expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(mockError));
  consoleSpy.mockRestore();
});

方案二:SpyOn已有实例的fetch方法

如果业务代码中已创建cModel实例,可通过spyOn替换其fetch方法:

// 导入业务文件中的cModel实例(或确保测试能访问到该实例)
import { cModel } from "./your-business-file";
import CModel from "xxxx";

test("验证fetch调用行为", async () => {
  // SpyOn实例的fetch方法,mock成功返回
  const fetchSpy = jest.spyOn(cModel, "fetch").mockResolvedValue({ errCode: 0 });
  
  await getData();
  
  expect(fetchSpy).toHaveBeenCalledWith(xxxxxx, { body: { type: 1 } });
  
  // 恢复原始方法
  fetchSpy.mockRestore();
});

test("验证错误分支处理", async () => {
  const mockErr = { message: "接口出错" };
  const fetchSpy = jest.spyOn(cModel, "fetch").mockRejectedValue(mockErr);
  const consoleSpy = jest.spyOn(console, "log");
  
  await getData();
  
  expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(mockErr));
  
  fetchSpy.mockRestore();
  consoleSpy.mockRestore();
});

关键注意点

  • 若业务代码是在模块内直接创建cModel实例且未导出,优先用方案一mock整个模块。
  • 替换示例中的xxxxxx为实际参数值,或用expect.any(类型)做模糊匹配(如expect.any(String))。
  • 动态生成的参数需根据实际场景调整断言逻辑。

内容的提问来源于stack exchange,提问作者zhu liwei

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 08:01:24