Home > front end >  Tests fail when using @InjectRepository: Nest can't resolve Repository
Tests fail when using @InjectRepository: Nest can't resolve Repository

Time:02-01

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.

CodePudding user response:

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

CodePudding user response:

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.

  •  Tags:  
  • Related