如何使用Jest模拟Mongoose模型依赖?遇创建类报错
解决Mongoose模型测试中的
Target class "undefined"错误 错误原因
直接使用jest.mock('mongoose')会全量替换mongoose模块的所有导出,导致@nestjs/mongoose的SchemaFactory.createForClass()无法获取正确的mongoose类型定义(比如Schema.Types.ObjectId),进而无法解析装饰器元数据,抛出类为undefined的错误。
解决方案
方案1:使用@nestjs/testing搭建测试模块(推荐)
通过官方测试模块配置Mongoose连接,搭配内存数据库模拟真实环境,避免手动mock带来的依赖问题:
- 安装内存数据库依赖:
npm install mongodb-memory-server --save-dev
- 编写测试文件:
import { Test, TestingModule } from '@nestjs/testing'; import { MongooseModule, getModelToken } from '@nestjs/mongoose'; import { MongoMemoryServer } from 'mongodb-memory-server'; import mongoose, { Model } from 'mongoose'; import { Justification, JustificationSchema } from './justification.schema'; let mongod: MongoMemoryServer; let justificationModel: Model<Justification>; beforeAll(async () => { // 启动内存MongoDB服务 mongod = await MongoMemoryServer.create(); const mongoUri = mongod.getUri(); // 配置测试模块 const module: TestingModule = await Test.createTestingModule({ imports: [ MongooseModule.forRoot(mongoUri), MongooseModule.forFeature([{ name: Justification.name, schema: JustificationSchema }]), ], }).compile(); // 获取模型实例 justificationModel = module.get<Model<Justification>>(getModelToken(Justification.name)); }); afterAll(async () => { // 关闭内存服务 await mongod.stop(); }); it('should define the Justification model', () => { expect(justificationModel).toBeDefined(); });
方案2:部分mock mongoose而非全量替换
如果必须手动mock,保留mongoose的核心结构,只mock需要的方法:
// 在测试文件顶部添加 jest.mock('mongoose', () => { // 引入真实的mongoose模块 const originalMongoose = jest.requireActual('mongoose'); return { ...originalMongoose, // 只mock model和connect方法 model: jest.fn(), connect: jest.fn().mockResolvedValue(true), }; });
方案3:检查路径别名配置
确保测试环境中~/user/schemas能正确解析到User类,在jest.config.js中添加路径映射:
module.exports = { moduleNameMapper: { '^~/user/(.*)$': '<rootDir>/src/user/$1', }, };
内容的提问来源于stack exchange,提问作者Lucas Schlottfeldt
相关产品推荐
相关产品推荐

