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

如何修改Jest中被Mock的类方法的返回值?

解决方法

要在不同测试用例中动态修改methodOne的返回值,你可以把methodOne定义为Jest mock函数,然后在每个测试用例里单独设置它的返回值。具体实现如下:

1. 调整初始Mock配置

将methodOne替换为Jest mock函数,并可设置默认返回值:

jest.mock("module_name", () => {
  return {
    __esModule: true,
    Abc: class Abc {
      constructor(config) {}

      // 定义为mock函数并设置默认返回值
      methodOne = jest.fn().mockResolvedValue({
        message: {
          content: 'This text I need to change',
        },
      });
    },
    Configuration: class Configuration {
      constructor(config) {
        return true;
      }
    },
  };
});

2. 在测试用例中动态修改返回值

通过Abc.prototype.methodOne直接覆盖每个测试用例的返回值:

describe("getVeganStatus", () => {
  it("should handle case one......", async () => {
    // 设置methodOne返回"ABC"
    Abc.prototype.methodOne.mockResolvedValue({
      message: {
        content: "ABC",
      },
    });

    // 执行你的测试逻辑并断言
    const result = await getVeganStatus();
    expect(result).toBe(...);
  });

  it("should handle case two......", async () => {
    // 设置methodOne返回"XYZ"
    Abc.prototype.methodOne.mockResolvedValue({
      message: {
        content: "XYZ",
      },
    });

    // 执行你的测试逻辑并断言
    const result = await getVeganStatus();
    expect(result).toBe(...);
  });
});

可选:添加测试用例隔离钩子

如果需要避免测试用例之间的mock状态干扰,可以在describe块中添加重置钩子:

describe("getVeganStatus", () => {
  afterEach(() => {
    // 重置mock的调用记录和返回值
    jest.clearAllMocks();
  });

  // ...测试用例
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 18:52:11