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

Jest如何测试函数是否被调用?测试anotherFunc调用失败怎么解决

失效原因

你当前的测试逻辑不生效,核心是测试用例内局部声明的anotherFunc mock对象,和my_util.js中实际调用的anotherFunc没有任何关联。myFunc运行时调用的仍然是another_util.js导出的真实函数,自然不会触发你定义的mock,也就没有调用记录。

最简解决方案

使用Jest的模块mock能力直接替换整个依赖模块即可,不需要修改业务代码:

  1. 先确认你的my_util.js已经正确导入了anotherFunc(缺失导入的话业务代码本身就无法正常运行),示例如下:
// my_util.js 完整代码
import { anotherFunc } from './another_util.js'
export function myFunc(i) {
  if (i === 1){
    anotherFunc();
  }
}
  1. 修改测试代码,在导入阶段mock整个another_util.js模块:
import { myFunc } from './my_util.js'
import { anotherFunc } from './another_util.js'

// 整模块mock,Jest会自动将模块的所有导出替换为mock函数
jest.mock('./another_util.js')

it('myFunc should call anotherFunc', () => {
  myFunc(1);
  expect(anotherFunc).toHaveBeenCalled();  
});

如果存在多个测试用例需要清空mock的历史调用记录,可以在测试套件开头添加钩子函数:

beforeEach(() => {
  // 每次测试前清空所有mock的调用记录
  jest.clearAllMocks()
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 17:36:01