Erez Hod
Erez Hod

Reputation: 1883

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.

Upvotes: 1

Views: 2429

Answers (2)

Micael Levi
Micael Levi

Reputation: 6675

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.

Upvotes: 1

Martin Ad&#225;mek
Martin Ad&#225;mek

Reputation: 18389

Nest 8 changed the way DI works, it was using string tokens before, but now it uses class references instead. The nest MikroORM adapter does register both string token and class reference for custom repositories. Here you are registering the repository yourself, so you either need to register it both ways or at least the way you use.

Importing via the type requires the class reference way. Importing via @InjectRepository() requires the string token. forFeature() call registers them both in case the entity has a custom repository class.

https://github.com/mikro-orm/nestjs/blob/e51206762f9eb3e96bfc9edbb6abbf7ae8bc08a8/src/mikro-orm.providers.ts#L82-L94

So either add the provide: UserRepository as suggested in the other answer, or use @InjectRepository() decorator.

Upvotes: 1

Related Questions