0
0
NestJSframework~5 mins

Unit testing services in NestJS

Choose your learning style9 modes available
Introduction

Unit testing services helps you check if each part of your app works right by itself. It finds mistakes early so your app stays reliable.

When you want to check if a service method returns the correct result.
When you change service code and want to make sure nothing breaks.
When you want to test service logic without running the whole app.
When you want to catch bugs before users see them.
When you want to write safe, maintainable code that others can trust.
Syntax
NestJS
import { Test, TestingModule } from '@nestjs/testing';
import { MyService } from './my.service';

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

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

    service = module.get<MyService>(MyService);
  });

  it('should do something', () => {
    expect(service.someMethod()).toBe(expectedValue);
  });
});

Use Test.createTestingModule to create a test environment for your service.

Use module.get to get the service instance for testing.

Examples
This tests the add method of a calculator service.
NestJS
import { Test, TestingModule } from '@nestjs/testing';
import { CalculatorService } from './calculator.service';

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

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

    service = module.get<CalculatorService>(CalculatorService);
  });

  it('should add two numbers', () => {
    expect(service.add(2, 3)).toBe(5);
  });
});
This shows how to mock a dependency when testing a service.
NestJS
import { Test, TestingModule } from '@nestjs/testing';
import { UserService } from './user.service';

// Mock dependency
const mockUserRepository = {
  findOne: jest.fn().mockReturnValue({ id: 1, name: 'Alice' }),
};

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

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        UserService,
        { provide: 'UserRepository', useValue: mockUserRepository },
      ],
    }).compile();

    service = module.get<UserService>(UserService);
  });

  it('should return user by id', async () => {
    const user = await service.findUserById(1);
    expect(user.name).toBe('Alice');
  });
});
Sample Program

This test checks if the multiply method in MathService returns the correct product of two numbers.

NestJS
import { Test, TestingModule } from '@nestjs/testing';

class MathService {
  multiply(a: number, b: number): number {
    return a * b;
  }
}

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

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

    service = module.get<MathService>(MathService);
  });

  it('should multiply two numbers correctly', () => {
    const result = service.multiply(4, 5);
    expect(result).toBe(20);
  });
});
OutputSuccess
Important Notes

Always test one small piece of logic per test to keep tests clear.

Use mocks to replace dependencies so tests focus only on the service.

Run tests often to catch errors early.

Summary

Unit testing services checks if each service works alone.

Use NestJS testing tools to create a test module and get the service.

Mock dependencies to isolate service logic during tests.