如何修改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
相关产品推荐
相关产品推荐

