Lesson 23 / 33

Testing

Unit tests with Jest, integration tests, and test utilities.

Unit test with mocked dependencies

Use Test.createTestingModule() to mock and test in isolation.

import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from './users.service';

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

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        {
          provide: UsersService,
          useValue: { findAll: jest.fn().mockReturnValue([]) }
        }
      ]
    }).compile();
    service = module.get<UsersService>(UsersService);
  });

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

E2E test

Test the full request/response cycle with supertest.

import { Test, TestingModule } from '@nestjs/testing';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';

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

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

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