Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

nestjs

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

like image 901
vanna Avatar asked Dec 07 '25 02:12

vanna


1 Answers

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();
like image 147
Micael Levi Avatar answered Dec 10 '25 09:12

Micael Levi