3
votes

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.

1

1 Answers

6
votes

getRepositoryToken() is a helper method that allows you to get the same injection token that @InjectReposiotry() 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 tat 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.