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

Jest Mock在导出函数基础示例中失效问题排查

问题原因

当someFunctionImTesting在文件内部直接调用otherFunction时,它引用的是文件内的本地函数实例,而非你通过jest.mock替换的导出版本。所以即便你mock了导出的otherFunction,实际执行时函数调用的还是原本地函数,断言自然检测不到调用记录。

解决方法

方法1:修改原文件,让函数调用导出的版本

调整原文件中someFunctionImTesting的调用逻辑,使其引用导出的otherFunction,而非本地引用:

方式A:使用exports(适配CommonJS风格)

const otherFunction = () => {..........}

const someFunctionImTesting = async () => {
  // 改为调用exports上的版本
  const result = await exports.otherFunction(param);
}

export {
  otherFunction,
  someFunctionImTesting
};

方式B:ES模块自引用(推荐,适配ES模块规范)

// 导入自身模块的引用
import * as self from './当前文件名';

export const otherFunction = () => {..........}

export const someFunctionImTesting = async () => {
  // 调用自引用上的otherFunction
  const result = await self.otherFunction(param);
}

修改后,someFunctionImTesting会调用导出的otherFunction,你原有的测试代码就能正常捕获mock函数的调用了。

方法2:不修改原代码,用jest.spyOn替换导出函数

如果不想改动业务代码,可以通过jest.spyOn直接替换模块导出的函数:

import * as service from '../service';

describe('testing', () => {
  it('........', async () => {
    // 替换otherFunction的实现
    const mockOtherFn = jest.spyOn(service, 'otherFunction').mockResolvedValue('模拟返回值');
    
    await service.someFunctionImTesting();
    expect(mockOtherFn).toHaveBeenCalled();
    
    // 测试后恢复原函数
    mockOtherFn.mockRestore();
  });
});

注意:这种方法依赖模块编译配置,需确保编译工具会将内部函数调用转换为对导出对象的引用,若不生效则优先使用方法1。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:42:09