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

如何断言Jest模拟模块的方法已被调用?

解决Jest模拟模块后无法断言mock函数的问题

问题原因

jest.mock()会被Jest自动提升到当前模块代码的最顶部执行,比任何变量声明都早。你把log变量放在jest.mock()外部的写法,会导致Jest执行模块工厂函数时,外部的log还未初始化,因此触发"模块工厂不允许引用作用域外变量"的错误。

正确解决方案

直接从你模拟的模块中导入log函数即可访问到mock实例,具体代码如下:

// 先导入被模拟的模块
import logsService from '../../../../services/logs.service.js';

// 模拟模块
jest.mock('../../../../services/logs.service.js', () => ({
    log: jest.fn()
}));

// 在测试用例中断言
test('log方法被正确调用', () => {
    // 执行触发log调用的业务代码
    // ...

    // 断言调用次数和参数
    expect(logsService.log).toHaveBeenCalledTimes(2);
    expect(logsService.log).toHaveBeenCalledWith(2, "foo");
});

另一种可选写法

如果需要在模块工厂里复用mock函数,也可以直接在工厂内定义jest.fn(),再通过导入的模块访问:

jest.mock('../../../../services/logs.service.js', () => {
    const mockLog = jest.fn();
    return {
        log: mockLog
    };
});

import logsService from '../../../../services/logs.service.js';

test('log方法被正确调用', () => {
    expect(logsService.log).toHaveBeenCalledWith(2, "foo");
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 00:42:41