Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

510
Vistas
Tests fail when using @InjectRepository: Nest can't resolve Repository

I'm using NestJs with Typeorm, normal setup. UsersService gets the Typeorm Repository injected:

constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

In the UsersModule:

@Module({
  imports:[ TypeOrmModule.forFeature([User])],
  controllers: [UsersController ],
  providers: [UsersService]
})

Nothing special as you can see. But the auto-generated test for UsersService fails, no matter what I do:

describe('UsersService', () => {
  let service: UsersService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [UsersService],      
    }).compile();

    service = module.get<UsersService>(UsersService);
  });

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

I get the following error:

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

The solutions on Stackoverflow that I found seem to be obsolete, or over-complicated. I understand that the problem stems from the usage of @InjectRepository.

What is the solution? I tried downloading other people's fairly-similar projects, and get the same error! Both with nest 8 and 7.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Nest can't resolve the dependency because you don't provide the repository in the testing module. If you're doing unit tests you probably want to mock the repository using a custom provider:

 import { getRepositoryToken } from '@nestjs/typeorm';

 describe('UsersService', () => {
   let service: UsersService;
   let repository: Repository<User>;

   beforeEach(async () => {
     const module: TestingModule = await Test.createTestingModule({
       providers: [
         UsersService,
         {
           provide: getRepositoryToken(User),
           useValue: {},
         }
       ],      
     }).compile();

     service = module.get<UsersService>(UsersService);
   });

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

You can provide an object, a class or a factory function, more details in the doc: https://docs.nestjs.com/fundamentals/custom-providers

Then in your tests you can mock the methods of the repository this way:

jest.spyOn(repository, 'find').mockResolvedValueOnce([])

It's not the only way to mock, but that's a simple and standard one.

about 4 years ago · Juan Pablo Isaza Denunciar

0

The docs are pretty clear on how to write tests when using @nestjs/typeorm: https://docs.nestjs.com/techniques/database#testing

There are a bunch of samples here as well: https://github.com/jmcdo29/testing-nestjs

about 4 years ago · Juan Pablo Isaza Denunciar

0

So I managed to "solve" this myself. I should've mentioned perhaps that i didn't intend to do any mocking, but wanted the test to work "as is"(I prefer using a test-dedicated DB, rather than mocking units. Seems more realistic to me).

So it appears i kind of misunderstood, that every call to createTestingModule() needs to make sure all relevant dependencies are created, including stuff like ORM initialization, which is usually done in the AppModule(here i'm testing a service in UserModule..). So what I did in users.service.specs.ts:

const module: TestingModule = await Test.createTestingModule({
      imports: [TypeOrmModule.forFeature([User]), TypeOrmModule.forRoot({
        type: 'postgres',
        host: 'localhost',
        port: 5432,
        username: 'postgres',
        password: '',
        database: 'postgres',
        schema: 'test-db',
        entities: [User],
        synchronize: true,
      }), TypeOrmModule.forFeature([User])],
      providers: [UsersService],
    }).compile();

Notice that I had to both create the TypeOrm connection, and register the entity. Now I understand that each test suite is totally isolated, and therefore needs all relevant dependencies to be passed to it, even if in the "original" application this code is already imported in the root module.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda