Skip to content
NestPath

Testing (Unit + E2E)

Prove it works. Unit tests with mocked models, bcrypt and ExecutionContext fakes; E2E journeys on an in-memory MongoDB through the real AppModule; and the framework for deciding what to test where.

Alright, final boss. You've built everything — middleware, guards, interceptors, pipes, controllers, services, filters, MongoDB, JWT auth, Swagger. But right now, you're verifying your code works by hitting Swagger manually and hoping for the best. That's not testing. That's praying with extra steps.


The Problem You Have Right Now

Every time you change something — refactor a service method, update a DTO, tweak the auth flow — you manually:

  1. Start the server
  2. Open Swagger
  3. Register a user
  4. Login
  5. Copy the token
  6. Hit each endpoint
  7. Check responses visually
  8. Repeat for edge cases

That's 15 minutes minimum per change. You make 20 changes a day. That's 5 hours of manual testing per day. In a week, you've wasted more time testing than you spent coding. And you're still missing edge cases because humans forget.

Automated tests run in seconds, cover every edge case, and run on every commit. You write them once, they protect you forever.

Analogy

Manually clicking through every endpoint after each change is like a car maker rolling every single car off the line and personally driving it around the block before shipping it. Nobody does that. They run crash tests and rigs that repeat the exact same checks in seconds, flawlessly, on every unit, forever. Automated tests are your crash-test lab.


Testing in NestJS — Two Types

Unit Tests (.spec.ts)

Test individual pieces in isolation. A service method, a guard, a pipe — ripped out of the application, mocked dependencies injected, tested alone.

Analogy

A unit test is crash-testing one component on a rig. You bolt just the door onto a machine, slam it ten thousand times, and measure — no engine, no wheels, no road, all of that faked by the rig (your mocks). You learn whether that one part is sound without ever building the whole car.

  • Fast — no database, no HTTP, no server startup
  • Focused — tests one thing at a time
  • Mocked — all dependencies are fake/simulated
  • File convention: tasks.service.spec.ts next to tasks.service.ts

E2E Tests (.e2e-spec.ts)

Test the entire application as a real client would. Real HTTP requests, real pipeline (middleware → guards → interceptors → pipes → controllers → services), real database (test instance).

Analogy

An E2E test is driving the fully assembled car on a closed test track. Engine running, real steering, real brakes, at real speed — you find out whether the parts that each passed on their own rig actually work together. The in-memory MongoDB is that private test track: real driving, but nowhere near public roads (your production data).

  • Slow — spins up the app, connects to DB
  • Realistic — tests the full request lifecycle
  • Integration — catches issues between layers that unit tests miss
  • File convention: test/ folder at project root

Which to write first?

E2E tests first. Hot take, but hear me out. You're a product-minded developer. E2E tests tell you "does the feature work from the user's perspective?" Unit tests tell you "does this internal function work?" If you have limited time, E2E tests catch more real-world bugs. Unit tests are for when you need to verify complex business logic in isolation.

The testing pyramid says "lots of unit tests, few E2E tests." Reality says "E2E tests catch the bugs that actually ship to production." Write both. But start with E2E.


Testing Stack

NestJS comes pre-configured with:

  • Jest — Test runner and assertion library
  • @nestjs/testing — NestJS testing utilities (Test.createTestingModule)
  • Supertest — HTTP assertions for E2E tests
bash
# These should already be in your devDependencies from nest new
# If not:
npm install -D jest @nestjs/testing supertest @types/jest @types/supertest ts-jest

Also install for MongoDB testing:

bash
npm install -D mongodb-memory-server

mongodb-memory-server — Spins up a real MongoDB instance in memory for tests. No external MongoDB needed. Starts fast, isolated per test suite, auto-cleaned. Your tests don't touch your development database. Ever.

Analogy

This is a temporary test track that the crew builds fresh each morning and bulldozes each night. It behaves exactly like a real road (it's a real MongoDB), but it's fenced off from the public highway, so you can drive recklessly, crash on purpose, and wipe it clean — never once risking a real commuter's car.


Project Structure — Test Files

nestjs-tasks-api
src
auth
auth.controller.ts
auth.service.ts
auth.service.spec.tsunit test
dto
tasks
tasks.controller.ts
tasks.service.ts
tasks.service.spec.tsunit test
dto
common
guards
auth.guard.ts
auth.guard.spec.tsunit test
interceptors
transform.interceptor.ts
transform.interceptor.spec.tsunit test
users
users.service.ts
users.service.spec.tsunit test
test
app.e2e-spec.tse2e: full auth + tasks flow
auth.e2e-spec.tse2e: auth endpoints
tasks.e2e-spec.tse2e: task CRUD endpoints
setup.tse2e: shared setup/teardown
jest-e2e.jsone2e: jest config

Configuration Files First

jest config in package.json — Unit tests

json
{
  "jest": {
    "moduleFileExtensions": ["js", "json", "ts"],
    "rootDir": "src",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": ["**/*.(t|j)s"],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
}

test/jest-e2e.json — E2E tests

json
{
  "moduleFileExtensions": ["js", "json", "ts"],
  "rootDir": ".",
  "testEnvironment": "node",
  "testRegex": ".e2e-spec.ts$",
  "transform": {
    "^.+\\.(t|j)s$": "ts-jest"
  },
  "moduleNameMapper": {
    "^src/(.*)$": "<rootDir>/../src/$1"
  }
}

package.json scripts — add these:

json
{
  "scripts": {
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  }
}

PART 1: UNIT TESTS

The Mental Model

Unit testing in NestJS follows one pattern:

text
1. Create a testing module with MOCKED dependencies
2. Get the service/guard/interceptor from the module
3. Call its methods
4. Assert the results

Every dependency is replaced with a mock — a fake object that pretends to be the real thing. Your TasksService depends on a Mongoose Model<TaskDocument>? You don't need MongoDB. You create a fake model that returns fake data. You're testing your logic, not Mongoose's.

Analogy

A mock is a crash-test dummy. It's shaped like a real passenger and sits where a passenger would, but it has no life of its own — it does exactly what the test needs and reports back precisely. You're not testing whether the dummy can think; you're testing whether the airbag (your logic) fires correctly when the dummy is present.


Unit Test 1: TasksService

This is the most important service to test. It has business logic — ownership checks, CRUD operations, error throwing.

src/tasks/tasks.service.spec.ts

ts
import { Test, TestingModule } from '@nestjs/testing';
import { getModelToken } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { TasksService } from './tasks.service';
import { Task, TaskDocument } from './schemas/task.schema';
import { NotFoundException, ForbiddenException } from '@nestjs/common';

// Mock task data
const mockUserId = '507f1f77bcf86cd799439011';
const mockOtherUserId = '507f1f77bcf86cd799439099';

const mockTask = {
  _id: '507f1f77bcf86cd799439022',
  title: 'Test task',
  description: 'Test description',
  done: false,
  owner: { toString: () => mockUserId },
  createdAt: new Date(),
  updatedAt: new Date(),
};

const mockTasksList = [
  mockTask,
  {
    ...mockTask,
    _id: '507f1f77bcf86cd799439033',
    title: 'Second task',
  },
];

describe('TasksService', () => {
  let service: TasksService;
  let model: Model<TaskDocument>;

  // Factory for creating mock model
  // Each method returns jest functions we can control
  const mockTaskModel = {
    find: jest.fn(),
    findById: jest.fn(),
    findByIdAndUpdate: jest.fn(),
    findByIdAndDelete: jest.fn(),
    create: jest.fn(),
  };

  beforeEach(async () => {
    // ① Create a testing module — this replaces AppModule
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        TasksService,
        {
          // Instead of the real Mongoose model, inject our mock
          provide: getModelToken(Task.name),
          useValue: mockTaskModel,
        },
      ],
    }).compile();

    // ② Get the service instance from the testing module
    service = module.get<TasksService>(TasksService);
    model = module.get<Model<TaskDocument>>(getModelToken(Task.name));

    // ③ Clear all mock call history between tests
    jest.clearAllMocks();
  });

  // ================================
  //          describe blocks
  //  Group tests by method
  // ================================

  describe('findAll', () => {
    it('should return an array of tasks for the user', async () => {
      // Arrange: tell the mock what to return
      mockTaskModel.find.mockReturnValue({
        exec: jest.fn().mockResolvedValue(mockTasksList),
      });

      // Act: call the method
      const result = await service.findAll(mockUserId);

      // Assert: check the result
      expect(result).toEqual(mockTasksList);
      expect(mockTaskModel.find).toHaveBeenCalledWith({ owner: mockUserId });
    });

    it('should return empty array when user has no tasks', async () => {
      mockTaskModel.find.mockReturnValue({
        exec: jest.fn().mockResolvedValue([]),
      });

      const result = await service.findAll(mockUserId);

      expect(result).toEqual([]);
    });
  });

  describe('findOne', () => {
    it('should return a task if found and user owns it', async () => {
      mockTaskModel.findById.mockReturnValue({
        exec: jest.fn().mockResolvedValue(mockTask),
      });

      const result = await service.findOne(mockTask._id, mockUserId);

      expect(result).toEqual(mockTask);
      expect(mockTaskModel.findById).toHaveBeenCalledWith(mockTask._id);
    });

    it('should throw NotFoundException if task does not exist', async () => {
      mockTaskModel.findById.mockReturnValue({
        exec: jest.fn().mockResolvedValue(null),
      });

      await expect(
        service.findOne('nonexistent-id', mockUserId),
      ).rejects.toThrow(NotFoundException);
    });

    it('should throw ForbiddenException if user does not own the task', async () => {
      mockTaskModel.findById.mockReturnValue({
        exec: jest.fn().mockResolvedValue(mockTask),
      });

      // Different user trying to access the task
      await expect(
        service.findOne(mockTask._id, mockOtherUserId),
      ).rejects.toThrow(ForbiddenException);
    });
  });

  describe('create', () => {
    it('should create and return a new task', async () => {
      const createDto = { title: 'New task', description: 'New description' };
      const createdTask = {
        ...mockTask,
        ...createDto,
        owner: mockUserId,
      };

      mockTaskModel.create.mockResolvedValue(createdTask);

      const result = await service.create(createDto, mockUserId);

      expect(result).toEqual(createdTask);
      expect(mockTaskModel.create).toHaveBeenCalledWith({
        ...createDto,
        owner: mockUserId,
      });
    });
  });

  describe('update', () => {
    it('should update and return the task if user owns it', async () => {
      const updateDto = { title: 'Updated title', done: true };
      const updatedTask = { ...mockTask, ...updateDto };

      // findOne is called internally — needs findById mock
      mockTaskModel.findById.mockReturnValue({
        exec: jest.fn().mockResolvedValue(mockTask),
      });
      mockTaskModel.findByIdAndUpdate.mockReturnValue({
        exec: jest.fn().mockResolvedValue(updatedTask),
      });

      const result = await service.update(mockTask._id, updateDto, mockUserId);

      expect(result.title).toBe('Updated title');
      expect(result.done).toBe(true);
      expect(mockTaskModel.findByIdAndUpdate).toHaveBeenCalledWith(
        mockTask._id,
        updateDto,
        { new: true },
      );
    });

    it('should throw ForbiddenException if non-owner tries to update', async () => {
      mockTaskModel.findById.mockReturnValue({
        exec: jest.fn().mockResolvedValue(mockTask),
      });

      await expect(
        service.update(mockTask._id, { title: 'Hacked' }, mockOtherUserId),
      ).rejects.toThrow(ForbiddenException);

      // Ensure update was never called
      expect(mockTaskModel.findByIdAndUpdate).not.toHaveBeenCalled();
    });
  });

  describe('remove', () => {
    it('should delete the task if user owns it', async () => {
      mockTaskModel.findById.mockReturnValue({
        exec: jest.fn().mockResolvedValue(mockTask),
      });
      mockTaskModel.findByIdAndDelete.mockReturnValue({
        exec: jest.fn().mockResolvedValue(mockTask),
      });

      await service.remove(mockTask._id, mockUserId);

      expect(mockTaskModel.findByIdAndDelete).toHaveBeenCalledWith(
        mockTask._id,
      );
    });

    it('should throw NotFoundException for non-existent task', async () => {
      mockTaskModel.findById.mockReturnValue({
        exec: jest.fn().mockResolvedValue(null),
      });

      await expect(
        service.remove('nonexistent-id', mockUserId),
      ).rejects.toThrow(NotFoundException);

      expect(mockTaskModel.findByIdAndDelete).not.toHaveBeenCalled();
    });

    it('should throw ForbiddenException if non-owner tries to delete', async () => {
      mockTaskModel.findById.mockReturnValue({
        exec: jest.fn().mockResolvedValue(mockTask),
      });

      await expect(
        service.remove(mockTask._id, mockOtherUserId),
      ).rejects.toThrow(ForbiddenException);

      expect(mockTaskModel.findByIdAndDelete).not.toHaveBeenCalled();
    });
  });
});

Breaking down the patterns:

Test.createTestingModule() — NestJS's testing utility. It creates a mini DI container just for this test. You register only what you need — the service under test and its mocked dependencies. No database, no HTTP server, no other modules.

getModelToken(Task.name) — When NestJS injects @InjectModel(Task.name), it uses a token internally. getModelToken gives you that same token so you can replace the real model with a mock.

jest.fn() — Creates a mock function. You control what it returns with .mockReturnValue() or .mockResolvedValue() (for promises). You verify it was called with .toHaveBeenCalledWith().

Chain mocking (.find().exec()) — Mongoose methods return query builders, not promises directly. .find() returns an object with .exec(). So you mock the chain: find returns an object with exec as a mock function that returns the resolved value.

jest.clearAllMocks() — Resets call counts and return values between tests. Without this, mock state leaks between tests — test 2 might pass because of mock state left by test 1. Always clear.

rejects.toThrow() — For async functions that throw, await expect(asyncFn()).rejects.toThrow(ErrorType) catches the rejection and asserts the error type. Without rejects, the test would fail with an unhandled promise rejection instead of a clean assertion.


Unit Test 2: AuthService

The auth service has the most complex logic — hashing, token generation, refresh rotation, reuse detection.

src/auth/auth.service.spec.ts

ts
import { Test, TestingModule } from '@nestjs/testing';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import {
  UnauthorizedException,
  ForbiddenException,
} from '@nestjs/common';
import * as bcrypt from 'bcrypt';
import { AuthService } from './auth.service';
import { UsersService } from '../users/users.service';

// Mock bcrypt at the module level
jest.mock('bcrypt');
const mockedBcrypt = bcrypt as jest.Mocked<typeof bcrypt>;

describe('AuthService', () => {
  let authService: AuthService;
  let usersService: Partial<Record<keyof UsersService, jest.Mock>>;
  let jwtService: Partial<Record<keyof JwtService, jest.Mock>>;

  const mockUser = {
    _id: { toString: () => '507f1f77bcf86cd799439011' },
    email: 'john@example.com',
    username: 'john_doe',
    password: '$2b$12$hashedpassword',
    roles: ['user'],
    refreshTokens: ['$2b$12$hashedRefreshToken'],
  };

  beforeEach(async () => {
    // Create mock implementations for all dependencies
    usersService = {
      findByEmail: jest.fn(),
      findById: jest.fn(),
      create: jest.fn(),
      addRefreshToken: jest.fn(),
      removeRefreshToken: jest.fn(),
      removeAllRefreshTokens: jest.fn(),
    };

    jwtService = {
      signAsync: jest.fn(),
      verify: jest.fn(),
    };

    const module: TestingModule = await Test.createTestingModule({
      providers: [
        AuthService,
        { provide: UsersService, useValue: usersService },
        { provide: JwtService, useValue: jwtService },
        {
          provide: ConfigService,
          useValue: {
            get: jest.fn((key: string) => {
              const config = {
                JWT_ACCESS_SECRET: 'test-access-secret',
                JWT_REFRESH_SECRET: 'test-refresh-secret',
                JWT_ACCESS_EXPIRATION: '15m',
                JWT_REFRESH_EXPIRATION: '7d',
              };
              return config[key];
            }),
          },
        },
      ],
    }).compile();

    authService = module.get<AuthService>(AuthService);
    jest.clearAllMocks();
  });

  // ========================
  //       REGISTER
  // ========================
  describe('register', () => {
    it('should hash password and create user', async () => {
      const registerDto = {
        email: 'john@example.com',
        username: 'john_doe',
        password: 'SecurePass123',
      };

      (mockedBcrypt.hash as jest.Mock).mockResolvedValue('$2b$12$hashed');
      usersService.create.mockResolvedValue(mockUser);

      const result = await authService.register(registerDto);

      // Verify password was hashed with 12 rounds
      expect(mockedBcrypt.hash).toHaveBeenCalledWith('SecurePass123', 12);

      // Verify user was created with HASHED password, not raw
      expect(usersService.create).toHaveBeenCalledWith(
        'john@example.com',
        'john_doe',
        '$2b$12$hashed',
      );

      // Verify response shape
      expect(result.message).toBe('Registration successful');
      expect(result.user.email).toBe('john@example.com');
    });

    it('should NOT return tokens on registration', async () => {
      (mockedBcrypt.hash as jest.Mock).mockResolvedValue('$2b$12$hashed');
      usersService.create.mockResolvedValue(mockUser);

      const result = await authService.register({
        email: 'john@example.com',
        username: 'john_doe',
        password: 'SecurePass123',
      });

      // No tokens — user must log in explicitly
      expect(result).not.toHaveProperty('accessToken');
      expect(result).not.toHaveProperty('refreshToken');
    });
  });

  // ========================
  //         LOGIN
  // ========================
  describe('login', () => {
    const loginDto = {
      email: 'john@example.com',
      password: 'SecurePass123',
    };

    it('should return tokens and user data on valid credentials', async () => {
      usersService.findByEmail.mockResolvedValue(mockUser);
      (mockedBcrypt.compare as jest.Mock).mockResolvedValue(true);
      (mockedBcrypt.hash as jest.Mock).mockResolvedValue('$2b$12$hashedRefresh');
      jwtService.signAsync
        .mockResolvedValueOnce('mock-access-token')
        .mockResolvedValueOnce('mock-refresh-token');

      const result = await authService.login(loginDto);

      expect(result.accessToken).toBe('mock-access-token');
      expect(result.refreshToken).toBe('mock-refresh-token');
      expect(result.user.email).toBe('john@example.com');
      expect(result.user.roles).toEqual(['user']);
    });

    it('should store HASHED refresh token in database', async () => {
      usersService.findByEmail.mockResolvedValue(mockUser);
      (mockedBcrypt.compare as jest.Mock).mockResolvedValue(true);
      (mockedBcrypt.hash as jest.Mock).mockResolvedValue('$2b$12$hashedRefresh');
      jwtService.signAsync
        .mockResolvedValueOnce('access')
        .mockResolvedValueOnce('refresh');

      await authService.login(loginDto);

      // Verify hashed token was stored, not raw token
      expect(usersService.addRefreshToken).toHaveBeenCalledWith(
        '507f1f77bcf86cd799439011',
        '$2b$12$hashedRefresh',
      );
    });

    it('should throw UnauthorizedException for non-existent email', async () => {
      usersService.findByEmail.mockResolvedValue(null);

      await expect(authService.login(loginDto)).rejects.toThrow(
        UnauthorizedException,
      );
      // Generic message — doesn't reveal email exists
      await expect(authService.login(loginDto)).rejects.toThrow(
        'Invalid credentials',
      );
    });

    it('should throw UnauthorizedException for wrong password', async () => {
      usersService.findByEmail.mockResolvedValue(mockUser);
      (mockedBcrypt.compare as jest.Mock).mockResolvedValue(false);

      await expect(authService.login(loginDto)).rejects.toThrow(
        UnauthorizedException,
      );
      // Same generic message — can't distinguish from wrong email
      await expect(authService.login(loginDto)).rejects.toThrow(
        'Invalid credentials',
      );
    });

    it('should generate access token with full payload and refresh token with minimal payload', async () => {
      usersService.findByEmail.mockResolvedValue(mockUser);
      (mockedBcrypt.compare as jest.Mock).mockResolvedValue(true);
      (mockedBcrypt.hash as jest.Mock).mockResolvedValue('hashed');
      jwtService.signAsync
        .mockResolvedValueOnce('access')
        .mockResolvedValueOnce('refresh');

      await authService.login(loginDto);

      // Access token gets full payload
      expect(jwtService.signAsync).toHaveBeenNthCalledWith(
        1,
        { sub: '507f1f77bcf86cd799439011', email: 'john@example.com', roles: ['user'] },
        expect.objectContaining({ secret: 'test-access-secret' }),
      );

      // Refresh token gets minimal payload (just user ID)
      expect(jwtService.signAsync).toHaveBeenNthCalledWith(
        2,
        { sub: '507f1f77bcf86cd799439011' },
        expect.objectContaining({ secret: 'test-refresh-secret' }),
      );
    });
  });

  // ========================
  //        REFRESH
  // ========================
  describe('refresh', () => {
    it('should throw if no refresh token provided', async () => {
      await expect(authService.refresh(null)).rejects.toThrow(
        UnauthorizedException,
      );
      await expect(authService.refresh('')).rejects.toThrow(
        UnauthorizedException,
      );
    });

    it('should throw if refresh token signature is invalid', async () => {
      jwtService.verify.mockImplementation(() => {
        throw new Error('invalid signature');
      });

      await expect(authService.refresh('bad-token')).rejects.toThrow(
        UnauthorizedException,
      );
    });

    it('should invalidate ALL sessions on token reuse detection', async () => {
      jwtService.verify.mockReturnValue({ sub: '507f1f77bcf86cd799439011' });
      usersService.findById.mockResolvedValue({
        ...mockUser,
        refreshTokens: ['$2b$12$someOtherHash'],
      });
      // bcrypt.compare returns false — token not in DB (already rotated)
      (mockedBcrypt.compare as jest.Mock).mockResolvedValue(false);

      await expect(authService.refresh('reused-token')).rejects.toThrow(
        ForbiddenException,
      );
      // ALL sessions nuked
      expect(usersService.removeAllRefreshTokens).toHaveBeenCalledWith(
        '507f1f77bcf86cd799439011',
      );
    });

    it('should rotate tokens on valid refresh', async () => {
      jwtService.verify.mockReturnValue({ sub: '507f1f77bcf86cd799439011' });
      usersService.findById.mockResolvedValue(mockUser);
      (mockedBcrypt.compare as jest.Mock).mockResolvedValue(true);
      (mockedBcrypt.hash as jest.Mock).mockResolvedValue('$2b$12$newHash');
      jwtService.signAsync
        .mockResolvedValueOnce('new-access-token')
        .mockResolvedValueOnce('new-refresh-token');

      const result = await authService.refresh('valid-refresh-token');

      // Old token removed
      expect(usersService.removeRefreshToken).toHaveBeenCalled();
      // New token stored
      expect(usersService.addRefreshToken).toHaveBeenCalledWith(
        '507f1f77bcf86cd799439011',
        '$2b$12$newHash',
      );
      // New tokens returned
      expect(result.accessToken).toBe('new-access-token');
      expect(result.refreshToken).toBe('new-refresh-token');
    });
  });

  // ========================
  //        LOGOUT
  // ========================
  describe('logout', () => {
    it('should remove specific refresh token from database', async () => {
      usersService.findById.mockResolvedValue(mockUser);
      (mockedBcrypt.compare as jest.Mock).mockResolvedValue(true);

      await authService.logout('some-refresh-token', '507f1f77bcf86cd799439011');

      expect(usersService.removeRefreshToken).toHaveBeenCalled();
    });

    it('should handle logout gracefully when no refresh token', async () => {
      const result = await authService.logout(null, '507f1f77bcf86cd799439011');

      expect(result.message).toBe('Logged out');
      expect(usersService.findById).not.toHaveBeenCalled();
    });
  });

  describe('logoutAll', () => {
    it('should remove ALL refresh tokens for the user', async () => {
      await authService.logoutAll('507f1f77bcf86cd799439011');

      expect(usersService.removeAllRefreshTokens).toHaveBeenCalledWith(
        '507f1f77bcf86cd799439011',
      );
    });
  });
});

Key testing patterns introduced:

jest.mock('bcrypt') — Module-level mock. Replaces the entire bcrypt module with mock functions. Every function in bcrypt becomes a jest.fn(). You control what bcrypt.hash and bcrypt.compare return without doing actual hashing (which is slow — 12 rounds of bcrypt takes ~250ms per call, multiply by 20 tests = 5 seconds just on hashing).

.mockResolvedValueOnce() — Returns a specific value for the next call only, then resets. Used when signAsync is called twice (access + refresh) and you need different return values for each call.

expect.objectContaining() — Partial match. "I don't care about all properties, but these specific ones must exist with these values." Perfect for checking JWT sign options without matching every property.

.toHaveBeenNthCalledWith(n, ...args) — Asserts what the mock was called with on its Nth invocation. First call (access token) gets full payload. Second call (refresh token) gets minimal payload. This verifies the security design decision.


Unit Test 3: AuthGuard

Guards are critical — a bug here means either everyone gets in or nobody gets in. Both are terrible.

src/common/guards/auth.guard.spec.ts

ts
import { Test, TestingModule } from '@nestjs/testing';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from './auth.guard';

describe('AuthGuard', () => {
  let guard: AuthGuard;
  let reflector: Reflector;
  let jwtService: Partial<Record<keyof JwtService, jest.Mock>>;

  // Helper to create a mock ExecutionContext
  const createMockContext = (
    authHeader?: string,
  ): ExecutionContext => {
    const mockRequest = {
      headers: {
        authorization: authHeader,
      },
    };

    return {
      switchToHttp: () => ({
        getRequest: () => mockRequest,
      }),
      getHandler: () => jest.fn(),
      getClass: () => jest.fn(),
    } as unknown as ExecutionContext;
  };

  beforeEach(async () => {
    jwtService = {
      verifyAsync: jest.fn(),
    };

    const module: TestingModule = await Test.createTestingModule({
      providers: [
        AuthGuard,
        {
          provide: Reflector,
          useValue: {
            getAllAndOverride: jest.fn(),
          },
        },
        { provide: JwtService, useValue: jwtService },
        {
          provide: ConfigService,
          useValue: {
            get: jest.fn().mockReturnValue('test-secret'),
          },
        },
      ],
    }).compile();

    guard = module.get<AuthGuard>(AuthGuard);
    reflector = module.get<Reflector>(Reflector);
  });

  it('should allow access to @Public() routes without token', async () => {
    // Reflector returns true for IS_PUBLIC_KEY
    (reflector.getAllAndOverride as jest.Mock).mockReturnValue(true);

    const context = createMockContext(); // no auth header

    const result = await guard.canActivate(context);

    expect(result).toBe(true);
    // JWT service should never be called for public routes
    expect(jwtService.verifyAsync).not.toHaveBeenCalled();
  });

  it('should throw UnauthorizedException when no token provided', async () => {
    (reflector.getAllAndOverride as jest.Mock).mockReturnValue(false);

    const context = createMockContext(); // no auth header

    await expect(guard.canActivate(context)).rejects.toThrow(
      UnauthorizedException,
    );
  });

  it('should throw UnauthorizedException for invalid token', async () => {
    (reflector.getAllAndOverride as jest.Mock).mockReturnValue(false);
    jwtService.verifyAsync.mockRejectedValue(new Error('invalid'));

    const context = createMockContext('Bearer invalid-token');

    await expect(guard.canActivate(context)).rejects.toThrow(
      UnauthorizedException,
    );
  });

  it('should attach user payload to request on valid token', async () => {
    (reflector.getAllAndOverride as jest.Mock).mockReturnValue(false);

    const mockPayload = {
      sub: 'user-id',
      email: 'john@example.com',
      roles: ['user'],
    };
    jwtService.verifyAsync.mockResolvedValue(mockPayload);

    const context = createMockContext('Bearer valid-token');
    const request = context.switchToHttp().getRequest();

    await guard.canActivate(context);

    // User should be attached to request
    expect(request['user']).toEqual(mockPayload);
  });

  it('should only accept Bearer scheme', async () => {
    (reflector.getAllAndOverride as jest.Mock).mockReturnValue(false);

    const context = createMockContext('Basic some-token');

    await expect(guard.canActivate(context)).rejects.toThrow(
      UnauthorizedException,
    );
  });
});

Why mock ExecutionContext?

ExecutionContext is what NestJS passes to guards in real requests. In tests, there's no real HTTP request. So you build a fake one — an object that has the same shape (switchToHttp().getRequest(), getHandler(), getClass()) but returns your controlled mock data. This is the most common pattern in NestJS guard tests.


Unit Test 4: TransformInterceptor

src/common/interceptors/transform.interceptor.spec.ts

ts
import { TransformInterceptor } from './transform.interceptor';
import { ExecutionContext, CallHandler } from '@nestjs/common';
import { of } from 'rxjs';

describe('TransformInterceptor', () => {
  let interceptor: TransformInterceptor<any>;

  beforeEach(() => {
    interceptor = new TransformInterceptor();
  });

  const createMockContext = (url: string = '/tasks'): ExecutionContext => {
    return {
      switchToHttp: () => ({
        getRequest: () => ({ url }),
      }),
    } as unknown as ExecutionContext;
  };

  const createMockCallHandler = (data: any): CallHandler => ({
    handle: () => of(data),
  });

  it('should wrap response data in success envelope', (done) => {
    const context = createMockContext('/tasks');
    const data = [{ id: 1, title: 'Test' }];
    const handler = createMockCallHandler(data);

    interceptor.intercept(context, handler).subscribe((result) => {
      expect(result.success).toBe(true);
      expect(result.data).toEqual(data);
      expect(result.path).toBe('/tasks');
      expect(result.timestamp).toBeDefined();
      done();
    });
  });

  it('should handle null/undefined data (e.g., delete operations)', (done) => {
    const context = createMockContext('/tasks/1');
    const handler = createMockCallHandler(undefined);

    interceptor.intercept(context, handler).subscribe((result) => {
      expect(result.success).toBe(true);
      expect(result.data).toBeNull();
      done();
    });
  });
});

Why done callback? Interceptors return Observables (RxJS). Jest doesn't natively wait for Observable completion. The done callback tells Jest: "this test is async — don't finish until I call done()." Inside the .subscribe(), you assert and then call done(). If the Observable never emits, the test times out (which is correct — it means something is broken).


PART 2: E2E TESTS

This is where it gets real. Real HTTP requests, real MongoDB (in-memory), real pipeline.


E2E Setup — Shared Test Configuration

Analogy

The shared setup is the pit crew that prepares the test track before every drive: they lay the tarmac (spin up the in-memory MongoDB), fit the real pipeline of validation and filters, and hand you the keys to a fully assembled car. Writing it once means every E2E test starts from the same clean track instead of each driver paving their own road.

test/setup.ts

ts
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { AllExceptionsFilter } from '../src/common/filters/all-exceptions.filter';
import { TransformInterceptor } from '../src/common/interceptors/transform.interceptor';
import * as cookieParser from 'cookie-parser';
import { AppModule } from '../src/app.module';

let mongod: MongoMemoryServer;

/**
 * Creates a fully configured NestJS application for E2E testing.
 * Uses an in-memory MongoDB instance — no external DB needed.
 */
export async function createTestApp(): Promise<INestApplication> {
  // ① Start in-memory MongoDB
  mongod = await MongoMemoryServer.create();
  const mongoUri = mongod.getUri();

  // ② Override the MongoDB URI in environment
  process.env.MONGODB_URI = mongoUri;
  process.env.JWT_ACCESS_SECRET = 'test-access-secret';
  process.env.JWT_REFRESH_SECRET = 'test-refresh-secret';
  process.env.JWT_ACCESS_EXPIRATION = '15m';
  process.env.JWT_REFRESH_EXPIRATION = '7d';

  // ③ Create the testing module from the REAL AppModule
  const moduleFixture: TestingModule = await Test.createTestingModule({
    imports: [AppModule],
  }).compile();

  // ④ Create the app with the same middleware as main.ts
  const app = moduleFixture.createNestApplication();

  app.use(cookieParser());
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
    }),
  );
  app.useGlobalFilters(new AllExceptionsFilter());
  app.useGlobalInterceptors(new TransformInterceptor());

  await app.init();
  return app;
}

/**
 * Cleanup: close app and stop in-memory MongoDB
 */
export async function closeTestApp(app: INestApplication): Promise<void> {
  await app.close();
  if (mongod) {
    await mongod.stop();
  }
}

Why MongoMemoryServer?

Your E2E tests need a real database because they test the full pipeline including Mongoose operations. But you don't want to: - Require MongoDB installed on every dev machine - Risk polluting your development database - Deal with test data cleanup

MongoMemoryServer solves all three. It downloads a MongoDB binary once, runs it in memory, gives you a connection URI, and tears down completely when tests finish. Each test suite gets a fresh, empty database.

Why use the real AppModule?

Unit tests use Test.createTestingModule with individual providers. E2E tests use the actual AppModule — the same module that runs in production. This ensures your module wiring, DI configuration, and middleware setup are tested. If you forgot to import a module or export a service, the E2E test catches it.


E2E Test 1: Auth Flow

test/auth.e2e-spec.ts

ts
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { createTestApp, closeTestApp } from './setup';

describe('Auth (e2e)', () => {
  let app: INestApplication;

  beforeAll(async () => {
    app = await createTestApp();
  }, 30000); // 30s timeout — MongoMemoryServer download on first run

  afterAll(async () => {
    await closeTestApp(app);
  });

  // Store tokens across tests — simulates a real client session
  let accessToken: string;
  let refreshCookie: string;

  // ========================
  //     REGISTRATION
  // ========================
  describe('POST /auth/register', () => {
    it('should register a new user', () => {
      return request(app.getHttpServer())
        .post('/auth/register')
        .send({
          email: 'john@example.com',
          username: 'john_doe',
          password: 'SecurePass123',
        })
        .expect(201)
        .expect((res) => {
          expect(res.body.success).toBe(true);
          expect(res.body.data.message).toBe('Registration successful');
          expect(res.body.data.user.email).toBe('john@example.com');
          expect(res.body.data.user.username).toBe('john_doe');
          // No tokens in response
          expect(res.body.data).not.toHaveProperty('accessToken');
        });
    });

    it('should reject duplicate email', () => {
      return request(app.getHttpServer())
        .post('/auth/register')
        .send({
          email: 'john@example.com',
          username: 'different_user',
          password: 'SecurePass123',
        })
        .expect(409)
        .expect((res) => {
          expect(res.body.success).toBe(false);
          expect(res.body.message).toContain('email already exists');
        });
    });

    it('should reject duplicate username', () => {
      return request(app.getHttpServer())
        .post('/auth/register')
        .send({
          email: 'different@example.com',
          username: 'john_doe',
          password: 'SecurePass123',
        })
        .expect(409)
        .expect((res) => {
          expect(res.body.success).toBe(false);
          expect(res.body.message).toContain('username already exists');
        });
    });

    it('should reject weak password', () => {
      return request(app.getHttpServer())
        .post('/auth/register')
        .send({
          email: 'weak@example.com',
          username: 'weak_user',
          password: 'weak',
        })
        .expect(400)
        .expect((res) => {
          expect(res.body.success).toBe(false);
          expect(res.body.message).toBe('Validation failed');
          expect(res.body.details).toEqual(
            expect.arrayContaining([
              expect.stringContaining('at least 8 characters'),
            ]),
          );
        });
    });

    it('should reject invalid email format', () => {
      return request(app.getHttpServer())
        .post('/auth/register')
        .send({
          email: 'not-an-email',
          username: 'valid_user',
          password: 'SecurePass123',
        })
        .expect(400);
    });

    it('should reject extra fields (whitelist)', () => {
      return request(app.getHttpServer())
        .post('/auth/register')
        .send({
          email: 'hacker@example.com',
          username: 'hacker',
          password: 'SecurePass123',
          roles: ['admin'], // trying to self-assign admin
        })
        .expect(400)
        .expect((res) => {
          expect(res.body.details).toEqual(
            expect.arrayContaining([
              expect.stringContaining('roles should not exist'),
            ]),
          );
        });
    });
  });

  // ========================
  //         LOGIN
  // ========================
  describe('POST /auth/login', () => {
    it('should login and return access token + set refresh cookie', () => {
      return request(app.getHttpServer())
        .post('/auth/login')
        .send({
          email: 'john@example.com',
          password: 'SecurePass123',
        })
        .expect(200)
        .expect((res) => {
          expect(res.body.success).toBe(true);
          expect(res.body.data.accessToken).toBeDefined();
          expect(res.body.data.user.email).toBe('john@example.com');

          // Refresh token should NOT be in response body
          expect(res.body.data).not.toHaveProperty('refreshToken');

          // Refresh token should be in Set-Cookie header
          const cookies = res.headers['set-cookie'];
          expect(cookies).toBeDefined();

          const refreshCookieHeader = Array.isArray(cookies)
            ? cookies.find((c: string) => c.startsWith('refreshToken='))
            : cookies;
          expect(refreshCookieHeader).toBeDefined();
          expect(refreshCookieHeader).toContain('HttpOnly');
          expect(refreshCookieHeader).toContain('Path=/auth');

          // Store for subsequent tests
          accessToken = res.body.data.accessToken;
          refreshCookie = refreshCookieHeader;
        });
    });

    it('should reject wrong password with generic message', () => {
      return request(app.getHttpServer())
        .post('/auth/login')
        .send({
          email: 'john@example.com',
          password: 'WrongPassword123',
        })
        .expect(401)
        .expect((res) => {
          expect(res.body.message).toBe('Invalid credentials');
        });
    });

    it('should reject non-existent email with same generic message', () => {
      return request(app.getHttpServer())
        .post('/auth/login')
        .send({
          email: 'nobody@example.com',
          password: 'SecurePass123',
        })
        .expect(401)
        .expect((res) => {
          // Same message as wrong password — no email enumeration
          expect(res.body.message).toBe('Invalid credentials');
        });
    });
  });

  // ========================
  //    PROTECTED ROUTES
  // ========================
  describe('Protected route access', () => {
    it('should allow access with valid token', () => {
      return request(app.getHttpServer())
        .get('/tasks')
        .set('Authorization', `Bearer ${accessToken}`)
        .expect(200)
        .expect((res) => {
          expect(res.body.success).toBe(true);
          expect(Array.isArray(res.body.data)).toBe(true);
        });
    });

    it('should reject access without token', () => {
      return request(app.getHttpServer())
        .get('/tasks')
        .expect(401)
        .expect((res) => {
          expect(res.body.success).toBe(false);
          expect(res.body.message).toContain('Access token not provided');
        });
    });

    it('should reject access with garbage token', () => {
      return request(app.getHttpServer())
        .get('/tasks')
        .set('Authorization', 'Bearer garbage.token.here')
        .expect(401)
        .expect((res) => {
          expect(res.body.message).toContain('Invalid or expired');
        });
    });
  });

  // ========================
  //     TOKEN REFRESH
  // ========================
  describe('POST /auth/refresh', () => {
    it('should return new access token using refresh cookie', () => {
      return request(app.getHttpServer())
        .post('/auth/refresh')
        .set('Cookie', refreshCookie)
        .expect(200)
        .expect((res) => {
          expect(res.body.success).toBe(true);
          expect(res.body.data.accessToken).toBeDefined();

          // New refresh cookie should be set (rotation)
          const cookies = res.headers['set-cookie'];
          expect(cookies).toBeDefined();

          // Update stored values for subsequent tests
          accessToken = res.body.data.accessToken;
          const newRefreshCookie = Array.isArray(cookies)
            ? cookies.find((c: string) => c.startsWith('refreshToken='))
            : cookies;
          if (newRefreshCookie) refreshCookie = newRefreshCookie;
        });
    });

    it('should reject refresh without cookie', () => {
      return request(app.getHttpServer())
        .post('/auth/refresh')
        .expect(401);
    });
  });

  // ========================
  //        LOGOUT
  // ========================
  describe('POST /auth/logout', () => {
    it('should logout and clear refresh cookie', () => {
      return request(app.getHttpServer())
        .post('/auth/logout')
        .set('Authorization', `Bearer ${accessToken}`)
        .set('Cookie', refreshCookie)
        .expect(200)
        .expect((res) => {
          expect(res.body.success).toBe(true);
          expect(res.body.data.message).toBe('Logged out');

          // Cookie should be cleared
          const cookies = res.headers['set-cookie'];
          if (cookies) {
            const cleared = Array.isArray(cookies)
              ? cookies.find((c: string) => c.startsWith('refreshToken='))
              : cookies;
            if (cleared) {
              // Cleared cookie has empty value or past expiry
              expect(
                cleared.includes('refreshToken=;') ||
                cleared.includes('Expires=Thu, 01 Jan 1970'),
              ).toBe(true);
            }
          }
        });
    });

    it('should reject logout without access token', () => {
      return request(app.getHttpServer())
        .post('/auth/logout')
        .expect(401);
    });
  });
});

E2E Test 2: Tasks CRUD Flow

test/tasks.e2e-spec.ts

ts
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { createTestApp, closeTestApp } from './setup';

describe('Tasks CRUD (e2e)', () => {
  let app: INestApplication;
  let accessToken: string;
  let secondUserToken: string;
  let createdTaskId: string;

  beforeAll(async () => {
    app = await createTestApp();

    // Register and login first user
    await request(app.getHttpServer())
      .post('/auth/register')
      .send({
        email: 'alice@example.com',
        username: 'alice',
        password: 'SecurePass123',
      });

    const loginRes = await request(app.getHttpServer())
      .post('/auth/login')
      .send({ email: 'alice@example.com', password: 'SecurePass123' });

    accessToken = loginRes.body.data.accessToken;

    // Register and login second user (for ownership tests)
    await request(app.getHttpServer())
      .post('/auth/register')
      .send({
        email: 'bob@example.com',
        username: 'bob',
        password: 'SecurePass123',
      });

    const secondLogin = await request(app.getHttpServer())
      .post('/auth/login')
      .send({ email: 'bob@example.com', password: 'SecurePass123' });

    secondUserToken = secondLogin.body.data.accessToken;
  }, 30000);

  afterAll(async () => {
    await closeTestApp(app);
  });

  // ========================
  //     CREATE TASK
  // ========================
  describe('POST /tasks', () => {
    it('should create a task for authenticated user', () => {
      return request(app.getHttpServer())
        .post('/tasks')
        .set('Authorization', `Bearer ${accessToken}`)
        .send({
          title: 'Buy groceries',
          description: 'Milk, eggs, bread',
        })
        .expect(201)
        .expect((res) => {
          expect(res.body.success).toBe(true);
          expect(res.body.data.title).toBe('Buy groceries');
          expect(res.body.data.description).toBe('Milk, eggs, bread');
          expect(res.body.data.done).toBe(false);
          expect(res.body.data.owner).toBeDefined();
          expect(res.body.data._id).toBeDefined();

          // Store for later tests
          createdTaskId = res.body.data._id;
        });
    });

    it('should create a second task', () => {
      return request(app.getHttpServer())
        .post('/tasks')
        .set('Authorization', `Bearer ${accessToken}`)
        .send({
          title: 'Learn NestJS testing',
          description: 'Unit + E2E',
        })
        .expect(201);
    });

    it('should reject creation without auth', () => {
      return request(app.getHttpServer())
        .post('/tasks')
        .send({
          title: 'Unauthorized task',
          description: 'Should fail',
        })
        .expect(401);
    });

    it('should reject empty title', () => {
      return request(app.getHttpServer())
        .post('/tasks')
        .set('Authorization', `Bearer ${accessToken}`)
        .send({
          title: '',
          description: 'Valid description',
        })
        .expect(400)
        .expect((res) => {
          expect(res.body.success).toBe(false);
          expect(res.body.details).toEqual(
            expect.arrayContaining([
              expect.stringContaining('title should not be empty'),
            ]),
          );
        });
    });

    it('should reject missing description', () => {
      return request(app.getHttpServer())
        .post('/tasks')
        .set('Authorization', `Bearer ${accessToken}`)
        .send({ title: 'Title only' })
        .expect(400);
    });

    it('should strip unknown fields', () => {
      return request(app.getHttpServer())
        .post('/tasks')
        .set('Authorization', `Bearer ${accessToken}`)
        .send({
          title: 'Valid task',
          description: 'Valid description',
          hackField: 'should be rejected',
        })
        .expect(400)
        .expect((res) => {
          expect(res.body.details).toEqual(
            expect.arrayContaining([
              expect.stringContaining('hackField should not exist'),
            ]),
          );
        });
    });
  });

  // ========================
  //     GET ALL TASKS
  // ========================
  describe('GET /tasks', () => {
    it('should return only tasks owned by the authenticated user', () => {
      return request(app.getHttpServer())
        .get('/tasks')
        .set('Authorization', `Bearer ${accessToken}`)
        .expect(200)
        .expect((res) => {
          expect(res.body.success).toBe(true);
          expect(Array.isArray(res.body.data)).toBe(true);
          expect(res.body.data.length).toBe(2); // alice's 2 tasks
        });
    });

    it('should return empty array for user with no tasks', () => {
      return request(app.getHttpServer())
        .get('/tasks')
        .set('Authorization', `Bearer ${secondUserToken}`)
        .expect(200)
        .expect((res) => {
          expect(res.body.data).toEqual([]);
        });
    });
  });

  // ========================
  //     GET SINGLE TASK
  // ========================
  describe('GET /tasks/:id', () => {
    it('should return task if user owns it', () => {
      return request(app.getHttpServer())
        .get(`/tasks/${createdTaskId}`)
        .set('Authorization', `Bearer ${accessToken}`)
        .expect(200)
        .expect((res) => {
          expect(res.body.data._id).toBe(createdTaskId);
          expect(res.body.data.title).toBe('Buy groceries');
        });
    });

    it('should return 403 if different user tries to access', () => {
      return request(app.getHttpServer())
        .get(`/tasks/${createdTaskId}`)
        .set('Authorization', `Bearer ${secondUserToken}`)
        .expect(403)
        .expect((res) => {
          expect(res.body.message).toContain('do not own');
        });
    });

    it('should return 404 for non-existent task', () => {
      return request(app.getHttpServer())
        .get('/tasks/507f1f77bcf86cd799439099')
        .set('Authorization', `Bearer ${accessToken}`)
        .expect(404);
    });
  });

  // ========================
  //     UPDATE TASK
  // ========================
  describe('PATCH /tasks/:id', () => {
    it('should update task title', () => {
      return request(app.getHttpServer())
        .patch(`/tasks/${createdTaskId}`)
        .set('Authorization', `Bearer ${accessToken}`)
        .send({ title: 'Buy groceries and snacks' })
        .expect(200)
        .expect((res) => {
          expect(res.body.data.title).toBe('Buy groceries and snacks');
          // Untouched fields remain
          expect(res.body.data.description).toBe('Milk, eggs, bread');
          expect(res.body.data.done).toBe(false);
        });
    });

    it('should mark task as done', () => {
      return request(app.getHttpServer())
        .patch(`/tasks/${createdTaskId}`)
        .set('Authorization', `Bearer ${accessToken}`)
        .send({ done: true })
        .expect(200)
        .expect((res) => {
          expect(res.body.data.done).toBe(true);
        });
    });

    it('should reject update from non-owner', () => {
      return request(app.getHttpServer())
        .patch(`/tasks/${createdTaskId}`)
        .set('Authorization', `Bearer ${secondUserToken}`)
        .send({ title: 'Hacked title' })
        .expect(403);
    });

    it('should reject invalid field types', () => {
      return request(app.getHttpServer())
        .patch(`/tasks/${createdTaskId}`)
        .set('Authorization', `Bearer ${accessToken}`)
        .send({ done: 'not-a-boolean' })
        .expect(400);
    });
  });

  // ========================
  //     DELETE TASK
  // ========================
  describe('DELETE /tasks/:id', () => {
    it('should reject delete from non-admin user', () => {
      return request(app.getHttpServer())
        .delete(`/tasks/${createdTaskId}`)
        .set('Authorization', `Bearer ${accessToken}`)
        .expect(403)
        .expect((res) => {
          expect(res.body.message).toContain('Requires one of [admin] roles');
        });
    });

    it('should reject delete from different non-admin user', () => {
      return request(app.getHttpServer())
        .delete(`/tasks/${createdTaskId}`)
        .set('Authorization', `Bearer ${secondUserToken}`)
        .expect(403);
    });
  });

  // ========================
  //    RESPONSE ENVELOPE
  // ========================
  describe('Response format consistency', () => {
    it('success responses should have consistent shape', () => {
      return request(app.getHttpServer())
        .get('/tasks')
        .set('Authorization', `Bearer ${accessToken}`)
        .expect((res) => {
          expect(res.body).toHaveProperty('success', true);
          expect(res.body).toHaveProperty('data');
          expect(res.body).toHaveProperty('timestamp');
          expect(res.body).toHaveProperty('path');
        });
    });

    it('error responses should have consistent shape', () => {
      return request(app.getHttpServer())
        .get('/tasks/nonexistent')
        .set('Authorization', `Bearer ${accessToken}`)
        .expect((res) => {
          expect(res.body).toHaveProperty('success', false);
          expect(res.body).toHaveProperty('statusCode');
          expect(res.body).toHaveProperty('error');
          expect(res.body).toHaveProperty('message');
          expect(res.body).toHaveProperty('timestamp');
          expect(res.body).toHaveProperty('path');
        });
    });
  });
});

E2E Test 3: Full Integration Flow

Tests the complete journey a real user takes — register → login → create tasks → manage → logout.

Analogy

This is the full endurance lap: the examiner has you start the car cold, drive the entire route, handle the roundabout, park, and switch off — in one unbroken run. Individual manoeuvres already passed on their own, but only the complete lap proves the car survives a real trip from ignition to handbrake.

test/app.e2e-spec.ts

ts
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { createTestApp, closeTestApp } from './setup';

describe('Full Application Flow (e2e)', () => {
  let app: INestApplication;

  beforeAll(async () => {
    app = await createTestApp();
  }, 30000);

  afterAll(async () => {
    await closeTestApp(app);
  });

  // This test runs as a SINGLE sequential story
  // Each step depends on the previous one
  // This mirrors how a real user interacts with the API

  let accessToken: string;
  let refreshCookie: string;
  let taskId: string;

  it('Step 1: Register a new account', async () => {
    const res = await request(app.getHttpServer())
      .post('/auth/register')
      .send({
        email: 'fullflow@example.com',
        username: 'fullflow',
        password: 'SecurePass123',
      })
      .expect(201);

    expect(res.body.data.message).toBe('Registration successful');
  });

  it('Step 2: Cannot access tasks before login', async () => {
    await request(app.getHttpServer())
      .get('/tasks')
      .expect(401);
  });

  it('Step 3: Login with registered credentials', async () => {
    const res = await request(app.getHttpServer())
      .post('/auth/login')
      .send({
        email: 'fullflow@example.com',
        password: 'SecurePass123',
      })
      .expect(200);

    accessToken = res.body.data.accessToken;
    const cookies = res.headers['set-cookie'];
    refreshCookie = Array.isArray(cookies)
      ? cookies.find((c: string) => c.startsWith('refreshToken='))
      : cookies;

    expect(accessToken).toBeDefined();
    expect(refreshCookie).toBeDefined();
  });

  it('Step 4: Task list is empty after registration', async () => {
    const res = await request(app.getHttpServer())
      .get('/tasks')
      .set('Authorization', `Bearer ${accessToken}`)
      .expect(200);

    expect(res.body.data).toEqual([]);
  });

  it('Step 5: Create first task', async () => {
    const res = await request(app.getHttpServer())
      .post('/tasks')
      .set('Authorization', `Bearer ${accessToken}`)
      .send({
        title: 'Setup NestJS project',
        description: 'Initialize with MongoDB and JWT',
      })
      .expect(201);

    taskId = res.body.data._id;
    expect(res.body.data.done).toBe(false);
  });

  it('Step 6: Create second task', async () => {
    await request(app.getHttpServer())
      .post('/tasks')
      .set('Authorization', `Bearer ${accessToken}`)
      .send({
        title: 'Write E2E tests',
        description: 'Cover auth and CRUD flows',
      })
      .expect(201);
  });

  it('Step 7: Verify both tasks exist', async () => {
    const res = await request(app.getHttpServer())
      .get('/tasks')
      .set('Authorization', `Bearer ${accessToken}`)
      .expect(200);

    expect(res.body.data.length).toBe(2);
  });

  it('Step 8: Complete the first task', async () => {
    const res = await request(app.getHttpServer())
      .patch(`/tasks/${taskId}`)
      .set('Authorization', `Bearer ${accessToken}`)
      .send({ done: true })
      .expect(200);

    expect(res.body.data.done).toBe(true);
    expect(res.body.data.title).toBe('Setup NestJS project');
  });

  it('Step 9: Refresh tokens (simulating token expiry)', async () => {
    const res = await request(app.getHttpServer())
      .post('/auth/refresh')
      .set('Cookie', refreshCookie)
      .expect(200);

    // Update tokens
    accessToken = res.body.data.accessToken;
    const cookies = res.headers['set-cookie'];
    const newCookie = Array.isArray(cookies)
      ? cookies.find((c: string) => c.startsWith('refreshToken='))
      : cookies;
    if (newCookie) refreshCookie = newCookie;
  });

  it('Step 10: Old refresh token should be invalid (rotation)', async () => {
    // The old refresh cookie was already rotated in Step 9
    // Using it again should fail (or trigger reuse detection)
    // Note: this depends on whether the old cookie is still stored
    // In practice, the old cookie was replaced in Step 9

    // Verify new token works
    const res = await request(app.getHttpServer())
      .get('/tasks')
      .set('Authorization', `Bearer ${accessToken}`)
      .expect(200);

    expect(res.body.data.length).toBe(2);
  });

  it('Step 11: Cannot delete task without admin role', async () => {
    await request(app.getHttpServer())
      .delete(`/tasks/${taskId}`)
      .set('Authorization', `Bearer ${accessToken}`)
      .expect(403);
  });

  it('Step 12: Logout', async () => {
    await request(app.getHttpServer())
      .post('/auth/logout')
      .set('Authorization', `Bearer ${accessToken}`)
      .set('Cookie', refreshCookie)
      .expect(200);
  });

  it('Step 13: Refresh should fail after logout', async () => {
    await request(app.getHttpServer())
      .post('/auth/refresh')
      .set('Cookie', refreshCookie)
      .expect((res) => {
        // Should be 401 or 403 — token was revoked
        expect([401, 403]).toContain(res.status);
      });
  });
});

Why sequential steps in one describe block?

This test tells a story. It's not testing isolated features — it's testing the user journey. Step 9 depends on the token from Step 3. Step 11 verifies that the role system works with the task from Step 5. If any step fails, the story breaks and you know exactly where in the user journey the bug is.

Jest runs tests within a describe block in declaration order by default. The shared variables (accessToken, taskId) carry state across steps, simulating a real client session.


Running Tests

bash
# Run all unit tests
npm test

# Run unit tests in watch mode (re-runs on file changes)
npm run test:watch

# Run with coverage report
npm run test:cov

# Run E2E tests
npm run test:e2e

# Run a specific test file
npx jest --config ./test/jest-e2e.json auth.e2e

# Run tests matching a pattern
npx jest --testPathPattern="tasks.service"

What the output looks like:

ts
 PASS  src/tasks/tasks.service.spec.ts
  TasksService
    findAll
      ✓ should return an array of tasks for the user (5 ms)
      ✓ should return empty array when user has no tasks (2 ms)
    findOne
      ✓ should return a task if found and user owns it (3 ms)
      ✓ should throw NotFoundException if task does not exist (4 ms)
      ✓ should throw ForbiddenException if user does not own the task (2 ms)
    create
      ✓ should create and return a new task (2 ms)
    update
      ✓ should update and return the task if user owns it (3 ms)
      ✓ should throw ForbiddenException if non-owner tries to update (2 ms)
    remove
      ✓ should delete the task if user owns it (2 ms)
      ✓ should throw NotFoundException for non-existent task (1 ms)
      ✓ should throw ForbiddenException if non-owner tries to delete (2 ms)

 PASS  test/app.e2e-spec.ts (8.234 s)
  Full Application Flow (e2e)
    ✓ Step 1: Register a new account (156 ms)
    ✓ Step 2: Cannot access tasks before login (12 ms)
    ✓ Step 3: Login with registered credentials (312 ms)
    ✓ Step 4: Task list is empty after registration (15 ms)
    ✓ Step 5: Create first task (23 ms)
    ✓ Step 6: Create second task (18 ms)
    ✓ Step 7: Verify both tasks exist (14 ms)
    ✓ Step 8: Complete the first task (22 ms)
    ✓ Step 9: Refresh tokens (278 ms)
    ✓ Step 10: Old refresh token should be invalid (16 ms)
    ✓ Step 11: Cannot delete task without admin role (11 ms)
    ✓ Step 12: Logout (265 ms)
    ✓ Step 13: Refresh should fail after logout (8 ms)

Test Suites: 5 passed, 5 total
Tests:       42 passed, 42 total
Time:        12.456 s

Unit tests: milliseconds. E2E tests: seconds (MongoDB startup + bcrypt hashing). Both are acceptable for CI/CD.


What Each Test Type Catches

Bug TypeUnit TestE2E Test
Service logic error (wrong ownership check)YesYes
Missing module import/exportNoYes
Guard not applied to routeNoYes
Pipe validation misconfiguredNoYes
Interceptor not wrapping responseNoYes
DTO missing decoratorNoYes
Cookie not being setNoYes
CORS misconfigurationNoYes
bcrypt hashing brokenNo (mocked)Yes
Edge case in complex business logicYes (fast)Yes (slow)
Database query returning wrong dataNo (mocked)Yes

Unit tests are fast and focused. E2E tests are slow and realistic. You need both. Unit tests for rapid feedback during development. E2E tests for confidence before deployment.

Analogy

Notice how the rig catches a weak hinge but never a wiring fault between two parts, while the track drive catches both. A crash rig can't tell you the brake pedal isn't connected to the brakes — only driving the whole car does. That's why "the door passed on the rig" and "the car drives safely" are two different guarantees, and you want both.


The Testing Decision Framework

text
"Should I write a test for this?"

Is it business logic? (ownership check, token rotation, reuse detection)
  → Unit test the service method

Is it a security boundary? (auth guard, roles guard)
  → Unit test the guard + E2E test the endpoint

Is it a user-facing flow? (register → login → use → logout)
  → E2E test the journey

Is it a configuration/wiring concern? (module imports, global pipes)
  → E2E test catches it automatically

Is it a utility function? (pure function, no dependencies)
  → Unit test directly, no NestJS testing module needed

Analogy

This framework is the safety engineer's checklist for deciding rig-test versus track-test. Fragile internal parts (business logic) go on the rig where you can hammer them cheaply and repeatedly; anything about the parts working together on the road (auth flows, wiring, full journeys) has to be driven on the track. Match the test to what could actually break, not to a quota.


That's the full suite — 9 files: 4 unit tests, 3 E2E tests, 1 shared setup, and 1 jest config. Drop them into your project matching the file paths above.

To integrate with your existing project:

bash
# Install test dependencies
npm install -D mongodb-memory-server supertest @types/supertest

# Add to package.json scripts (if not already there)
# "test": "jest"
# "test:e2e": "jest --config ./test/jest-e2e.json"

# Copy unit tests into src/ alongside their source files
# Copy test/ folder to project root

# Run
npm test              # unit tests (~2 seconds)
npm run test:e2e      # e2e tests (~10-15 seconds)

First E2E run will be slower — mongodb-memory-server downloads a MongoDB binary (~100MB, cached after that). Every subsequent run uses the cache.

That's the complete NestJS journey — from "what's a module?" to a production-grade, fully tested backend with every architectural layer understood, implemented, and verified.