0
0
NestJSframework~5 mins

Unit testing controllers in NestJS - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the main purpose of unit testing controllers in NestJS?
To verify that the controller methods handle requests correctly and interact properly with services, without involving external dependencies.
Click to reveal answer
beginner
Which NestJS testing utility helps create a testing module for controllers?
The Test.createTestingModule() method is used to build a testing module that can include controllers and mocked providers.
Click to reveal answer
intermediate
Why do we mock services when unit testing controllers?
Mocking services isolates the controller logic by replacing real service calls with fake ones, ensuring tests focus only on controller behavior.
Click to reveal answer
intermediate
How do you test a controller method that returns a promise in NestJS?
Use async/await in the test function to wait for the promise to resolve, then assert the returned value or behavior.
Click to reveal answer
intermediate
What is a common pattern to verify that a controller calls a service method correctly?
Use Jest spies or mocks to check if the service method was called with expected arguments when the controller method runs.
Click to reveal answer
What does Test.createTestingModule() do in NestJS unit tests?
ACreates a module for testing with controllers and providers
BRuns the entire application
CMocks HTTP requests automatically
DGenerates database schemas
Why should services be mocked when unit testing controllers?
ATo speed up database queries
BTo test the service logic instead
CTo isolate controller logic and avoid external dependencies
DTo automatically generate test data
Which Jest feature helps verify if a service method was called by a controller?
Ajest.resetModules()
Bjest.mock()
Cjest.clearAllMocks()
Djest.spyOn()
How do you handle asynchronous controller methods in tests?
AIgnore the promise and test synchronously
BUse async/await to wait for the promise
CUse setTimeout to delay assertions
DConvert promises to callbacks
What is the best practice for testing controller methods that depend on services?
AMock the services to isolate controller logic
BUse real services with a test database
CSkip testing those methods
DTest only the services, not the controllers
Explain how to set up a unit test for a NestJS controller method that calls a service.
Think about isolating the controller by mocking dependencies.
You got /5 concepts.
    Describe why mocking is important in unit testing NestJS controllers and how it improves test quality.
    Consider what happens if you don’t mock services in unit tests.
    You got /4 concepts.