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

Jest多测试用例监视同一原型函数的独立性问题及解决方法

解决方案:测试用例隔离与函数调用监控

1. 每个测试后恢复Spy

jest.spyOn创建的Spy会挂载在类原型上,默认不会自动清除状态,导致测试用例互相干扰。可以在单个测试结束后手动恢复原方法,或者用afterEach统一处理所有测试:

test('test1', async () => {
    const spy_f1 = jest.spyOn(A.prototype, "f1");
    f2();
    console.log("In test1", spy_f1.mock.calls);
    spy_f1.mockRestore(); // 恢复原方法并清除mock数据
});

// 或者用afterEach统一处理所有测试用例
afterEach(() => {
    jest.restoreAllMocks();
});

2. 直接模拟整个A类

通过jest.mock完全替换A类的实现,让每个测试都拿到独立的模拟实例,从根源避免状态共享:

// 假设A类在your-module-path文件中
jest.mock('./your-module-path', () => {
    const originalModule = jest.requireActual('./your-module-path');
    return {
        ...originalModule,
        A: jest.fn().mockImplementation(() => ({
            f1: jest.fn()
        }))
    };
});

test('test1', async () => {
    f2();
    // 获取f2中创建的A实例
    const aInstance = A.mock.instances[0];
    console.log("In test1", aInstance.f1.mock.calls);
});

test('test2', async () => {
    f2();
    const aInstance = A.mock.instances[0];
    console.log("In test2", aInstance.f1.mock.calls);
});

3. 全局重置Mock调用记录

如果只需要清空mock的调用次数和参数记录,不需要恢复原方法,可以在每个测试前调用jest.clearAllMocks(),或者在Jest配置中设置resetMocks: true:

beforeEach(() => {
    jest.clearAllMocks();
});

test('test1', async () => {
    const spy_f1 = jest.spyOn(A.prototype, "f1");
    f2();
    console.log("In test1", spy_f1.mock.calls);
});

test('test2', async () => {
    const spy_f1 = jest.spyOn(A.prototype, "f1");
    f2();
    console.log("In test2", spy_f1.mock.calls);
});

内容的提问来源于stack exchange,提问作者carlo.milanesi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:16:21