0
0
NestjsHow-ToBeginner ยท 4 min read

How to Test NestJS Application: Simple Guide with Examples

To test a NestJS application, use the built-in TestingModule from @nestjs/testing to create a test environment and write tests with Jest. This setup allows you to test services, controllers, and modules in isolation with mock dependencies.
๐Ÿ“

Syntax

Testing in NestJS uses TestingModule to create a test environment. You import the module or service you want to test, then use Test.createTestingModule() to build it. Use compile() to finalize the module and get() to retrieve the service or controller instance for testing.

Tests are written with Jest using describe and it blocks.

typescript
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 be defined', () => {
    expect(service).toBeDefined();
  });
});
๐Ÿ’ป

Example

This example shows how to test a simple CalculatorService with a method add. It demonstrates setting up the test module, injecting the service, and writing a test case to check the addition result.

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

class CalculatorService {
  add(a: number, b: number): number {
    return a + b;
  }
}

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 correctly', () => {
    expect(service.add(2, 3)).toBe(5);
  });
});
Output
PASS ./calculator.service.spec.ts CalculatorService โœ“ should add two numbers correctly (5 ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 1.234 s
โš ๏ธ

Common Pitfalls

Common mistakes when testing NestJS applications include:

  • Not compiling the testing module before getting services or controllers.
  • Forgetting to mock dependencies, causing tests to fail or behave unpredictably.
  • Testing asynchronous methods without async/await or proper promises handling.
  • Not resetting mocks or test state between tests, leading to flaky tests.

Always use beforeEach to set up a fresh module and mock dependencies as needed.

typescript
/* Wrong way: Missing compile() and no mock */
const module = Test.createTestingModule({ providers: [MyService] });
const service = module.get(MyService); // Error: module not compiled

/* Right way: */
const module = await Test.createTestingModule({ providers: [MyService] }).compile();
const service = module.get(MyService);
๐Ÿ“Š

Quick Reference

Tips for effective NestJS testing:

  • Use @nestjs/testing to create isolated test modules.
  • Mock external dependencies to keep tests focused and fast.
  • Use beforeEach to reset state before each test.
  • Write clear, small test cases for each function or behavior.
  • Run tests with npm run test or jest command.
โœ…

Key Takeaways

Use TestingModule from @nestjs/testing to create a test environment for your NestJS components.
Always compile the testing module before retrieving services or controllers.
Mock dependencies to isolate the unit under test and avoid side effects.
Write tests with Jest using async/await for asynchronous code.
Reset test state in beforeEach to keep tests independent and reliable.