[Error] Nest can’t resolve dependencies of the UserService (?). Please make sure that the argument “UsersModel” at index [0] is available in the RootTestModule context.
I had only used Nest.js a couple of times a few years ago, but I decided to dive back into it recently. I started by following a tutorial on YouTube and successfully connected to Mongoose without any issues. However, the problem arose when I ran the tests.
While yarn start:dev
worked perfectly without any errors, running yarn test
began to throw errors:
Nest can't resolve dependencies of the UserService (?). Please make sure that the argument "UsersModel" at index [0] is available in the RootTestModule context.
Unsure of what this error meant, I turned to the internet for solutions.
Case 1: Someone suggested that it might be due to duplicate imports and advised checking if service.ts
was imported more than once in app.module.ts
or elsewhere. After thoroughly inspecting my code, I found no duplicate imports.
Case 2: Another suggestion was to add this part to module.ts
:
@Module({
controllers: [UserController],
providers: [
UserService,
{ provide: getModelToken(User.name), useValue: userModule },
],
})
But this didn’t work either.
Case 3: After further investigation, I found that commenting out the following part in service.ts
prevented the error from occurring:
constructor(@InjectModel(Users.name) private userModel: Model<Users>) {}
It did not work for me, so I continued searching for a proper solution.
Case 4: Some recommended exporting the module in user.module.ts
. I tried that as well, but it didn't help.
Case 5: I tried at least five more solutions, all to no avail.
So, what finally worked?
I stumbled upon this sample project: Mongo Sample. By following it closely and modifying user.service.spec.ts
and user.service.ts
accordingly, the tests finally passed!
It took quite a while, but seeing it work in the end was incredibly satisfying.