vanna
vanna

Reputation: 1049

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

Upvotes: 16

Views: 42161

Answers (1)

Micael Levi
Micael Levi

Reputation: 6685

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();

Upvotes: 31

Related Questions