0
0
NestJSframework~5 mins

Unit testing controllers in NestJS

Choose your learning style9 modes available
Introduction

Unit testing controllers helps check if each part of your app that handles user requests works correctly on its own. It finds mistakes early and keeps your app reliable.

When you want to check if a controller returns the right response for a request.
When you want to test controller logic without running the whole app.
When you want to catch bugs in how controllers handle data or call services.
When you want to make sure changes in code don't break controller behavior.
When you want to write automated tests to save time in the future.
Syntax
NestJS
describe('ControllerName', () => {
  let controller: ControllerName;
  let service: ServiceName;

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      controllers: [ControllerName],
      providers: [
        {
          provide: ServiceName,
          useValue: { methodName: jest.fn() },
        },
      ],
    }).compile();

    controller = module.get<ControllerName>(ControllerName);
    service = module.get<ServiceName>(ServiceName);
  });

  it('should do something', () => {
    // test code here
  });
});

Use Test.createTestingModule to set up a test environment for your controller.

Mock services with useValue to isolate controller tests from real service logic.

Examples
This example tests a findAll method in a CatsController. The service is mocked to return a fixed list.
NestJS
describe('CatsController', () => {
  let controller: CatsController;
  let service: CatsService;

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      controllers: [CatsController],
      providers: [
        {
          provide: CatsService,
          useValue: { findAll: jest.fn().mockReturnValue(['cat1', 'cat2']) },
        },
      ],
    }).compile();

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

  it('should return an array of cats', () => {
    expect(controller.findAll()).toEqual(['cat1', 'cat2']);
  });
});
This example tests a create method that adds a user. The service mock returns the user with an ID.
NestJS
describe('UsersController', () => {
  let controller: UsersController;
  let service: UsersService;

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      controllers: [UsersController],
      providers: [
        {
          provide: UsersService,
          useValue: { createUser: jest.fn().mockImplementation(user => ({ id: 1, ...user })) },
        },
      ],
    }).compile();

    controller = module.get<UsersController>(UsersController);
    service = module.get<UsersService>(UsersService);
  });

  it('should create a user', () => {
    const userDto = { name: 'Alice' };
    expect(controller.create(userDto)).toEqual({ id: 1, name: 'Alice' });
  });
});
Sample Program

This test checks two controller methods: findAll returns a list of books, and findOne returns a single book by id. The service is mocked to return fixed values.

NestJS
import { Test } from '@nestjs/testing';
import { BooksController } from './books.controller';
import { BooksService } from './books.service';

describe('BooksController', () => {
  let controller: BooksController;
  let service: BooksService;

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      controllers: [BooksController],
      providers: [
        {
          provide: BooksService,
          useValue: {
            findAll: jest.fn().mockReturnValue(['Book A', 'Book B']),
            findOne: jest.fn().mockImplementation(id => `Book ${id}`),
          },
        },
      ],
    }).compile();

    controller = module.get<BooksController>(BooksController);
    service = module.get<BooksService>(BooksService);
  });

  it('should return all books', () => {
    expect(controller.findAll()).toEqual(['Book A', 'Book B']);
  });

  it('should return one book by id', () => {
    expect(controller.findOne('A')).toBe('Book A');
  });
});
OutputSuccess
Important Notes

Always mock services to keep controller tests focused and fast.

Use jest.fn() to create mock functions and control their return values.

Run tests often to catch errors early and keep your code healthy.

Summary

Unit testing controllers checks if they handle requests correctly by themselves.

Mock services to isolate controller logic from other parts.

Use NestJS testing tools like Test.createTestingModule and Jest mocks.