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

如何使用Jest仅Mock类中的单个函数?

如何用Jest仅Mock类中的单个实例方法

嘿,作为Jest新手,你遇到的这个问题其实很常见——直接给类本身赋值Mock方法是行不通的,因为类的实例方法是挂载在原型链上的,不是类的静态属性。我来给你一步步讲清楚正确的做法:

首先,先明确你当前代码的问题:你写的myModule.getCases = jest.fn()是给MyModule类添加了一个静态方法,但当你实例化new MyModule()时,实例会从MyModule.prototype上获取getCases方法,完全不会用到你Mock的这个静态方法。

下面是两种最常用的正确解决方案:

方法一:直接Mock类原型上的方法

这种方式简单直接,适合只需要临时Mock的场景:

// myModule.test.js
const MyModule = require('./myModule.js');

// 替换原型上的getCases为Mock函数,还可以指定返回值
MyModule.prototype.getCases = jest.fn().mockReturnValue(5);

describe('Test mock function', () => {
  test('should use mocked getCases while keeping other methods working', () => {
    const instance = new MyModule();
    
    // 验证Mock方法的返回值
    expect(instance.getCases()).toBe(5);
    // 验证其他未Mock的方法依然正常
    expect(instance.getOtherCases()).toBe(3);
    // 验证Mock方法被调用过
    expect(MyModule.prototype.getCases).toHaveBeenCalled();
  });
});

方法二:用jest.spyOn更灵活地Mock(推荐)

spyOn可以让你在测试后轻松恢复原方法,避免影响其他测试用例,非常适合大型测试套件:

// myModule.test.js
const MyModule = require('./myModule.js');

describe('Test mock function', () => {
  let getCasesSpy;

  // 每个测试前创建Mock
  beforeEach(() => {
    getCasesSpy = jest.spyOn(MyModule.prototype, 'getCases').mockReturnValue(5);
  });

  // 每个测试后恢复原方法
  afterEach(() => {
    getCasesSpy.mockRestore();
  });

  test('should use mocked getCases and preserve original behavior after test', () => {
    const instance = new MyModule();
    
    expect(instance.getCases()).toBe(5);
    expect(instance.getOtherCases()).toBe(3);
    expect(getCasesSpy).toHaveBeenCalledTimes(1);
  });
});

额外技巧:Mock单个实例的方法

如果你只想Mock某一个具体实例的getCases方法,而不是所有实例,可以在实例化之后再Mock:

test('mock only one instance\'s getCases method', () => {
  const instance = new MyModule();
  // 针对这个实例创建Mock
  const mockGetCases = jest.spyOn(instance, 'getCases').mockReturnValue(10);
  
  expect(instance.getCases()).toBe(10);
  expect(instance.getOtherCases()).toBe(3);
  
  // 恢复这个实例的原方法
  mockGetCases.mockRestore();
});

这样就能精准Mock你需要的那个方法,同时保留类的其他功能和构造函数的执行啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:32:16