'Nest can't resolve dependencies of the Repository Mongoose

I am trying to write a simple test to my Nestjs project but I keep failing to get this to work.

Error Message

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

Potential solutions:

  • If UserModel is a provider, is it part of the current RootTestModule?
  • If UserModel is exported from a separate @Module, is that module imported within RootTestModule? @Module({imports: [ /* the Module containing UserModel */ ]})

user.service.spec.ts

beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [MongooseModule.forRoot(process.env.MONGO_URI)],
      providers: [
        UserService,
        UserRepository,
        {
          provide: User.name,
          useValue: MongooseModule.forFeature([
            { name: User.name, schema: UserSchema },
          ]),
        },
      ],
    }).compile();

    userService = module.get<UserService>(UserService);
  });

user.service.ts

@Injectable()
export class UserService {
  constructor(private readonly userRepository: UserRepository) {}
}

user.repository.ts

@Injectable()
export class UserRepository {
  constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}
}


Solution 1:[1]

@InjectModel(User.name) isn't the same as doing @Inject(User.name), this is why you can't use provide: User.name and expect it to find the value for that provider.

Use provide: getModelToken(User.name)

Read the docs next time, please: https://docs.nestjs.com/techniques/mongodb#testing

Also, you can explore a bunch of other testing samples here: https://github.com/jmcdo29/testing-nestjs

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 Micael Levi