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

Jest中如何Mock返回类型为never的抛错函数?

解决Jest Mock返回never类型函数的TypeScript类型错误

原函数定义返回never类型(永远不会正常返回,只会抛出错误),而Jest的jest.fn()默认会推断返回any类型,这就导致了TypeScript的类型不兼容错误。要保留类型注解的同时解决问题,有两种可靠方案:

方案一:显式指定Jest Mock的泛型类型

通过jest.fn的泛型参数,明确指定函数的返回类型和参数类型数组,让TS正确识别mock函数的类型:

throwerGuard.throwCycleDetected = jest
  .fn<never, [string]>() // 第一个泛型:返回类型为never;第二个泛型:参数为[string]类型数组
  .mockImplementation((ticketId: string) => {
    throw new Error(`Detected a cycle of tickets for ${ticketId}`);
  });

这种方式最安全,TS会全程做类型检查,避免参数或返回值的类型错误。

方案二:使用类型断言

如果觉得泛型写法繁琐,可以用类型断言直接告诉TS,这个mock函数符合原函数的类型:

throwerGuard.throwCycleDetected = jest
  .fn()
  .mockImplementation(() => {
    throw new Error('Detected a cycle of tickets for ticketId');
  }) as typeof throwerGuard.throwCycleDetected;

注意:类型断言会跳过TS的类型检查,所以要确保mock的实现逻辑和原函数的行为一致(比如都抛出错误)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 10:07:05