When building API's in Nest, I often come across an issue where a particular API might need to make use of several Nest modules to do it's job. I'd like to know if there's a better way to structure my modules so that unit testing them is easier.
For example, imagine we have an OrderService. The OrderService makes use of a few different dependencies in order to do it's job:
- It uses the
ProductsServicein order to look up product details and prices. - It uses the
UsersServicein order to look up customer information, such as a Stripe customer ID. - It uses a Typeorm to handle writing the
Orderinto the database - And finally, let's say it uses a
CouponsServicein order to look up and validate coupon details for theOrder.
For the sake of this example, let's just imagine each of these 4 dependencies to be it's own Nest module.
When it comes to unit testing the OrdersService, I'd then need to stub out 4 different dependencies. This seems like a lot more work than it should be, and so I realized there must be a better way.
One thing that I've tried doing is creating separate helper files for setting up each services mocks. This cuts down on the amount of boilerplate for each service that uses a particular dependency, but you still end up in a situation where 1 service might have 4 different dependencies.
Ideally, I'd like to implement some pattern or structure so that when I test a file, the dependencies are either really simple or automatic to mock, or a particular file only has 1 dependency at a time, without oversimplifying the system.
My question really boils down to:
How do you handle many dependencies like this in a Service, without ending up in a situation where testing a function requires you to mock 4+ methods. I'd love to hear a Nest specific way to do this, but I'd also appreciate any generic software engineering examples or patterns to look into as well.