3
votes

When writing a unit test for a controller, Nest is unable to resolve my Mongoose model dependency:

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

Potential solutions:
- If USER_MODEL is a provider, is it part of the current _RootTestModule?
- If USER_MODEL is exported from a separate @Module, is that module imported within _RootTestModule?
  @Module({
    imports: [ /* the Module containing USER_MODEL */ ]
  })

My model is injected via my service constructor in the users.service.ts:

import { IUserModel } from './interfaces';
import { Model } from 'mongoose';
import { USER_MODEL } from './constants/users.constants';

@Injectable()
export class UsersService {

  constructor (
    @Inject(USER_MODEL)
    private readonly userModel: Model<IUserModel>,
  ) {}

  ...
}

and my test is defined as:

const mockUserModel = {};

describe('Users Controller', () => {
  let usersController: UsersController;
  let usersService: UsersService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [UsersController],
      providers: [
        {
          provide: getModelToken(USER_MODEL),
          useValue: mockUserModel,
        },
        UsersService,
      ],
    }).compile();

    usersController = module.get<UsersController>(UsersController);
    usersService = module.get<UsersService>(UsersService);
  });

  it('should define user controller and service', () => {
    expect(usersController).toBeDefined();
    expect(usersService).toBeDefined();
  });
});

All of these classes are defined in the same module. I'm not quite sure what Nest is looking for. I'm following the guide at: https://docs.nestjs.com/fundamentals/testing and have looked through several older Github issues as well.

I've also tried creating a custom class provider as defined here: https://docs.nestjs.com/fundamentals/custom-providers to supply the typed Mongoose Model, but that returned the same error.

Can anyone help me out?

1

1 Answers

4
votes

If you are using @Inject(USER_MODEL) then you need to use provide: USER_MODEL in your test. The getModelToken utility method is necessary if you use @InjectModel() instead of the raw @Inject().