0
0
NestJSframework~10 mins

Unit testing services in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Unit testing services
Write test case
Create testing module
Inject service
Call service method
Check result with expect()
Pass or fail test
Repeat for other methods
This flow shows how to write and run a unit test for a NestJS service step-by-step.
Execution Sample
NestJS
describe('CatsService', () => {
  let service: CatsService;

  beforeEach(async () => {
    const module = await Test.createTestingModule({ providers: [CatsService] }).compile();
    service = module.get<CatsService>(CatsService);
  });

  it('should return all cats', () => {
    expect(service.findAll()).toEqual(['cat1', 'cat2']);
  });
});
This code sets up a test for CatsService and checks if findAll() returns the expected list.
Execution Table
StepActionEvaluationResult
1Create testing module with CatsServiceModule createdModule instance ready
2Get CatsService instance from moduleService injectedservice variable assigned
3Call service.findAll()Returns ['cat1', 'cat2']Output: ['cat1', 'cat2']
4Compare output with expect()Output matches expectedTest passes
5End of test caseNo more testsTest suite completes
💡 All test cases executed, no failures
Variable Tracker
VariableStartAfter Step 2After Step 3Final
serviceundefinedCatsService instanceCatsService instanceCatsService instance
outputundefinedundefined['cat1', 'cat2']['cat1', 'cat2']
Key Moments - 3 Insights
Why do we create a testing module before getting the service?
The testing module simulates NestJS dependency injection, so the service can be properly created and injected as in the real app. See Step 1 and 2 in execution_table.
What does expect(service.findAll()).toEqual(...) check?
It checks if the service method returns exactly the expected value. If it matches, the test passes (Step 4).
Why do we use beforeEach() to create the module and service?
beforeEach() runs before every test to ensure a fresh service instance, avoiding shared state between tests. This keeps tests independent.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'service' after Step 2?
Anull
BCatsService instance
Cundefined
DArray of cats
💡 Hint
Check the 'service' variable in variable_tracker after Step 2
At which step does the test check if the output matches the expected value?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Action' and 'Result' columns in execution_table for the expect() call
If the service.findAll() returned ['cat1'] instead of ['cat1', 'cat2'], what would happen at Step 4?
ATest fails
BTest passes
CService instance changes
DModule creation fails
💡 Hint
Step 4 compares output with expected value; mismatch causes failure
Concept Snapshot
Unit testing services in NestJS:
- Use Test.createTestingModule to build a test module
- Inject service with module.get()
- Call service methods inside it() blocks
- Use expect() to check outputs
- Use beforeEach() for fresh setup
- Tests pass if outputs match expected values
Full Transcript
Unit testing services in NestJS involves creating a testing module that mimics the real app environment. We inject the service we want to test from this module. Then, we call the service methods and check their outputs using expect(). The beforeEach() function ensures each test runs with a fresh service instance. If the output matches what we expect, the test passes. This process helps us verify that our service behaves correctly in isolation.