Nest 无法解析 (?) 的依赖关系。请确保索引 [0] 处的参数在 RootTestModule 上下文中可用

van*_*nna 13 nestjs

我尝试运行 NestJs 测试,但出现以下错误

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

该项目使用 Mongoose 连接到 MongoDB

您可以通过运行此存储库中的代码来重现错误 https://github.com/kruyvanna/nestjs-test-error

先感谢您

Mic*_*evi 27

您会收到该错误,因为您有以下模块:

const module: TestingModule = await Test.createTestingModule({
  providers: [CatService],
}).compile();
Run Code Online (Sandbox Code Playgroud)

和这个提供商:

@Injectable()
export class CatService {
  constructor(@InjectModel(Cat.name) private catModel: Model<CatDocument>) {}
}
Run Code Online (Sandbox Code Playgroud)

并且无法判断其价值是多少,catModel因为其提供者令牌未在测试模块中注册。

要解决这个问题,您可以像文档所示那样注册它

const module: TestingModule = await Test.createTestingModule({
  providers: [CatService, { provide: getModelToken(Cat.name), useValue: jest.fn() }],
}).compile();
Run Code Online (Sandbox Code Playgroud)