Skip to main content

Command Palette

Search for a command to run...

Unit Tests for NestJS Controllers and Services

Published
2 min read
Unit Tests for NestJS Controllers and Services

Let's check how to write unit tests for NestJS controllers and services. Unit testing is an essential practice for ensuring the correctness and reliability of your API endpoints and business logic.

Writing Unit Tests for Controllers

Let's start by writing a unit test for a simple controller method. First, create a new controller:

nest generate controller cats

This will create a new cats.controller.ts file in the src directory. Now, let's write a unit test for the findAll method in the cats.controller.spec.ts file:

import { Test, TestingModule } from '@nestjs/testing';
import { CatsController } from './cats.controller';

describe('CatsController', () => {
  let controller: CatsController;
  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [CatsController],
    }).compile();
    controller = module.get<CatsController>(CatsController);
  });

  it('should be defined', () => {
    expect(controller).toBeDefined();
  });

  it('should return an array of cats', () => {
    expect(controller.findAll()).toEqual([]);
  });
});

Writing Unit Tests for Services

Next, let's write a unit test for a service method. First, create a new service:

nest generate service cats

This will create a new cats.service.ts file in the src directory. Now, let's write a unit test for the findAll method in the cats.service.spec.ts file:

import { Test, TestingModule } from '@nestjs/testing';
import { CatsService } from './cats.service';

describe('CatsService', () => {
  let service: CatsService;

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

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  it('should return an array of cats', () => {
    expect(service.findAll()).toEqual([]);
  });
});

Running Unit Tests

To run your unit tests, use the following command:

npm run test

This will execute all unit tests in your project and provide you with feedback on their success or failure.Unit testing is a crucial practice for ensuring the correctness and reliability of your API endpoints and business logic.

3 views

More from this blog

Brijesh Yadav

23 posts