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

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 {}

错误原因

  1. AuthModule未导入依赖的UserModule
    AuthService的构造函数依赖UserModel,但当前AuthModule的imports数组里没有导入UserModule。UserModel是在UserModule中导出的,只有AuthModule显式导入UserModule后,AuthModule的上下文才能访问到UserModel,解决依赖缺失问题。

  2. 测试模块重复注册服务导致冲突
    测试模块里同时导入了AuthModule和UserModule,又在providers里重复注册AuthService、UserService、UserModel这些已经由对应模块管理的服务。这种重复注册会让Nest的DI容器出现重复提供者,反而干扰正常的依赖解析逻辑,应该移除providers里的这些重复注册项,让模块自行管理内部的服务依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 13:22:54