The test infrastructure has several "API" surfaces: the configuration files that define how tests run, the mock server that intercepts HTTP requests, and the CI workflow that orchestrates everything. Let me walk through each interface.
Vitest configuration
The test runner config is the contract between the test files and the execution environment. I use Vitest (not Jest) because it is natively compatible with Vite's transform pipeline, supports ESM out of the box, and runs tests in worker threads for parallel execution.
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
test: {
environment: "jsdom",
globals: true,
setupFiles: ["./test-setup.ts"],
coverage: {
provider: "v8",
reporter: ["text", "html", "lcov"],
exclude: ["node_modules/", "test-setup.ts"],
},
testTimeout: 10_000,
hookTimeout: 10_000,
retry: process.env.CI ? 2 : 0,
},
});
The setup file runs before every test file. It extends Jest DOM matchers (.toBeInTheDocument(), .toHaveTextContent()), mocks browser APIs that jsdom doesn't implement (IntersectionObserver, ResizeObserver), and clears the DOM after each test.
import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react";
import { afterEach, vi } from "vitest";
// Clean up DOM after each test
afterEach(() => {
cleanup();
});
// Mock IntersectionObserver if not in jsdom
if (typeof IntersectionObserver === "undefined") {
class MockIntersectionObserver {
observe() {}
unobserve() {}
disconnect() {}
}
vi.stubGlobal("IntersectionObserver", MockIntersectionObserver);
}
// Mock ResizeObserver
if (typeof ResizeObserver === "undefined") {
class MockResizeObserver {
observe() {}
unobserve() {}
disconnect() {}
}
vi.stubGlobal("ResizeObserver", MockResizeObserver);
}
Mock Service Worker (MSW)
MSW intercepts HTTP requests at the network level — the same requests that the application's fetch calls. Unlike module-level mocks that replace the API client functions, MSW intercepts at the fetch event level, which means the entire HTTP pipeline runs: request serialization, header processing, response parsing. This catches bugs that module mocks miss, like incorrect content-type headers or malformed response bodies.
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
const handlers = [
http.get("/api/users", () => {
return HttpResponse.json([
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
]);
}),
http.post("/api/login", async ({ request }) => {
const body = await request.json();
if (body.email === "invalid@test.com") {
return HttpResponse.json(
{ error: "Invalid credentials" },
{ status: 401 }
);
}
return HttpResponse.json({ token: "fake-jwt-token" });
}),
];
export const server = setupServer(...handlers);
The server lifecycle is managed in the setup file:
import { server } from "./handlers";
// Start MSW before all tests
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
// Reset handlers between tests
afterEach(() => server.resetHandlers());
// Clean up after all tests
afterAll(() => server.close());
I use onUnhandledRequest: 'error' because it catches the case where a test triggers an API call that no handler matches. Without this, the request passes through to the real network (which doesn't exist in CI) and fails with a cryptic connection refused error.
Playwright configuration
import { defineConfig } from "@playwright/test";
export default defineConfig({
testDir: "./e2e",
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 4 : undefined,
reporter: [
["html"],
["list"],
["junit", { outputFile: "test-results/junit.xml" }],
],
use: {
baseURL: process.env.BASE_URL || "http://localhost:3000",
trace: "on-first-retry",
screenshot: "only-on-failure",
},
projects: [
{
name: "chromium",
use: { browserName: "chromium" },
},
{
name: "firefox",
use: { browserName: "firefox" },
},
{
name: "webkit",
use: { browserName: "webkit" },
},
],
});
Three key decisions in this config. First, fullyParallel: true — Playwright runs each test file in its own worker, which means they execute in parallel across available CPU cores. Second, trace: "on-first-retry" — Playwright records a full trace (DOM snapshots, network logs, console messages) only when a test fails on the first attempt and is retried. This gives you forensic debugging without the storage cost of always-on tracing. Third, multi-browser projects — I run critical tests against Chromium, Firefox, and WebKit, but most tests run only on Chromium to save time.