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

执行Jest测试时Nest无法解析UserService依赖的问题求助

问题描述

运行Jest测试时出现依赖解析错误:

Nest can't resolve dependencies of the UserService (UserRepository, ?). Please make sure that the argument StaticContentService at index [1] is available in the RootTestModule context.

UserService代码:

@Injectable()
export class UserService {
  constructor(
    private userRepository: UserRepository,
    private staticContentService: StaticContentService,
  ) {}
}

测试模块代码:

const module: TestingModule = await Test.createTestingModule({
      imports: [
        ConfigModule.forRoot({
          load: [AppConfig],
        }),
      ],
      controllers: [StageReviewController],
      providers: [
        PrismaService,
        { provide: StaticContentRepository, useClass: MockStaticContentRepository },
        { provide: StaticContentService, useClass: MockStaticContentService },
        UserService,
        UserRepository,
    }).compile();
解决方法
  • 校验依赖注入token一致性:确保UserService中注入的StaticContentService,与测试模块providers里provide字段指定的StaticContentService是同一个类(确认导入路径一致,未使用自定义token或别名)。
  • 处理抽象类依赖:如果UserRepository是抽象类/接口,不能直接放入providers数组,需参照StaticContentRepository的方式提供mock实现:
    { provide: UserRepository, useClass: MockUserRepository }
    
  • 修正测试模块语法错误:你的测试模块存在语法缺失,providers数组缺少闭合],createTestingModule配置对象缺少闭合},修正后代码示例:
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        ConfigModule.forRoot({
          load: [AppConfig],
        }),
      ],
      controllers: [StageReviewController],
      providers: [
        PrismaService,
        { provide: StaticContentRepository, useClass: MockStaticContentRepository },
        { provide: StaticContentService, useClass: MockStaticContentService },
        UserService,
        // 若UserRepository为抽象类,替换为对应mock实现
        { provide: UserRepository, useClass: MockUserRepository },
      ],
    }).compile();
    
  • 确认Mock类有效性:保证MockStaticContentService的结构与原StaticContentService一致,且已正确导入到测试文件中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 06:16:16