How to test a controller with a service that has @Inject in its constructor?
See original GitHub issueI have a question regarding testing as described on https://docs.nestjs.com/advanced/unit-testing:
beforeEach(async () => {
const module = await Test.createTestingModule({
controllers: [CatsController],
components: [CatsService],
}).compile();
catsService = module.get<CatsService>(CatsService);
catsController = module.get<CatsController>(CatsController);
});
The CatService is quite simple. How about this?
constructor(@Inject(CAT_MODEL_TOKEN) private readonly catModel: Model<Cat>) {}
How are we supposed to provide the catModel to CatsService in beforeEach? Without providing any parameters I get an error:
Nest can’t resolve dependencies of the CatsService. Please verify whether all of them are available in the current context.
Issue Analytics
- State:
- Created 6 years ago
- Comments:33 (4 by maintainers)
Top Results From Across the Web
node.js - How to unit test Controller and mock @InjectModel in ...
I am testing my API using the @injectModel and another service. Here's the snippet: import { CategoriesService } from './.
Read more >Testing your controllers when you have a decoupled core
We need a way to inject this mock into the controller as a constructor argument. This should only happen when the controller is...
Read more >Dependency injection into controllers in ASP.NET Core
ASP.NET Core MVC controllers request dependencies explicitly via constructors. ASP.NET Core has built-in support for dependency injection (DI).
Read more >Make services unit testable using dependency injection
We will use Mockito to provide and inject mock objects into WatchlistService . We will use these annotations:
Read more >Spring Boot Unit Testing | Code With Arho
The solution is not to use field injection at all. Instead, we should use constructor injection: @Service public class OrderService ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@adrien2p finally 💃 problem solved, thank you so much.
Not sure if it’s still relevant after a year, but when you are unit testing your controller, you don’t want to worry about it’s dependencies so you mock them out by doing:
so when your CatsService changes you don’t have to update it in every single place you use it.