Skip to the content

Lesson 206 of 296

Back-end testing: unit, integration and end-to-end

What you will learn

  • The three levels of back-end tests
  • Unit testing services with fakes
  • Integration testing HTTP endpoints with Supertest
  • Testing with a real database (Testcontainers)
  • End-to-end and contract tests
  • What makes a good test suite
On this page

Three levels

LevelTestsDependenciesSpeed
UnitOne function or class: business rules, validation, calculationsReplaced with fakes or mocksMilliseconds
IntegrationSeveral parts together: route + validation + service + real databaseReal database (in a container), fake external APIsSeconds
End-to-endThe deployed system through its public API or UIEverything real (a test environment)Slowest

Unit tests: design for testability

Code that creates its own dependencies is hard to test. Pass dependencies in (dependency injection, Lesson 208), so a test can give a fake:

TypeScript
type User = { id: string; email: string; passwordHash: string };

export interface UserRepository {
  findByEmail(email: string): Promise<User | null>;
  create(user: Omit<User, "id">): Promise<User>;
}

export interface Hasher {
  hash(password: string): Promise<string>;
}

export class EmailTakenError extends Error {}

export class SignupService {
  constructor(
    private readonly users: UserRepository,
    private readonly hasher: Hasher
  ) {}

  async signup(email: string, password: string): Promise<{ id: string; email: string }> {
    const normalised = email.trim().toLowerCase();
    if (await this.users.findByEmail(normalised)) throw new EmailTakenError("Email already registered");
    const user = await this.users.create({ email: normalised, passwordHash: await this.hasher.hash(password) });
    return { id: user.id, email: user.email };
  }
}

The unit test uses an in-memory fake repository: no database, runs in milliseconds:

TypeScript
import { describe, it, expect } from "vitest";

class InMemoryUsers implements UserRepository {
  users: User[] = [];
  async findByEmail(email: string) {
    return this.users.find((u) => u.email === email) ?? null;
  }
  async create(data: Omit<User, "id">) {
    const user = { id: `u${this.users.length + 1}`, ...data };
    this.users.push(user);
    return user;
  }
}

const fakeHasher: Hasher = { hash: async (p) => `hashed:${p}` };

describe("SignupService", () => {
  it("normalises the email and never returns the hash", async () => {
    const repo = new InMemoryUsers();
    const result = await new SignupService(repo, fakeHasher).signup("  Sam@Example.COM ", "pw-123456789");
    expect(result).toEqual({ id: "u1", email: "sam@example.com" });
    expect(repo.users[0]?.passwordHash).toBe("hashed:pw-123456789");
  });

  it("rejects a duplicate email, ignoring case", async () => {
    const service = new SignupService(new InMemoryUsers(), fakeHasher);
    await service.signup("sam@example.com", "pw-123456789");
    await expect(service.signup("SAM@example.com", "other-password")).rejects.toBeInstanceOf(EmailTakenError);
  });
});

A fake is a simple working implementation (the in-memory repository). A mock (vi.fn()) records calls. Prefer fakes for repositories: tests stay readable and do not break when internal call details change.

Integration tests with Supertest

Supertest sends real HTTP requests to your Express (or NestJS, or Fastify) app without starting a network server. Continuing in the same test file:

TypeScript
import express from "express";
import request from "supertest";
import { z } from "zod";

export function buildApp(service: SignupService) {
  const app = express();
  app.use(express.json());
  const Body = z.object({ email: z.email(), password: z.string().min(12) });

  app.post("/signup", async (req, res) => {
    const parsed = Body.safeParse(req.body);
    if (!parsed.success) {
      res.status(422).json({ error: "Invalid signup details" });
      return;
    }
    try {
      res.status(201).json(await service.signup(parsed.data.email, parsed.data.password));
    } catch (err) {
      if (err instanceof EmailTakenError) {
        res.status(409).json({ error: err.message });
        return;
      }
      throw err;
    }
  });
  return app;
}

describe("POST /signup", () => {
  const app = buildApp(new SignupService(new InMemoryUsers(), fakeHasher));

  it("creates a user", async () => {
    const res = await request(app).post("/signup").send({ email: "aisha@example.com", password: "long-password-1" });
    expect(res.status).toBe(201);
    expect(res.body).toEqual({ id: "u1", email: "aisha@example.com" });
    expect(res.body).not.toHaveProperty("passwordHash");
  });

  it("returns 409 for a duplicate", async () => {
    const res = await request(app).post("/signup").send({ email: "AISHA@example.com", password: "long-password-2" });
    expect(res.status).toBe(409);
  });

  it("returns 422 for invalid input", async () => {
    const res = await request(app).post("/signup").send({ email: "not-an-email", password: "short" });
    expect(res.status).toBe(422);
  });
});

Exporting a buildApp function (separate from the line that calls listen) is what makes the app testable.

Testing with a real database

Fakes cannot catch SQL mistakes, missing indexes, constraint violations or transaction bugs. For integration tests, use a real database of the same kind as production:

  • Testcontainers starts a throwaway PostgreSQL (or Redis, or anything) in Docker for the test run, runs migrations, and removes it afterwards.
  • Keep tests independent: wrap each test in a transaction that is rolled back, or truncate tables between tests, and create the data each test needs (factories or builders).
  • Do not use SQLite in tests when production uses PostgreSQL; behaviour differs.
  • External APIs (payments, email): fake them with MSW (Lesson 185), Nock, or the provider's test mode, and test your webhook handlers with recorded payloads.

End-to-end and contract tests

  • E2E API tests run against a deployed test environment: sign up, log in, create an order, check the email was queued. Few, focused on critical journeys.
  • Contract tests (for example with Pact) check that a provider API still matches what its consumers expect, so teams can deploy services independently without breaking each other. OpenAPI-based schema checks are a lighter alternative.
  • Load tests (k6, Artillery) measure performance under traffic before launches.

What makes a good back-end test suite

  • Tests the behaviour and the error paths: validation errors, 401 and 403 and 404, conflicts, external failures, timeouts.
  • Includes authorisation tests (Lesson 203): user A cannot touch user B's data.
  • Fast enough to run on every commit; deterministic (control time with fake timers or an injected clock, control randomness and IDs).
  • Runs in CI on every pull request (Lesson 251).
  • Coverage is a guide, not a goal (Lesson 271).

How to say it in an interview

"I write unit tests for business logic with dependencies injected and replaced by in-memory fakes, so they run in milliseconds. Integration tests exercise the HTTP layer with Supertest against an exported app, through validation, services and a real database of the same engine as production started with Testcontainers, with isolated data per test and external APIs faked with MSW. A few end-to-end tests cover critical journeys in a test environment, and contract tests protect service boundaries. I always test error and authorisation paths, keep tests deterministic, and run everything in CI."

Key words

WordMeaning
Unit testTests one piece in isolation
Integration testTests parts working together, often with a real database
FakeA simple working stand-in, like an in-memory repository
SupertestSends HTTP requests to an app in tests
TestcontainersStarts real services in Docker for tests
Contract testChecks an API still matches what consumers expect
DeterministicGives the same result every run

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.