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

Jest模拟单例Service实例失败,期望输出与实际不符的问题求助

Jest模拟单例Service实例失败,期望输出与实际不符的问题求助

大家好,我最近在写Jest测试的时候遇到了个头疼的问题——明明已经尝试mock了单例的Service实例,但测试结果始终不符合预期,想请各位帮忙看看哪里出了问题。

先给大家看下我的代码结构:

service.js

这个文件定义了Service类,并且直接导出了它的实例:

class Service {
    constructor() {
        this.value = 'A';
    }
    getValue() {
        return this.value;
    }
}

export default new Service();

main.js

这里导入了上面的service实例,定义了run函数来调用实例的方法并打印消息:

import service from './service';

export function run() {
    const value = service.getValue();
    console.log('Executing service with value ' + value);
}

Main.test.js

这是我的测试文件,我尝试用Jest的mock功能来替换原有的service实例:

import { jest } from '@jest/globals';
import { run } from './main';

jest.mock('./service', () => {
    return jest.fn().mockImplementation(() => {
        return {
            getValue: jest.fn().mockReturnValue('mocked_value'),
        };
    });
});

describe('test run', () => {
    it('should log the correct message', () => {
        console.log = jest.fn();
        run();
        expect(console.log).toHaveBeenCalledWith('Executing service with value mocked_value');
    });
});

测试结果

运行测试后,得到的错误是:

Expected: "Executing service with value mocked_value"
Received: "Executing service with value A"

可以看到,测试还是用了原service实例的value值'A',而不是我mock的'mocked_value'。我尝试了好几种写法都没搞定,有没有大佬能指点下怎么让这个mock生效呀?非常感谢!

备注:内容来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 10:13:01