Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is getRepositoryToken in nestjs typeorm and when to use it?

The docs here are as below:

When it comes to unit testing an application, we usually want to avoid making a database connection, keeping our test suites independent and their execution process as fast as possible. But our classes might depend on repositories that are pulled from the connection instance. How do we handle that? The solution is to create mock repositories. In order to achieve that, we set up custom providers. Each registered repository is automatically represented by a Repository token, where EntityName is the name of your entity class.

The @nestjs/typeorm package exposes the getRepositoryToken() function which returns a prepared token based on a given entity.

What does that even mean? Autocomplete docs just give the signature with no explanation.

like image 456
Urasquirrel Avatar asked Jan 04 '21 22:01

Urasquirrel


1 Answers

getRepositoryToken() is a helper method that allows you to get the same injection token that @InjectRepository() returns. This is useful when it comes to tests so that you can define a custom provider that has a matching token for the DI resolution, and so you can provide a mock of the Repository methods without the need to actually talk to the database. So for example, if you have

@Injectable()
export class FooService {
  constructor(@InjectRepository(Foo) private readonly fooRepo: Repository<Foo>) {}

}

In your test you can add the provider

{
  provide: getRepositoryToken(Foo),
  useValue: {
    find: jest.fn(),
    insert: jest.fn(),
  },
}

And now you've got a mock injectable provider for the Repository.

The biggest reason that things have to be done this way is because typescript doesn't reflect generic classes, it only reflects Repository, and if Nest tries to figure out which repository you mean to inject, with just that name (Repository) it's most likely going to get it wrong and inject the wrong class. Using @InjectRepsitory() allows for setting the proper injection token.

like image 57
Jay McDoniel Avatar answered Sep 21 '22 15:09

Jay McDoniel