Jest测试Nest.js AuthController时遇AuthService依赖解析错误求助
问题:Nest.js AuthController测试时出现依赖解析错误
错误详情
Nest can't resolve dependencies of the AuthService (?, UserService, JwtService). "Please make sure that the argument UserModel at index [0] is available in the AuthModule context."
系统给出的潜在提示:
Potential solutions:
- Is AuthModule a valid NestJS module?
- If UserModel is a provider, is it part of the current AuthModule?
- If UserModel is exported from a separate @Module, is that module imported within AuthModule?
@Module({
imports: [ /* the Module containing UserModel */ ]
})
相关代码
auth.controller.spec.ts 测试模块配置
const UserModel = getModelForClass(User); describe('AuthController', () => { let app: INestApplication; let authService: AuthService; beforeEach(() => { jest.setTimeout(30000); }); beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [ AuthModule, UserModule, MongooseModule.forRootAsync({ useFactory: async () => { const mongo = await MongoMemoryServer.create(); const uri = mongo.getUri(); return { uri, useNewUrlParser: true, useUnifiedTopology: true, }; }, }), ], providers: [AuthService, UserService, JwtService, UserModel], }).compile(); app = module.createNestApplication(); app.useGlobalPipes(new ValidationPipe()); await app.init(); authService = module.get<AuthService>(AuthService); });
auth.module.ts
@Module({ imports: [ PassportModule, JwtModule.register({ secret: process.env.JWT_SECRET_KEY, signOptions: { expiresIn: '30m' }, }), ], controllers: [AuthController], providers: [AuthService, LocalStrategy, LocalAuthGuard, JwtAuthGuard], exports: [JwtAuthGuard], }) export class AuthModule {}
UserModule.ts
const UserModel = getModelForClass(User); @Module({ imports: [ MongooseModule.forFeature([ { name: User.name, schema: UserSchema, }, ]), ], providers: [UserService, UserModel], exports: [UserModel], }) export class UserModule {}
错误原因
AuthModule未导入依赖的UserModule
AuthService的构造函数依赖UserModel,但当前AuthModule的imports数组里没有导入UserModule。UserModel是在UserModule中导出的,只有AuthModule显式导入UserModule后,AuthModule的上下文才能访问到UserModel,解决依赖缺失问题。测试模块重复注册服务导致冲突
测试模块里同时导入了AuthModule和UserModule,又在providers里重复注册AuthService、UserService、UserModel这些已经由对应模块管理的服务。这种重复注册会让Nest的DI容器出现重复提供者,反而干扰正常的依赖解析逻辑,应该移除providers里的这些重复注册项,让模块自行管理内部的服务依赖。
内容的提问来源于stack exchange,提问作者Mateo
相关产品推荐
相关产品推荐

