Bird
Raised Fist0
NestJSframework~20 mins

Unit testing controllers in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
NestJS Controller Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this NestJS controller unit test?
Consider this simple NestJS controller and its unit test. What will the test output be when run?
NestJS
import { Test, TestingModule } from '@nestjs/testing';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';

class MockCatsService {
  findAll() {
    return ['cat1', 'cat2'];
  }
}

describe('CatsController', () => {
  let catsController: CatsController;

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

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

  it('should return an array of cats', () => {
    expect(catsController.findAll()).toEqual(['cat1', 'cat2']);
  });
});
AThe test passes because the controller returns ['cat1', 'cat2'] as expected.
BThe test fails because the controller returns an empty array.
CThe test throws a runtime error because CatsService is not defined.
DThe test fails due to a syntax error in the test setup.
Attempts:
2 left
💡 Hint
Look at how the service is mocked and injected into the controller.
📝 Syntax
intermediate
2:00remaining
Which option correctly mocks a service method in a NestJS controller test?
You want to mock the 'create' method of a service in your NestJS controller unit test. Which option correctly sets up the mock?
NestJS
const mockService = {
  create: jest.fn().mockReturnValue('created'),
};
Aconst mockService = { create: jest.fn().mockReturnValue('created') };
Bconst mockService = { create: jest.mockReturnValue('created') };
Cconst mockService = { create: () => 'created' };
Dconst mockService = { create: jest.fn().returns('created') };
Attempts:
2 left
💡 Hint
Check the Jest syntax for mocking functions.
🔧 Debug
advanced
2:00remaining
Why does this NestJS controller test fail with 'TypeError: Cannot read property'?
Given this test code, why does it throw a TypeError when calling the controller method?
NestJS
describe('UsersController', () => {
  let usersController: UsersController;
  let usersService: UsersService;

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      controllers: [UsersController],
      providers: [UsersService],
    }).compile();

    usersController = module.get<UsersController>(UsersController);
    // usersService is not assigned here
  });

  it('should call service method', () => {
    jest.spyOn(usersService, 'findAll').mockReturnValue(['user1']);
    expect(usersController.findAll()).toEqual(['user1']);
  });
});
ABecause jest.spyOn is used incorrectly on a non-function.
BBecause the controller method findAll does not exist.
CBecause usersService is undefined, so jest.spyOn fails with TypeError.
DBecause the test module did not compile correctly.
Attempts:
2 left
💡 Hint
Check if usersService is assigned before using it.
❓ state_output
advanced
2:00remaining
What is the value of 'result' after this NestJS controller test runs?
In this test, what will be the value of 'result' after calling the controller method?
NestJS
class MockService {
  getData() {
    return { count: 5 };
  }
}

let result;

describe('DataController', () => {
  let controller;

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      controllers: [DataController],
      providers: [{ provide: DataService, useClass: MockService }],
    }).compile();

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

  it('should set result to service data', () => {
    result = controller.getData();
  });
});
AAn empty object {}
Bundefined
Cnull
D{ count: 5 }
Attempts:
2 left
💡 Hint
Look at what the mock service returns and what the controller calls.
🧠 Conceptual
expert
2:00remaining
Which option best explains why mocking dependencies is important in NestJS controller unit tests?
Why do we mock service dependencies when unit testing NestJS controllers?
ATo speed up tests by running the full application stack including databases.
BTo isolate the controller logic and avoid testing external service implementations or side effects.
CTo ensure the controller uses the real service methods for integration testing.
DTo avoid writing any test code for services and focus only on controllers.
Attempts:
2 left
💡 Hint
Think about what unit testing means and why isolation matters.

Practice

(1/5)
1. What is the main purpose of unit testing a controller in NestJS?
easy
A. To verify the controller handles requests correctly without depending on other parts
B. To test the database connection and queries
C. To check the UI rendering of the application
D. To measure the performance of the entire application

Solution

  1. Step 1: Understand the role of a controller

    Controllers handle incoming requests and return responses, so testing them focuses on this behavior.
  2. Step 2: Identify what unit testing isolates

    Unit testing isolates the controller from other parts like services or databases to test its logic alone.
  3. Final Answer:

    To verify the controller handles requests correctly without depending on other parts -> Option A
  4. Quick Check:

    Unit testing controller logic = To verify the controller handles requests correctly without depending on other parts [OK]
Hint: Controllers handle requests; test them isolated from services [OK]
Common Mistakes:
  • Confusing unit tests with integration tests
  • Testing database or UI in controller unit tests
  • Ignoring mocking dependencies
2. Which of the following is the correct way to create a testing module for a controller in NestJS?
easy
A. const module = Test.createModule({ providers: [MyController] });
B. const module = new Module({ controllers: [MyController] });
C. const module = await Test.createTestingModule({ controllers: [MyController] }).compile();
D. const module = await Test.createTestingModule({ services: [MyController] }).compile();

Solution

  1. Step 1: Recall NestJS testing syntax

    Use Test.createTestingModule with a config object specifying controllers or providers, then compile it.
  2. Step 2: Identify correct property for controllers

    The property to register controllers is 'controllers', not 'services' or 'providers' for controllers.
  3. Final Answer:

    const module = await Test.createTestingModule({ controllers: [MyController] }).compile(); -> Option C
  4. Quick Check:

    Use controllers array in createTestingModule = const module = await Test.createTestingModule({ controllers: [MyController] }).compile(); [OK]
Hint: Use controllers: [] inside Test.createTestingModule [OK]
Common Mistakes:
  • Using 'services' instead of 'controllers' key
  • Forgetting to await compile()
  • Using new Module() instead of Test.createTestingModule
3. Given this controller method and test snippet, what will result be?
class MyController {
  getHello() {
    return 'Hello World!';
  }
}

// Test snippet
const controller = new MyController();
const result = controller.getHello();
medium
A. null
B. undefined
C. An error because getHello is async
D. 'Hello World!'

Solution

  1. Step 1: Analyze the controller method

    The method getHello returns the string 'Hello World!' synchronously.
  2. Step 2: Check the test call

    Calling getHello() directly returns the string without errors or async behavior.
  3. Final Answer:

    'Hello World!' -> Option D
  4. Quick Check:

    Direct method call returns string = 'Hello World!' [OK]
Hint: Direct call returns method's return value immediately [OK]
Common Mistakes:
  • Assuming async behavior without async keyword
  • Expecting undefined if not mocked
  • Confusing method call with property access
4. What is wrong with this unit test for a NestJS controller?
describe('MyController', () => {
  let controller: MyController;

  beforeEach(() => {
    controller = new MyController();
  });

  it('should return greeting', () => {
    expect(controller.getHello()).toBe('Hello World!');
  });
});
medium
A. The controller is not created using Test.createTestingModule
B. The test does not mock the service dependency
C. The test is missing async keyword
D. The expect statement uses toBe instead of toEqual

Solution

  1. Step 1: Check controller instantiation

    Creating controller directly is allowed but only if it has no dependencies.
  2. Step 2: Identify missing mocking

    If the controller depends on a service, it must be mocked to isolate controller logic.
  3. Final Answer:

    The test does not mock the service dependency -> Option B
  4. Quick Check:

    Missing mocks for dependencies = The test does not mock the service dependency [OK]
Hint: Always mock services when testing controllers with dependencies [OK]
Common Mistakes:
  • Assuming direct instantiation is always wrong
  • Forgetting to mock injected services
  • Confusing toBe and toEqual for strings
5. You want to unit test a NestJS controller method that calls a service method returning a promise. Which approach correctly mocks the service to test the controller method synchronously?
hard
A. Mock the service method with jest.fn().mockResolvedValue(value) and await the controller method in the test
B. Mock the service method with jest.fn().mockReturnValue(value) without async/await
C. Call the real service method without mocking to test actual behavior
D. Mock the service method with jest.fn().mockImplementation(() => { throw new Error(); })

Solution

  1. Step 1: Understand async service method

    The service method returns a promise, so the mock must simulate a resolved promise.
  2. Step 2: Use jest.fn().mockResolvedValue

    This creates a mock that returns a resolved promise with the given value, allowing the controller method to await it.
  3. Step 3: Await controller method in test

    The test must await the controller method to handle the async call properly.
  4. Final Answer:

    Mock the service method with jest.fn().mockResolvedValue(value) and await the controller method in the test -> Option A
  5. Quick Check:

    Use mockResolvedValue and await async calls = Mock the service method with jest.fn().mockResolvedValue(value) and await the controller method in the test [OK]
Hint: Use mockResolvedValue for async mocks and await calls [OK]
Common Mistakes:
  • Using mockReturnValue for async methods
  • Not awaiting async controller methods
  • Testing real service instead of mocking
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard