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

Jest中「类型参数无法赋值给never类型」错误的解决咨询

解决Jest Mock时TypeScript类型错误(mockResolvedValue相关)

问题核心

你遇到的两类错误本质都是TypeScript无法识别被mock函数的类型:

  • 直接调用mockResolvedValue时,TS判定原函数(如getUserByEmail、bcrypt.hash)不具备Jest Mock函数的属性
  • 使用as jest.Mock断言后,因未指定返回值类型,TS推断参数类型为never,导致传入值类型不匹配

解决方案

1. 自定义函数(如getUserByEmail)的mock处理

方案一:明确指定Mock函数的返回值类型

通过jest.Mock<T>泛型声明mock函数的返回值类型,避免TS推断为never:

// 假设getUserByEmail的返回类型是Promise<{ id: string; email: string; password: string; } | null>
(getUserByEmail as jest.Mock<Promise<{ id: string; email: string; password: string; } | null>>)
  .mockResolvedValue({ id: '1', email: 'test@example.com', password: 'mock-hash' });
方案二:用jest.mock自动mock模块

如果getUserByEmail是从某个模块导出的,直接mock整个模块,TS会自动识别函数为Mock类型:

// 测试文件顶部mock目标模块
jest.mock('./path-to-user-service');
import { getUserByEmail } from './path-to-user-service';

// 直接调用mockResolvedValue即可
getUserByEmail.mockResolvedValue({ id: '1', email: 'test@example.com', password: 'mock-hash' });

2. 第三方库函数(如bcrypt.hash)的mock处理

方案一:精确断言重载函数类型

bcrypt.hash是重载函数,需要明确指定要mock的重载签名:

import bcrypt from 'bcrypt';

// 断言为返回Promise的重载版本
(bcrypt.hash as jest.MockedFunction<(s: string, salt: string | number) => Promise<string>>)
  .mockResolvedValue('hashedPassword');
方案二:mock整个第三方库

通过jest.mockmock整个bcrypt模块,自动赋予函数Mock类型:

jest.mock('bcrypt');
import bcrypt from 'bcrypt';

// 直接使用mockResolvedValue
bcrypt.hash.mockResolvedValue('hashedPassword');

额外注意事项

  • 确保已安装@types/jest和@types/bcrypt(针对第三方库),提供完整的类型支持
  • 如果自定义函数有复杂类型,可提前定义类型别名,简化Mock泛型的书写

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 20:42:05