TypeScript Testing Strategies: From Unit to E2E
A comprehensive guide to testing TypeScript applications. Covers unit testing with Vitest, integration testing with Testcontainers, contract testing with Pact, and E2E with Playwright.

- Rol
- Andrés RW
- Año
- Reading time
- 15 min de lectura
- Actualizado
TypeScript Testing Strategies: From Unit to E2E
Testing is not a phase—it's a design tool. This guide walks through a complete testing strategy for TypeScript applications, from fast unit tests to reliable end-to-end suites.
The Testing Pyramid (Revisited)
The classic pyramid still holds, but modern tooling shifts where the boundaries lie:
┌─────────────┐
│ E2E │ ← Few, critical user journeys (Playwright)
│ (5-10%) │
┌───────────────┐
│ Contract │ ← API contracts between services (Pact)
│ (10-15%) │
┌─────────────────┐
│ Integration │ │ Real DB, real HTTP, real queue (Testcontainers)
│ (20-30%) │ │
┌───────────────────┐
│ Unit │ │ Pure logic, mocked boundaries (Vitest)
│ (50-60%) │ │
└───────────────────┘
Unit Testing with Vitest
Vitest is now the default choice for TypeScript projects—fast, type-safe, and Jest-compatible.
Setup
// vitest.config.ts
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
import path from "path";
export default defineConfig({
plugins: [react()],
test: {
environment: "jsdom",
globals: true,
setupFiles: ["./test/setup.ts"],
include: ["src/**/*.test.ts", "src/**/*.test.tsx"],
coverage: {
provider: "v8",
reporter: ["text", "json", "html"],
thresholds: {
lines: 80,
functions: 80,
branches: 70,
statements: 80,
},
},
},
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
});
Testing Domain Logic
// domain/order/order.entity.test.ts
import { describe, it, expect } from "vitest";
import { Order, OrderId, OrderItem } from "./order.entity";
describe("Order Entity", () => {
it("creates an order with valid items", () => {
const items = [
OrderItem.create(ProductId.generate(), 2, Money.usd(29.99)),
OrderItem.create(ProductId.generate(), 1, Money.usd(49.99)),
];
const order = Order.create(CustomerId.generate(), items);
expect(order.id).toBeInstanceOf(OrderId);
expect(order.status).toBe("pending");
expect(order.items).toHaveLength(2);
});
it("throws when creating order with no items", () => {
expect(() => Order.create(CustomerId.generate(), [])).toThrow(
"Order must have at least one item"
);
});
it("transitions from pending to paid", () => {
const order = Order.create(CustomerId.generate(), [validItem()]);
const paidOrder = order.markAsPaid();
expect(paidOrder.status).toBe("paid");
expect(paidOrder.id).toBe(order.id); // Same identity
});
it("throws when marking non-pending order as paid", () => {
const order = Order.create(CustomerId.generate(), [validItem()]);
const paid = order.markAsPaid();
expect(() => paid.markAsPaid()).toThrow("Only pending orders can be marked as paid");
});
});
Property-Based Testing with fast-check
For complex domain logic, property-based testing finds edge cases unit tests miss.
// domain/order/order.entity.pbt.test.ts
import { describe, it, expect } from "vitest";
import * as fc from "fast-check";
import { Order, OrderItem, Money } from "./order.entity";
describe("Order Properties", () => {
it("total is sum of item subtotals", () => {
fc.assert(
fc.property(fc.array(orderItemArbitrary(), { minLength: 1 }), (items) => {
const order = Order.create(CustomerId.generate(), items);
const expectedTotal = items.reduce(
(sum, item) => sum + item.quantity * item.price.amount,
0
);
expect(order.total.amount).toBe(expectedTotal);
})
);
});
it("adding items never removes existing ones", () => {
fc.assert(
fc.property(
fc.array(orderItemArbitrary(), { minLength: 1 }),
orderItemArbitrary(),
(items, newItem) => {
const order = Order.create(CustomerId.generate(), items);
const withNew = order.addItem(newItem);
expect(withNew.items).toContainEqual(newItem);
items.forEach((item) =>
expect(withNew.items).toContainEqual(item)
);
}
)
);
});
});
Integration Testing with Testcontainers
Testcontainers spins up real databases, message brokers, and services in Docker containers for integration tests.
PostgreSQL Integration Test
// infrastructure/persistence/prisma-order.repository.integration.test.ts
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { GenericContainer, StartedTestContainer } from "testcontainers";
import { PrismaClient } from "@prisma/client";
import { PrismaOrderRepository } from "./prisma-order.repository";
import { Order, OrderId, CustomerId } from "@/domain/order";
describe("PrismaOrderRepository (Integration)", () => {
let container: StartedTestContainer;
let prisma: PrismaClient;
let repo: PrismaOrderRepository;
beforeAll(async () => {
container = await new GenericContainer("postgres:16-alpine")
.withEnvironment({
POSTGRES_USER: "test",
POSTGRES_PASSWORD: "test",
POSTGRES_DB: "orders_test",
})
.withExposedPorts(5432)
.start();
const url = `postgresql://test:test@localhost:${container.getMappedPort(5432)}/orders_test`;
prisma = new PrismaClient({ datasources: { db: { url } } });
await prisma.$connect();
await prisma.$executeRaw`CREATE SCHEMA IF NOT EXISTS public`;
await prisma.$executeRaw`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`;
// Run migrations
await prisma.$executeRawUnsafe(`
CREATE TABLE "Order" (
id UUID PRIMARY KEY,
"customerId" UUID NOT NULL,
status TEXT NOT NULL,
items JSONB NOT NULL,
"createdAt" TIMESTAMP NOT NULL
)
`);
repo = new PrismaOrderRepository(prisma);
});
afterAll(async () => {
await prisma.$disconnect();
await container.stop();
});
it("saves and retrieves an order", async () => {
const order = Order.create(CustomerId.generate(), [validItem()]);
await repo.save(order);
const found = await repo.findById(order.id);
expect(found).not.toBeNull();
expect(found!.id).toEqual(order.id);
expect(found!.customerId).toEqual(order.customerId);
expect(found!.items).toHaveLength(1);
});
it("returns null for non-existent order", async () => {
const found = await repo.findById(OrderId.generate());
expect(found).toBeNull();
});
});
Contract Testing with Pact
When services communicate via HTTP, Pact ensures provider and consumer stay compatible.
Consumer Test (Frontend/Client)
// tests/contracts/order-api.consumer.test.ts
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { PactV3, MatchersV3 } from "@pact-foundation/pact";
import { OrderApiClient } from "@/infrastructure/http/order-api.client";
const { like, eachLike } = MatchersV3;
describe("Order API Contract (Consumer)", () => {
const provider = new PactV3({
consumer: "frontend",
provider: "orders-api",
logLevel: "WARN",
});
beforeAll(() => provider.setup());
afterAll(() => provider.finalize());
it("returns order list for customer", async () => {
provider
.given("customer has orders")
.uponReceiving("a request for customer orders")
.withRequest({
method: "GET",
path: "/api/customers/123/orders",
headers: { Accept: "application/json" },
})
.willRespondWith({
status: 200,
headers: { "Content-Type": "application/json" },
body: eachLike({
id: like("uuid"),
status: like("pending"),
total: like({ amount: 100, currency: "USD" }),
createdAt: like("2024-01-15T10:30:00Z"),
}),
});
await provider.executeTest(async (mockServer) => {
const client = new OrderApiClient(mockServer.url);
const orders = await client.getOrdersByCustomer("123");
expect(orders).toHaveLength(1);
expect(orders[0].status).toBe("pending");
});
});
});
E2E Testing with Playwright
Playwright handles complex user journeys across browsers with excellent TypeScript support.
Page Object Model
// e2e/pages/order-page.ts
import { Page, Locator, expect } from "@playwright/test";
export class OrderPage {
constructor(private page: Page) {}
async goto(orderId: string) {
await this.page.goto(`/orders/${orderId}`);
await this.page.waitForLoadState("networkidle");
}
async expectOrderVisible(orderId: string) {
await expect(this.page.locator("[data-testid=order-id]")).toHaveText(orderId);
}
async clickPayButton() {
await this.page.click("[data-testid=pay-button]");
await this.page.waitForLoadState("networkidle");
}
async expectStatus(status: string) {
await expect(this.page.locator("[data-testid=order-status]")).toHaveText(status);
}
}
Critical User Journey Test
// e2e/critical-journeys/order-payment.spec.ts
import { test, expect } from "@playwright/test";
import { OrderPage } from "../pages/order-page";
test.describe("Order Payment Flow", () => {
test("customer can pay for pending order", async ({ page }) => {
const orderPage = new OrderPage(page);
// Setup: create order via API
const orderId = await createTestOrder("customer-123");
// Navigate and verify
await orderPage.goto(orderId);
await orderPage.expectOrderVisible(orderId);
await orderPage.expectStatus("pending");
// Pay
await orderPage.clickPayButton();
// Verify payment success
await orderPage.expectStatus("paid");
await expect(page.locator("[data-testid=success-toast]")).toBeVisible();
});
test("payment fails gracefully for already paid order", async ({ page }) => {
const orderPage = new OrderPage(page);
const orderId = await createTestOrder("customer-123", { status: "paid" });
await orderPage.goto(orderId);
await orderPage.expectStatus("paid");
// Pay button should be disabled
await expect(page.locator("[data-testid=pay-button]")).toBeDisabled();
});
});
CI/CD Pipeline
# .github/workflows/test.yml
name: Test
on: [push, pull_request]
jobs:
unit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 20, cache: npm }
- run: npm ci
- run: npm run test:unit
integration:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16-alpine
env: { POSTGRES_PASSWORD: test }
ports: [5432:5432]
options: >-
--health-cmd "pg_isready -U postgres"
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 20, cache: npm }
- run: npm ci
- run: npm run test:integration
contract:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 20, cache: npm }
- run: npm ci
- run: npm run test:contract
- uses: pactflow/publish-action@v1
if: github.event_name == 'push'
with: { pact-broker-url: ${{ secrets.PACT_BROKER_URL }} }
e2e:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 20, cache: npm }
- run: npm ci
- run: npm run build
- run: npx playwright install --with-deps chromium
- run: npm run test:e2e
Summary
A robust TypeScript testing strategy:
| Layer | Tool | Speed | Confidence | Scope | |-------|------|-------|------------|-------| | Unit | Vitest + fast-check | ~ms | High | Pure logic | | Integration | Testcontainers | ~s | High | Real adapters | | Contract | Pact | ~ms | Medium | API boundaries | | E2E | Playwright | ~min | Highest | Critical paths |
Invest in the bottom layers—they run fast, catch regressions early, and serve as living documentation. Reserve E2E for the 3-5 critical journeys that define your product's value.
Part 2 of "TypeScript at Scale". Next: Event-Driven Architecture with TypeScript—domain events, outbox pattern, and eventual consistency.
Etiquetas
También te puede interesar
Arquitectura12 min de lectura
Building Scalable Architectures with TypeScript: Patterns That Scale
A deep dive into architectural patterns that help TypeScript applications scale from startup to enterprise. Covers module boundaries, dependency injection, and domain-driven design principles.
Arquitectura18 min de lectura
Migrating a Legacy Monolith to Microservices: A Case Study
Real-world case study of migrating a 500K LOC PHP monolith to a TypeScript/Node.js microservices architecture. Covers strangler fig pattern, data synchronization, and zero-downtime deployment.
Carrera10 min de lectura
Engineering Culture: Building Developer Experience That Scales
How to build a developer experience (DX) culture that attracts talent, accelerates delivery, and retains engineers. Covers tooling, documentation, onboarding, and psychological safety.