Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

507
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!