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

Jest测试报错:Matcher error,接收值必须为mock函数

问题原因与解决方案

错误根源

你用错了Jest匹配器:toHaveReturnedWith是专门用于断言mock函数的返回值的匹配器,它要求接收的必须是一个mock函数实例,但你这里await index.execute()得到的是函数执行后的返回值undefined,并非mock函数本身,因此触发了该错误。

正确的断言方式

如果你的目标是验证index.execute()的返回值为undefined,直接用普通值匹配器toBe(undefined)即可:

await expect(index.execute()).resolves.toBe(undefined);

若需验证mock函数的返回值

如果你是想检查你模拟的downloadModule或compareChecksum的返回情况,应该针对这些mock函数使用toHaveReturnedWith:

import * as utils from './utils';
import * as index from './index';

// 模拟utils模块的方法
jest.mock('./utils', () => ({
  downloadModule: jest.fn().mockResolvedValue('模拟下载结果'),
  compareChecksum: jest.fn().mockResolvedValue(true)
}));

test('execute方法执行逻辑正确', async () => {
  await index.execute();
  
  // 验证mock函数downloadModule的返回值
  expect(utils.downloadModule).toHaveReturnedWith('模拟下载结果');
  // 验证mock函数compareChecksum的返回值
  expect(utils.compareChecksum).toHaveReturnedWith(true);
});

关键注意点

  • 区分匹配器场景:toHaveReturnedWith、toHaveBeenCalled这类匹配器仅适用于mock函数,用来检查函数的调用/返回行为;toBe、toEqual则用于断言具体的值结果。
  • 若index.execute本身不是mock函数,不要用mock专属匹配器去断言它的执行结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 21:15:51