0
0
NestJSframework~20 mins

Unit testing controllers in NestJS - Practice Problems & Coding Challenges

Choose your learning style9 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.