0
0
NestJSframework~10 mins

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

Choose your learning style9 modes available
Concept Flow - Unit testing controllers
Write test case
Setup testing module
Inject controller
Mock dependencies
Call controller method
Assert expected result
Test passes or fails
This flow shows how a unit test for a NestJS controller is written, setting up the test module, injecting the controller, mocking dependencies, calling methods, and checking results.
Execution Sample
NestJS
describe('CatsController', () => {
  let controller: CatsController;

  const mockCatsService = {
    findAll: jest.fn(),
  };

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      controllers: [CatsController],
      providers: [{ provide: CatsService, useValue: mockCatsService }],
    }).compile();

    controller = module.get<CatsController>(CatsController);
  });

  it('should return all cats', async () => {
    jest.spyOn(mockCatsService, 'findAll').mockResolvedValue(['cat1', 'cat2']);
    const result = await controller.findAll();
    expect(result).toEqual(['cat1', 'cat2']);
  });
});
This test sets up a NestJS testing module, injects the CatsController with a mocked CatsService, calls the findAll method, and checks the returned cats.
Execution Table
StepActionEvaluationResult
1Create testing module with CatsController and mockCatsServiceModule createdTesting module ready
2Get CatsController instance from moduleController injectedcontroller variable assigned
3Mock CatsService.findAll to return ['cat1', 'cat2']Mock appliedfindAll returns ['cat1', 'cat2']
4Call controller.findAll()Calls mocked serviceReturns ['cat1', 'cat2']
5Assert result equals ['cat1', 'cat2']Check equalityTest passes
💡 Test completes after assertion; passes if result matches expected array
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
controllerundefinedCatsController instanceCatsController instance with mocked serviceResult of findAll call pendingResult is ['cat1', 'cat2']
mockCatsService.findAllundefinedundefinedMocked to return ['cat1', 'cat2']Returns ['cat1', 'cat2']Returns ['cat1', 'cat2']
Key Moments - 3 Insights
Why do we mock the service instead of using the real one?
We mock the service to isolate the controller's behavior and avoid dependencies on external data or logic, as shown in step 3 of the execution_table.
How does the controller get the mocked service?
The mocked service is provided in the testing module setup (step 1), so when the controller is injected (step 2), it uses the mock instead of the real service.
What happens if the controller method returns a different result than expected?
The assertion in step 5 will fail, causing the test to fail, indicating a problem in the controller or mock setup.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'controller' after step 2?
AMockCatsService instance
BCatsController instance
Cundefined
DArray of cats
💡 Hint
Check the variable_tracker row for 'controller' after Step 2
At which step is the CatsService.findAll method mocked?
AStep 3
BStep 2
CStep 4
DStep 5
💡 Hint
Look at the 'Action' column in execution_table for mocking
If the mock returned an empty array instead of ['cat1', 'cat2'], what would change in the execution_table?
AStep 5 assertion would pass
BStep 3 would fail
CStep 4 result would be [] instead of ['cat1', 'cat2']
DController would not be injected
💡 Hint
Check the 'Result' column for Step 4 and how it affects the assertion in Step 5
Concept Snapshot
Unit testing controllers in NestJS:
- Use Test.createTestingModule to set up test environment
- Provide controller and mock dependencies
- Inject controller instance
- Mock service methods with jest.spyOn
- Call controller methods and assert results
- Isolate controller logic from real services
Full Transcript
Unit testing controllers in NestJS involves creating a testing module that includes the controller and mocks of its dependencies. The controller is injected from this module. Service methods are mocked to control their output. The controller method is called, and its output is checked against expected results. This isolates the controller's logic and ensures it behaves correctly without relying on real services or databases.