执行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
相关产品推荐
相关产品推荐

