Search code examples
jestjsnestjsmikro-orm

NestJS and Jest: Nest can't resolve dependencies of the UserService


I am using a NestJS + MikroORM stack and trying to write tests using Jest.

On the user.service.spec.ts I am always getting the following error:

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

The user.service.spec.ts:

describe('UserService', () => {
  let userService: UserService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        UserService,
        {
          provide: getRepositoryToken(User),
          useValue: {
            find: jest.fn().mockResolvedValue([]),
            findOneOrFail: jest.fn().mockResolvedValue({}),
            create: jest.fn().mockReturnValue({}),
            save: jest.fn(),
            update: jest.fn().mockResolvedValue(true),
            delete: jest.fn().mockResolvedValue(true),
          },
        },
      ],
    }).compile();

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

  it('should be defined with dependencies', () => {
    expect(userService).toBeDefined();
  });
});

The user.repository.ts:

@Repository(User)
export class UserRepository extends EntityRepository<User> {}

Why would that be happening? According to all other tutorials, it should work. Thanks.


Solution

  • if your UserService's constructor has
    private readonly repo: UserRepository

    then you should use provide: UserRepository because now your provider's token is a class references, not its name.