【发布时间】:2021-07-28 18:46:58
【问题描述】:
我的任务是向遗留项目添加单元测试。
在给定模块上引入单元测试之前,我正在做“冒烟测试”。基本上使脚手架“应该定义”通过。
因此我面临经典错误:
Error: Nest can't resolve dependencies of the MemberService (NestWinston, ?, RedisService, RepoService, SqsService). Please make sure that the argument Object at index [1] is available in the RootTestModule context.
Potential solutions:
- If Object is a provider, is it part of the current RootTestModule?
- If Object is exported from a separate @Module, is that module imported within RootTestModule?
@Module({
imports: [ /* the Module containing Object */ ]
})
我怎样才能确定该模块需要什么?
这是一个遗留项目,因此很难获得信息,我的同事也无法完全帮助我。
什么是解决这个问题的好方法?
编辑:这是 MemberService 的构造函数
@Injectable()
export class MemberService {
private readonly sendMail: any;
private algoliaClient: any;
private index: AlgoliaSearch.SearchIndex;
private readonly sendLog: any;
constructor(
@Inject(WINSTON_MODULE_NEST_PROVIDER)
private readonly cacheService: CacheService,
private readonly logger: LoggerService,
private readonly redisService: RedisService,
private readonly repoService: RepoService,
private readonly sqsService: SqsService,
) {
const { sendMessage: sendLog } = this.sqsService.initQueue('logs');
this.sendLog = sendLog;
const { sendMessage: sendMail } = this.sqsService.initQueue('mail');
this.sendMail = sendMail;
this.algoliaClient = AlgoliaSearch.default(ALGOLIA_APP_ID, ALGOLIA_API_KEY);
this.index = this.algoliaClient.initIndex(`${APP_ENV}_NETWORK_MEMBERS`);
}
编辑 2:这是我的测试模块设置
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [
TypeOrmModule.forRoot(DB_CONNECTION),
RepoModule,
RedisModule.register({
url: REDIS_URL,
autoResubscribe: false,
}),
],
providers: [
CacheService,
MemberService,
SqsService,
{
provide: WINSTON_MODULE_NEST_PROVIDER,
useFactory: () =>
Winston.createLogger({
transports: [new Winston.transports.Console()],
}),
},
],
}).compile();
service = module.get<MemberService>(MemberService);
});
【问题讨论】:
-
这是常见的;看看stackoverflow.com/…,如果您向我们展示您的
MemberService的constructor方法如何,我们可以为您提供帮助,顺便说一句 -
感谢@MicaelLevi 的回答,我已经进行了相应的编辑。
-
据我所知,LoggerService 丢失了。根据 MemberService 构造函数参数,预计提供者。
-
是的。您的测试模块是如何设置的?您必须执行此处显示的操作:docs.nestjs.com/techniques/database#testing-1
-
已编辑。出于某种原因,我无法在我的测试模块中导入
LoggerService。
标签: typescript testing dependency-injection dependencies nestjs