Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

513
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda