Mocking a NestJS Service with many dependencies - is there a cleaner way of doing so?

186 Views Asked by At

I'm writing unit tests for a NestJS Controller and I'm trying to mock its Service. My test suite currently works fine and my tests are passing, but I was wondering if there was a cleaner way to mock the Service as opposed to the current approach I've taken.

I followed the documentation on the NestJS website and defined a mock factory to apply to all of my missing dependencies (NestJS says this is useful for cases where you have a large number of dependencies in a class and mocking all of them will take a long time and a lot of setup). With this mock factory approach, I'm manually mocking every single method I have in my service, example: { findAll: jest.fn(), question: jest.fn(), questions: jest.fn() }. Is there a cleaner way of mocking this Service, without having to manually declare each method in that Service to be equal to a jest.fn()?

I've added an image of my code. Thanks all!

code screenshot

0

There are 0 best solutions below