Test Server Logic with Vitest
Updated
IntermediateWhat you'll learn
~30 min- Configure Vitest with a Node environment for server code and a jsdom environment (a simulated browser DOM) for the few tests that need one
- Test a route handler by seeding a session and mocking only the cookie jar and the database, never the guard
- Prove session expiry at SESSION_MAX_SECONDS and prove that withPermission() denies by default for every role and action pair
- Unit test pagination, schema validation and safe error output, then read a V8 coverage report (coverage measured by the JavaScript engine itself)
What you can prove without an identity provider
Every route handler in the reference app does the same four things in order: identify the caller, decide whether the caller may do this, validate the input, and answer in the shared response shape. Each of those is code you own, and none of it needs an identity provider or a database server to be tested. You will build a Vitest suite that proves them, including two tests that carry the most weight in a security review: the session ends at SESSION_MAX_SECONDS from Lesson 3, and withPermission() refuses anyone it has not been told to allow.
The suite runs in well under a few seconds because nothing touches a network. What it does not prove is that your real identity provider sends the role names you expect or that your real database accepts your query. Lesson 13 narrows that gap with a browser, and your first deployment closes it.
Vitest runs only on the Node lines listed in the baseline table of Lesson 2. An older Node line that your build agent or base image still carries is not supported, so check the runner image before you pin a test job.
| Problem | The pattern | Where your platform lesson lands it | You decide |
|---|---|---|---|
| Test server code with no provider or database | In-memory session store, a cookie jar mock, and a database mock beneath withPool() (the alternative: run the handlers against a disposable SQL container) | Unchanged on every platform: the mocks sit above the platform seam. Lessons 34, 35 and 36 are where a real provider and database come in | Which layer owns database truth: your mocks or a real engine |
| Make the guard testable | Call the real withPermission() and mock the session beneath it (the alternative: test the guard once, trust it elsewhere) | Unchanged | How many routes the matrix covers |
| Decide how much coverage is enough | A threshold in config that fails the run (the alternative: review-only, no gate) | Unchanged | The number, and who may lower it |
| Tests that gate an agent’s work | Protected paths: code owners (named people whose review a change to those files requires) on the test files, plus a hook or diff check | 37: the code host’s owner and required-review settings | Who owns the tests, and who may not |
Plan the change with your agent
Open your workspace agent at the project root with the project-memory file from Lesson 2 in place, switch to Plan mode (Shift+Tab, /plan, or the desktop app’s mode picker), and ask:
Read src/lib/auth/session.ts and with-permission.ts, and plan a Vitest setup that runs server tests in Node, component tests in jsdom, and tests the real auth guards with an in-memory session jar. Ask anything unclear.What to check in the plan before you approve
vitest.config.tsdefaults tonode, aliases"@"to./src, defines"server"(src/**/*.test.ts,node) and"components"(src/**/*.test.tsx,jsdom) projects, enablesunstubEnvs: true, and configuresv8coverage oversrc/libandsrc/app/api.src/test/setup.tsandsrc/test/cookie-jar.tsmocknext/headers(cookies()) and@/lib/auth/store(an in-memorySessionStore) while keepingwithPermission,requireSession, andisExpiredunmocked.src/test/session-helpers.tsexportssignInAs(roles, createdAtMs?)accepting raw provider role names (such as"Intake.Operator") andsignOut()to reset the cookie jar and session records.
If the first plan mocks withPermission() or passes mapped short role names into signInAs(), nudge it before approving:
Mock only next/headers and the session store; never mock requireSession, isExpired, or withPermission, and seed raw provider role names.- Typed in the terminal:
claude - Mode:Plan mode
- You type in the session: Read src/lib/auth/session.ts and with-permission.ts, and plan a Vitest setup that runs server tests in Node, component tests in jsdom, and tests the real auth guards with an in-memory session jar. Ask anything unclear.
- The tool replies: Proposed plan: 1. vitest.config.ts: default environment node, alias '@' to ./src, inline 'server' and 'components' projects, and v8 coverage. 2. src/test/cookie-jar.ts and src/test/setup.ts: mock next/headers and @/lib/auth/store. 3. src/test/session-helpers.ts: signInAs(roles, createdAtMs?) and signOut(). Should signInAs accept raw provider role claims like 'Intake.Operator', and confirm we leave requireSession and withPermission unmocked?
- You type in the session: Mock only next/headers and the session store; never mock requireSession, isExpired, or withPermission, and seed raw provider role names. Build it.
- The tool replies: Created: - vitest.config.ts: node by default, two inline projects (server, components), v8 coverage, unstubEnvs - src/test/setup.ts: mocks next/headers and @/lib/auth/store - src/test/cookie-jar.ts: a Map the mock cookies() reads and writes - src/test/session-helpers.ts: signInAs(roles, createdAtMs?) and signOut() Dev dependencies still to install: jsdom and @vitest/coverage-v8. I did not run the install. I used resolve.alias for "@" rather than a path-plugin, so the config has no extra dependency.
- Typed in the terminal:
npm install --save-dev jsdom @vitest/coverage-v8 && npx vitest run - The tool replies: added 2 packages No test files found, exiting with code 1 include: src/**/*.test.ts, src/**/*.test.tsx exclude: node_modules, .next, e2e
- You type in the session: Good, that is the right failure. The no-tests state should fail loudly. Now write the expiry and withPermission tests, using the real guard.
- The tool replies: I will write two files: 1. src/lib/auth/session-expiry.test.ts: fake timers, a session signed in at t0, requireSession() succeeds one second before SESSION_MAX_SECONDS and rejects at it, and the expired record is deleted from the store. 2. src/lib/auth/with-permission.test.ts: a table of role by action pairs with the expected status, plus the cases a table of allowed pairs cannot show: no cookie gives 401, an unknown role gives 403, and the handler spy is never called on a denial. One assumption to check: I am calling withPermission(resource, action, handler). If your Lesson 5 version takes a different shape, tell me and I will adapt the calls, not the assertions.
- Typed in the terminal:
npx vitest run --project server - The tool replies: FAIL |server| src/lib/auth/with-permission.test.ts > withPermission: role by action > viewer may read: 200 AssertionError: expected 403 to be 200 Test Files 1 failed | 4 passed (5) The guard is right and my seed was wrong. In the table I passed the closed role name 'viewer' to signInAs, but the helper takes the provider's raw names. Lesson 5's resolveRole maps raw names (Intake.Viewer), so 'viewer' is unknown and default deny applied. I changed the table's inputs. I did not touch an expected status, the guard, or the config. A red test that I could turn green by editing the assertion is the case to flag, so I am flagging it.
Illustrative session; exact output varies by tool and agency configuration.
The configuration it produces looks like this. Read it against the options you asked for.
REFERENCE CONFIG vitest.config.ts: Node and jsdom projects with V8 coverage thresholds open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { defineConfig } from "vitest/config";import { fileURLToPath } from "node:url";
export default defineConfig({ resolve: { alias: { "@": fileURLToPath(new URL("./src", import.meta.url)) }, }, test: { environment: "node", exclude: ["node_modules", ".next", "e2e"], setupFiles: ["./src/test/setup.ts"], testTimeout: 10_000, unstubEnvs: true, coverage: { provider: "v8", include: ["src/lib/**/*.ts", "src/app/api/**/*.ts"], exclude: ["**/*.test.ts"], // The numbers below are this team's decision. They are not a standard. thresholds: { lines: 80, branches: 70 }, }, projects: [ { test: { name: "server", environment: "node", include: ["src/**/*.test.ts"] } }, { test: { name: "components", environment: "jsdom", include: ["src/**/*.test.tsx"] } }, ], },});Inline projects inherit the root options, so the alias, the setup file and the timeout apply to both. Because arrays are merged, a project that adds its own setupFiles appends to the root list instead of replacing it.
Two environments, one rule for choosing
Server code (route handlers, session logic, schemas) runs in Node and should be tested there. A browser-like DOM is only needed when the code under test touches document or window. The directory convention above makes the choice automatic: .test.ts runs in Node, .test.tsx runs in jsdom.
For the odd file that breaks the convention, a docblock at the top of the file overrides the environment for that file alone (reference test shown):
/** * @vitest-environment jsdom */import { expect, it } from "vitest";import { announce } from "./announce";
it("writes the message into the polite live region", () => { document.body.innerHTML = '<div id="live" aria-live="polite"></div>'; announce("Vehicle created"); expect(document.getElementById("live")?.textContent).toBe("Vehicle created");});If you reach for the docblock often, the files are in the wrong place.
A route handler test that runs in jsdom can pass because a browser global exists that the Node server does not have. Run server code in the environment it ships in.
The setup that makes the guard testable
Two mocks sit beneath your code and nothing above it. The cookie jar replaces Next.js’s request-scoped cookies(), which only exists inside a real request. The store replaces the production session store with the in-memory one from Lesson 3. Here is the reference cookie jar in src/test/cookie-jar.ts that your agent generates:
export const jar = new Map<string, string>(); REFERENCE TEST src/test/setup.ts: Vitest setup mocking next/headers and the session store open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { vi } from "vitest";
vi.mock("next/headers", async () => { const { jar } = await import("./cookie-jar"); return { cookies: async () => ({ get: (name: string) => (jar.has(name) ? { name, value: jar.get(name)! } : undefined), has: (name: string) => jar.has(name), set: (name: string, value: string) => void jar.set(name, value), delete: (name: string) => void jar.delete(name), }), };});
vi.mock("@/lib/auth/store", async () => { const { memoryStore } = await import("./session-helpers"); return { store: memoryStore };}); REFERENCE TEST src/test/session-helpers.ts: in-memory session store and signInAs/signOut helpers open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { SESSION_COOKIE } from "@/lib/auth/session-config";import { newSessionId, type SessionStore, type StoredSession } from "@/lib/auth/session";import { jar } from "./cookie-jar";
const records = new Map<string, StoredSession>();export const memoryStore: SessionStore = { get: async (id) => records.get(id), set: async (id, s) => void records.set(id, s), delete: async (id) => void records.delete(id),};
export async function signInAs(roles: string[], createdAtMs = Date.now()) { const id = newSessionId(); await memoryStore.set(id, { createdAt: createdAtMs, user: { sub: "user-1", issuer: "https://idp.test", roles, name: "Test User" }, }); jar.set(SESSION_COOKIE, id); return id;}
export function signOut() { jar.clear(); records.clear();}Call signOut() in afterEach so one test’s session never leaks into the next.
Prove the session ends where the constant says
Lesson 3 tested isExpired on its own. This test goes one level up and proves that the request path (requireSession()) enforces it and cleans up. Fake timers move the clock without waiting.
REFERENCE TEST src/lib/auth/session-expiry.test.ts: request-path session expiry and cleanup tests open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { SESSION_MAX_SECONDS } from "@/lib/auth/session-config";import { requireSession } from "@/lib/auth/session";import { memoryStore, signInAs, signOut } from "@/test/session-helpers";
describe("session lifetime at the request path", () => { const t0 = new Date("2026-11-04T12:00:00Z").getTime();
beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(t0); }); afterEach(() => { vi.useRealTimers(); signOut(); });
it("still answers one second before SESSION_MAX_SECONDS", async () => { await signInAs(["Intake.Viewer"], t0); vi.setSystemTime(t0 + (SESSION_MAX_SECONDS - 1) * 1000); await expect(requireSession(memoryStore)).resolves.toMatchObject({ roles: ["Intake.Viewer"] }); });
it("refuses at SESSION_MAX_SECONDS and deletes the record", async () => { const id = await signInAs(["Intake.Viewer"], t0); vi.setSystemTime(t0 + SESSION_MAX_SECONDS * 1000); await expect(requireSession(memoryStore)).rejects.toThrow("Session expired"); expect(await memoryStore.get(id)).toBeUndefined(); });
it("refuses a request with no cookie", async () => { await expect(requireSession(memoryStore)).rejects.toThrow("Authentication required"); });});The tests import the constant, so your ISSO (the security officer who signs off on your system’s controls) can change the number without anyone editing a test.
Prove the guard denies by default
Do not mock withPermission(). Seed a session with a role and call the real guard. A table keeps the matrix readable, and the cases a table of allowed pairs cannot show go beside it.
REFERENCE TEST src/lib/auth/with-permission.test.ts: role-by-action matrix and default-deny tests open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { afterEach, describe, expect, it, vi } from "vitest";import { NextRequest, NextResponse } from "next/server";import { withPermission } from "@/lib/auth/with-permission";import { signInAs, signOut } from "@/test/session-helpers";
const request = () => new NextRequest("http://localhost/api/vehicle-fleet");afterEach(signOut);
describe("withPermission: role by action", () => { // raw provider name, action, expected status. Edit this table when Lesson 5's matrix changes. const cases = [ ["Intake.Viewer", "read", 200], ["Intake.Viewer", "create", 403], ["Intake.Viewer", "delete", 403], ["Intake.Operator", "read", 200], ["Intake.Operator", "create", 200], ["Intake.Operator", "delete", 403], ["Intake.Admin", "delete", 200], ] as const;
it.each(cases)("%s may %s: %i", async (name, action, expected) => { await signInAs([name]); const handler = vi.fn(async () => NextResponse.json({ data: {} })); const res = await withPermission("vehicle-fleet", action, handler)(request(), undefined); expect(res.status).toBe(expected); expect(handler).toHaveBeenCalledTimes(expected === 200 ? 1 : 0); });});
describe("withPermission: what a table of allowed pairs cannot show", () => { it("denies a role name that is not in the closed set", async () => { await signInAs(["contractor-temp"]); const handler = vi.fn(async () => NextResponse.json({})); const res = await withPermission("vehicle-fleet", "read", handler)(request(), undefined); expect(res.status).toBe(403); expect(handler).not.toHaveBeenCalled(); });
it("denies a resource nobody registered", async () => { await signInAs(["Intake.Admin"]); const handler = vi.fn(async () => NextResponse.json({})); const res = await withPermission("no-such-feature", "read", handler)(request(), undefined); expect(res.status).toBe(403); });
it("answers 401, not 403, when there is no session", async () => { const handler = vi.fn(async () => NextResponse.json({})); const res = await withPermission("vehicle-fleet", "read", handler)(request(), undefined); expect(res.status).toBe(401); expect((await res.json()).error.code).toBe("UNAUTHENTICATED"); expect(handler).not.toHaveBeenCalled(); });});The second argument to the guard is the route context (ctx), which Lesson 5’s withPermission() passes through untouched; these tests have no route params, so they pass undefined. The last case asserts a response, not a throw: requireSession() throws a SafeError with status 401, and withPermission() hands it to fail() from Lesson 7, so the caller gets a 401 response with the error envelope { error: { code, message } }.
Test a route handler end to end, minus the database
Seed a role, mock the data module, and call the exported handler as Next.js would. Three things are worth asserting: the response shape, the validation failure, and that an induced database failure leaks nothing.
REFERENCE TEST src/app/api/vehicle-fleet/route.test.ts: route handler tests with mocked database pool open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { afterEach, describe, expect, it, vi } from "vitest";import { NextRequest } from "next/server";import { GET, POST } from "./route";import { signInAs, signOut } from "@/test/session-helpers";
// Lesson 7's route talks to SQL through withPool() from Lesson 8: mock the pool, not a data module.const { query, sqlRequest } = vi.hoisted(() => { const query = vi.fn(); const sqlRequest = { input: vi.fn(), query }; sqlRequest.input.mockReturnValue(sqlRequest); return { query, sqlRequest };});vi.mock("@/lib/db/pool", () => ({ withPool: async (fn: (pool: unknown) => unknown) => fn({ request: () => sqlRequest }) }));
afterEach(() => { signOut(); query.mockReset(); });
const post = (body: unknown) => new NextRequest("http://localhost/api/vehicle-fleet", { method: "POST", body: JSON.stringify(body), headers: { "content-type": "application/json" }, });
describe("GET /api/vehicle-fleet", () => { it("returns the list envelope with paging metadata", async () => { await signInAs(["Intake.Viewer"]); query .mockResolvedValueOnce({ recordset: [{ id: 1 }] }) // the page of rows .mockResolvedValueOnce({ recordset: [{ n: 1 }] }); // the COUNT const res = await GET(new NextRequest("http://localhost/api/vehicle-fleet?page=1"), undefined); const body = await res.json(); expect(res.status).toBe(200); expect(body.data).toHaveLength(1); expect(body.meta).toMatchObject({ page: 1, total: 1 }); });});
describe("POST /api/vehicle-fleet", () => { it("rejects an invalid body with 422 before it reaches the database", async () => { await signInAs(["Intake.Operator"]); const res = await POST(post({ vehicle_id: "" }), undefined); expect(res.status).toBe(422); expect((await res.json()).error.code).toBe("VALIDATION_ERROR"); expect(query).not.toHaveBeenCalled(); });
it("leaks no stack frame or SQL when the database fails", async () => { await signInAs(["Intake.Operator"]); query.mockRejectedValue( new Error("Violation of UNIQUE KEY constraint 'UQ_vehicle_fleet_vehicle_id' at mssql/lib/pool.js:42"), ); const res = await POST(post({ vehicle_id: "FL-1001", make: "Ford", model: "F-150", year: 2024 }), undefined); const text = await res.text(); expect(res.status).toBe(500); expect(text).not.toMatch(/UNIQUE KEY|mssql|pool\.js|\bat \w/); });});The last test is the contract test for “errors are a contract” in Lesson 7: an induced failure on a route leaks no stack frame and no SQL.
Unit test the helpers
Helpers are small, pure and used by every route, so a test here is cheap and pays on every list view.
REFERENCE TEST src/lib/response.test.ts: unit tests for clampPageSize() open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { describe, expect, it } from "vitest";import { clampPageSize, DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE } from "@/lib/response";
describe("clampPageSize", () => { it("never exceeds the platform cap", () => { expect(clampPageSize(String(MAX_PAGE_SIZE * 2))).toBe(MAX_PAGE_SIZE); }); it("falls back to the default for a negative, zero or non-numeric size", () => { expect(clampPageSize("-3")).toBe(DEFAULT_PAGE_SIZE); expect(clampPageSize("0")).toBe(DEFAULT_PAGE_SIZE); expect(clampPageSize("abc")).toBe(DEFAULT_PAGE_SIZE); expect(clampPageSize(null)).toBe(DEFAULT_PAGE_SIZE); }); it("passes a size inside the cap through unchanged", () => { expect(clampPageSize("25")).toBe(25); });}); REFERENCE TEST src/types/vehicle-fleet.test.ts: Zod schema validation and unknown-field stripping tests open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { expect, it } from "vitest";import { VehicleFleetCreateSchema } from "./vehicle-fleet";
it("reports which field failed", () => { const result = VehicleFleetCreateSchema.safeParse({ make: "Ford" }); expect(result.success).toBe(false); expect(result.error?.issues.map((i) => i.path.join("."))).toContain("vehicle_id");});
it("drops fields the schema does not name", () => { const result = VehicleFleetCreateSchema.safeParse({ vehicle_id: "FL-1001", make: "Ford", model: "F-150", year: 2024, injected: "x", }); expect(result.success && "injected" in result.data).toBe(false);});Import MAX_PAGE_SIZE instead of writing the number in the test, for the same reason the expiry tests import the session constant.
Run it and read the coverage
- Typed in the terminal:
npx vitest run --coverage - The tool replies: ✓ |server| src/lib/auth/session-expiry.test.ts (3 tests) ✓ |server| src/lib/auth/with-permission.test.ts (10 tests) ✓ |server| src/app/api/vehicle-fleet/route.test.ts (3 tests) ✓ |server| src/lib/response.test.ts (3 tests) ✓ |server| src/types/vehicle-fleet.test.ts (2 tests) ✓ |server| src/lib/ui/announce.test.ts (1 test) Test Files 6 passed (6) Tests 22 passed (22) % Coverage report from v8 File | % Stmts | % Branch | % Funcs | % Lines All files | ... | ... | ... | ... The figures above are illustrative. Read your own report.
- You type in the session: Which branch in with-permission.ts is not covered?
- The tool replies: The report lists with-permission.ts with an uncovered branch at the 'resource not registered' path in checkAccess. The test 'denies a resource nobody registered' reaches it through withPermission, but the report is per-file for the file under src/lib/auth. If the branch is still marked, check that the test imports the same module path the route uses ('@/lib/auth/with-permission') and not a relative copy.
Illustrative session; exact output varies by tool and agency configuration.
A coverage number tells you which lines no test reached. It does not tell you the tests would fail if the line were wrong, which is why the next section matters more.
These tests gate your own work, so they are not yours to edit
The failure above had a right fix and a tempting one. The right one was to correct what the test was fed. The tempting one, for a person in a hurry or an agent that wants a green run, is to change the expected 403 to 200. Once an agent works in this repository, the session-expiry test and the permission matrix are the referee: they decide whether its change is acceptable, so they cannot sit where the same agent can rewrite them.
The pattern, named in Lesson 25 as the referee: the agent proposes, a protected test decides. Three parts, none of them a prompt instruction (which is a request, not a control):
- Owners on the test paths. A
CODEOWNERSfile assigns the tests, the Vitest config andCODEOWNERSitself to a named team, and the code host’s branch protection requires that team’s review before merge (GitHub: About code owners; Azure DevOps uses required-reviewer branch policies with a path filter instead, per its branch policies page). - A check that reads the diff. A pipeline step, or a hook your AI CLI runs before it writes, fails when a change touches a protected path. Lesson 25 builds the checker: every referee path must have an owner, and the protection list cannot shrink.
- A separate account. The check can only tell the agent from you if the agent commits under its own bot or service account. An agent run from your CLI commits as you, so the review requirement, not the account check, is what holds. A
CODEOWNERSfile excerpt covering the test paths looks like this:
# .github/CODEOWNERS (the test paths from this lesson)/src/**/*.test.ts @your-org/test-owners/src/test/ @your-org/test-owners/tests/contract/ @your-org/test-owners/vitest.config.ts @your-org/test-owners/.github/CODEOWNERS @your-org/test-ownersThe same list grows as the lessons do: Lesson 13’s e2e specs and Lesson 15’s conformance checks belong on it too.
Prove it
A test you have never seen fail is a guess. Plant each fault, run the suite, and confirm the named test turns red.
| Plant this fault | This test must fail |
|---|---|
In isExpired, change >= to > | refuses at SESSION_MAX_SECONDS and deletes the record |
In checkAccess, return true when the role is not found | denies a role that is not in the closed set |
In the POST error handler, return err.message in the body | leaks no stack frame or SQL when the database fails |
Delete the Math.min that applies the page cap | never exceeds the platform cap |
npx vitest run --project serverWhat this suite does not prove: that your identity provider sends the role names your map expects, and that your database accepts the queries the mocks stand in for. The platform lessons (34 to 36) are where a real provider and database come in.
A route handler test mocks withPermission() to always call the handler, so the test can focus on the response body. What has the test lost?
Your ISSO changes the session lifetime constant. Which test design keeps the suite correct without editing any test?
Key takeaway
Run server code in Node and keep jsdom for the files that need a DOM. Mock only what sits beneath your code (the cookie jar, the session store, the data module), call the real guard, and prove the two things reviewers ask about: the session ends at the constant, and a role you did not list is denied. The planted-fault table is the check that the tests can fail.
- LEADERSHIP DECISION
- Whether a failing server test blocks the merge, and who may change the planted-fault table.
- PRACTITIONER ACTION
- Run the planted-fault table and confirm each fault turns a named test red.
- SUCCESS MEASURE
- Assessor-hours: the session-expiry and denied-role evidence is one test run, not a walkthrough.
Legend: LEADERSHIP DECISION = what a leader decides · PRACTITIONER ACTION = what the engineer does next · SUCCESS MEASURE = how you know, in calendar time, assessor-hours or cost, contract or revenue risk, or audit finding avoided