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

I try to run NestJs test but got the following error

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

This project is using Mongoose for connecting to MongoDB

You can reproduce the error by running code in this repo https://github.com/kruyvanna/nestjs-test-error

Thank you in advance



Solution 1:[1]

You'll get that error because you have the following module:

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

and this provider:

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

and there is no way to tell what's the value of catModel as its provider token was not registered within the testing module.

To fix that you could register it like the docs show

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1