Skip to content
Advertisement

Inject TypeORM repository into NestJS service for mock data testing

There’s a longish discussion about how to do this in this issue.

I’ve experimented with a number of the proposed solutions but I’m not having much luck.

Could anyone provide a concrete example of how to test a service with an injected repository and mock data?

Advertisement

Answer

Let’s assume we have a very simple service that finds a user entity by id:

JavaScript

Then you can mock the UserRepository with the following mock factory (add more methods as needed):

JavaScript

Using a factory ensures that a new mock is used for every test.

JavaScript

For type safety and comfort you can use the following typing for your (partial) mocks (far from perfect, there might be a better solution when jest itself starts using typescript in the upcoming major releases):

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement