0
0
NestJSframework~5 mins

Unit testing services in NestJS - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the main goal of unit testing a service in NestJS?
To test the service's logic in isolation, ensuring each function works correctly without depending on other parts like databases or external APIs.
Click to reveal answer
beginner
How do you create a testing module for a service in NestJS?
Use Test.createTestingModule({ providers: [YourService] }).compile() to set up a module that provides the service for testing.
Click to reveal answer
intermediate
Why do we use mocks or spies in unit testing NestJS services?
Mocks replace real dependencies to isolate the service logic, while spies let us check if certain methods were called, helping us test behavior without side effects.
Click to reveal answer
intermediate
What Jest function is commonly used to create a spy on a method in NestJS service tests?
jest.spyOn(object, 'methodName') is used to spy on a method to track calls and control its behavior during tests.
Click to reveal answer
intermediate
How can you test asynchronous methods in a NestJS service?
Use async/await in your test functions and Jest's expect().resolves or expect().rejects to handle promises and verify async behavior.
Click to reveal answer
Which NestJS testing utility helps create a module for unit testing a service?
ATest.createTestingModule()
BModule.forRoot()
CService.register()
DAppModule.create()
What is the purpose of mocking dependencies in NestJS service tests?
ATo isolate the service logic from external parts
BTo add more features to the service
CTo speed up the app in production
DTo make the service dependent on real databases
Which Jest function lets you check if a method was called during a test?
Ajest.mock()
Bjest.fn()
Cjest.spyOn()
Djest.clearAllMocks()
How do you handle testing an async method in a NestJS service?
AUse setTimeout in tests
BUse callbacks only
CIgnore async behavior
DUse async/await and expect().resolves or expect().rejects
What does the compile() method do in Test.createTestingModule()?
ARuns the tests
BBuilds the testing module and resolves dependencies
CDeletes the module
DStarts the NestJS server
Explain how to set up and write a basic unit test for a NestJS service method.
Think about creating a testing module, getting the service, and writing a test function.
You got /5 concepts.
    Describe why and how you would mock a dependency in a NestJS service unit test.
    Focus on isolation and replacing real parts with fake ones.
    You got /5 concepts.