Testing Intro

Nest's Test.createTestingModule builds an isolated module so you can unit-test providers with mocks.

SyntaxTest.createTestingModule({ providers }).compile()

Nest is built for testability. The @nestjs/testing package provides Test.createTestingModule(), which builds a module just like the real one but lets you swap in mocks.

Unit-testing a service

  1. Create a testing module listing the provider under test.
  2. Override its dependencies with fakes using useValue.
  3. Resolve the provider with module.get() and assert on its behavior.

Because everything is injected, no real database or network is needed.

Example

Example Β· typescript
import { Test } from '@nestjs/testing';
import { UsersService } from './users.service';

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

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

    service = moduleRef.get(UsersService);
  });

  it('returns users', () => {
    expect(service.findAll()).toBeDefined();
  });
});

When to use it

  • A developer unit-tests a CatsService by creating a testing module that provides a mock CatsRepository so no real database is needed.
  • A team writes controller tests using Test.createTestingModule to verify that the controller calls the correct service method with the right arguments.
  • An engineer uses supertest with the real NestJS HTTP server in e2e tests to verify the full request-response cycle including guards and pipes.

More examples

Unit test a service with mock repo

Creates an isolated testing module with a mock repository token so CatsService can be tested without a real database.

Example Β· ts
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,
        { provide: getRepositoryToken(Cat), useValue: { find: jest.fn(() => []) } },
      ],
    }).compile();
    service = module.get<CatsService>(CatsService);
  });

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

Unit test a controller

Tests the controller in isolation by providing a mock service, asserting that the controller delegates to the service and returns its value.

Example Β· ts
const mockCatsService = { findAll: jest.fn(() => ['cat']) };

const module = await Test.createTestingModule({
  controllers: [CatsController],
  providers: [{ provide: CatsService, useValue: mockCatsService }],
}).compile();

const controller = module.get<CatsController>(CatsController);

it('findAll returns array', () => {
  expect(controller.findAll()).toEqual(['cat']);
  expect(mockCatsService.findAll).toHaveBeenCalled();
});

E2E test with supertest

Boots the real NestJS app and uses supertest to fire an HTTP request, verifying the full pipeline including middleware and guards.

Example Β· ts
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';

describe('AppController (e2e)', () => {
  let app;

  beforeAll(async () => {
    const module = await Test.createTestingModule({ imports: [AppModule] }).compile();
    app = module.createNestApplication();
    await app.init();
  });

  it('GET / returns Hello World', () => {
    return request(app.getHttpServer())
      .get('/')
      .expect(200)
      .expect('Hello World!');
  });

  afterAll(() => app.close());
});

Discussion

  • Be the first to comment on this lesson.