A route handler is an adapter: it turns a request into a call to a domain
rule, and the rule's result into a response. The rule can be perfect while the
adapter still sends 200 for an error, forgets to catch malformed JSON, or sends
the wrong body. Those mistakes live in the adapter, so the adapter needs tests
of its own.
You don't need a server for them. In the App Router a handler is just an
exported async function that takes a Request and returns a Response, and
both are standard objects you can build in a test.
Read, predict, run
lib/contract.js maps a domain code to a status:
JavaScript
export function run(code) { return ( new Map(Object.entries({ invalid: 400, missing: 404, conflict: 409 })).get( code, ) ?? 500 );}
app/api/example/route.js reads a code from the JSON body, calls run, and
sends that status. tests/route.test.js calls the handler directly:
JavaScript
import { test, assert } from "@/lib/test.js";import { POST } from "@/app/api/example/route.js";// Call the handler like Next.js does: with a Request. No server needed.const post = (body) => POST(new Request("http://localhost/api/example", { method: "POST", body }));test("a known domain code becomes its HTTP status", async () => { const response = await post('"missing"'); assert.equal(response.status, 404);});test("an unknown code fails closed as 500", async () => { const response = await post('"surprise"'); assert.equal(response.status, 500);});test("malformed JSON is a 400 with a code, not a crash", async () => { const response = await post("{"); assert.equal(response.status, 400); assert.deepEqual(await response.json(), { code: "invalid_json" });});
Predict: if you deleted the try/catch around request.json() in the
handler, which test would fail, and would the pure run cases in the table
notice? Try it, then put it back.
Test the HTTP Adapter SeparatelyNext.js · 10 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<strong>Study Library · Practice lab</strong>
</header>
{children}
</body>
</html>
);
}
import ApiProbe from "./ApiProbe.jsx";
import Cases from "./Cases.jsx";
import Tests from "./Tests.jsx";
export default function Page() {
return (
<main>
<h1>Test the HTTP Adapter Separately</h1>
<ApiProbe />
<Tests />
<Cases />
</main>
);
}
"use client";
import { useState } from "react";
export default function ApiProbe() {
const [result, setResult] = useState("");
async function load() {
try {
const response = await fetch("/api/example");
setResult(response.status + " " + JSON.stringify(await response.json()));
} catch {
setResult("Request failed");
}
}
return (
<section>
<button onClick={load}>Ask the API</button>
<p role="status">{result}</p>
</section>
);
}
import { run, examples } from "@/lib/contract.js";
const text = (value) => JSON.stringify(value) ?? "undefined";
export default async function Cases() {
const results = await Promise.all(
examples.map(async ([input, expected]) => {
// Record the input before running, to show whether run changed it.
const before = text(input);
const actual = await run(input);
return {
input: before,
expected,
actual,
kept: text(input) === before,
pass: text(actual) === text(expected),
};
}),
);
return (
<section>
<h2>Executable cases</h2>
<p>
Checks: {results.filter((row) => row.pass).length}/{results.length}{" "}
passed
</p>
<table>
<thead>
<tr>
<th>Input</th>
<th>Expected</th>
<th>Actual</th>
<th>Input kept</th>
</tr>
</thead>
<tbody>
{results.map((row, i) => (
<tr key={i}>
<td>
<code>{row.input}</code>
</td>
<td>
<code>{text(row.expected)}</code>
</td>
<td className={row.pass ? "pass" : "fail"}>
<code>{text(row.actual)}</code>
</td>
<td className={row.kept ? "pass" : "fail"}>
{row.kept ? "yes" : "no: run changed it"}
</td>
</tr>
))}
</tbody>
</table>
</section>
);
}
import "@/tests/route.test.js";
import { runTests } from "@/lib/test.js";
export default async function Tests() {
const results = await runTests();
return (
<section>
<h2>Tests in tests/route.test.js</h2>
<p>
Tests: {results.filter((r) => r.pass).length}/{results.length} passed
</p>
<ul>
{results.map((r) => (
<li key={r.name} className={r.pass ? "pass" : "fail"}>
{r.pass ? "✓" : "✗"} {r.name}
{r.message && `: ${r.message}`}
</li>
))}
</ul>
</section>
);
}
body {
font: 16px/1.5 system-ui;
margin: 0;
color: #182b3c;
background: #f4f8fc;
}
header,
main {
max-width: 900px;
margin: auto;
padding: 20px;
}
header {
border-bottom: 1px solid #cbd5e1;
}
a {
color: #075985;
}
button,
input,
textarea,
select {
font: inherit;
padding: 8px;
margin: 4px;
}
button {
cursor: pointer;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
padding: 10px;
border: 1px solid #cbd5e1;
text-align: left;
vertical-align: top;
}
pre,
code {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.pass {
color: #166534;
}
.fail,
[role="alert"] {
color: #a01818;
}
section {
margin: 16px 0;
padding: 12px;
background: white;
border-radius: 8px;
}
nav {
display: flex;
gap: 16px;
}
import { run, examples } from "@/lib/contract.js";
// run returns the HTTP status for a domain code; it is the response's status
// and its body says which code produced it.
function respond(code) {
const status = run(code);
return Response.json({ code, status }, { status });
}
// GET answers for the first example, so "Ask the API" shows a real response.
export async function GET() {
return respond(examples[0][0]);
}
export async function POST(request) {
let input;
try {
input = await request.json();
} catch {
return Response.json({ code: "invalid_json" }, { status: 400 });
}
return respond(input);
}
export function run(code) {
return (
new Map(Object.entries({ invalid: 400, missing: 404, conflict: 409 })).get(
code,
) ?? 500
);
}
export const examples = [
["invalid", 400],
["missing", 404],
["unexpected", 500],
];
// A tiny stand-in for node:test and node:assert/strict, so tests can run in
// the browser. On your computer, write instead:
// import { test } from "node:test";
// import assert from "node:assert/strict";
const tests = [];
export function test(name, fn) {
tests.push({ name, fn });
}
const show = (value) => JSON.stringify(value) ?? String(value);
export const assert = {
equal(actual, expected) {
if (!Object.is(actual, expected))
throw new Error(`expected ${show(expected)}, got ${show(actual)}`);
},
deepEqual(actual, expected) {
if (show(actual) !== show(expected))
throw new Error(`expected ${show(expected)}, got ${show(actual)}`);
},
};
export async function runTests() {
const results = [];
for (const { name, fn } of tests) {
try {
await fn();
results.push({ name, pass: true, message: "" });
} catch (error) {
results.push({ name, pass: false, message: error.message });
}
}
return results;
}
import { test, assert } from "@/lib/test.js";
import { POST } from "@/app/api/example/route.js";
// Call the handler like Next.js does: with a Request. No server needed.
const post = (body) =>
POST(new Request("http://localhost/api/example", { method: "POST", body }));
test("a known domain code becomes its HTTP status", async () => {
const response = await post('"missing"');
assert.equal(response.status, 404);
});
test("an unknown code fails closed as 500", async () => {
const response = await post('"surprise"');
assert.equal(response.status, 500);
});
test("malformed JSON is a 400 with a code, not a crash", async () => {
const response = await post("{");
assert.equal(response.status, 400);
assert.deepEqual(await response.json(), { code: "invalid_json" });
});
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Check your prediction
Only malformed JSON is a 400 with a code, not a crash fails: request.json()
throws on {, and the test reports that error instead of a 400. The case table
still says 3/3 passed, because run never sees the body. That's the gap
between the two kinds of test: the table checks the rule, the handler test
checks the translation.
The failure to avoid
Mocking both the adapter and the rule proves only that the mocks agree. Call the
real handler with a real Request, and replace only what you can't run in a
test, such as the database, by passing in a stand-in. A browser test is still
needed once, for the wiring: that the route exists at that path and the page
really calls it.
Exercise
A created status, tested at the edge
Treat a domain code of created as 201; unknown codes must still be 500.
Then add a handler test, a created code is a 201, that sends "created"
through POST and checks the status.
Add the rule's case to examples in lib/contract.js too:
Input "created" must return 201.
Your working spaceNext.js · 10 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<strong>Study Library · Practice lab</strong>
</header>
{children}
</body>
</html>
);
}
import ApiProbe from "./ApiProbe.jsx";
import Cases from "./Cases.jsx";
import Tests from "./Tests.jsx";
export default function Page() {
return (
<main>
<h1>Test the HTTP Adapter Separately</h1>
<ApiProbe />
<Tests />
<Cases />
</main>
);
}
"use client";
import { useState } from "react";
export default function ApiProbe() {
const [result, setResult] = useState("");
async function load() {
try {
const response = await fetch("/api/example");
setResult(response.status + " " + JSON.stringify(await response.json()));
} catch {
setResult("Request failed");
}
}
return (
<section>
<button onClick={load}>Ask the API</button>
<p role="status">{result}</p>
</section>
);
}
import { run, examples } from "@/lib/contract.js";
const text = (value) => JSON.stringify(value) ?? "undefined";
export default async function Cases() {
const results = await Promise.all(
examples.map(async ([input, expected]) => {
// Record the input before running, to show whether run changed it.
const before = text(input);
const actual = await run(input);
return {
input: before,
expected,
actual,
kept: text(input) === before,
pass: text(actual) === text(expected),
};
}),
);
return (
<section>
<h2>Executable cases</h2>
<p>
Checks: {results.filter((row) => row.pass).length}/{results.length}{" "}
passed
</p>
<table>
<thead>
<tr>
<th>Input</th>
<th>Expected</th>
<th>Actual</th>
<th>Input kept</th>
</tr>
</thead>
<tbody>
{results.map((row, i) => (
<tr key={i}>
<td>
<code>{row.input}</code>
</td>
<td>
<code>{text(row.expected)}</code>
</td>
<td className={row.pass ? "pass" : "fail"}>
<code>{text(row.actual)}</code>
</td>
<td className={row.kept ? "pass" : "fail"}>
{row.kept ? "yes" : "no: run changed it"}
</td>
</tr>
))}
</tbody>
</table>
</section>
);
}
import "@/tests/route.test.js";
import { runTests } from "@/lib/test.js";
export default async function Tests() {
const results = await runTests();
return (
<section>
<h2>Tests in tests/route.test.js</h2>
<p>
Tests: {results.filter((r) => r.pass).length}/{results.length} passed
</p>
<ul>
{results.map((r) => (
<li key={r.name} className={r.pass ? "pass" : "fail"}>
{r.pass ? "✓" : "✗"} {r.name}
{r.message && `: ${r.message}`}
</li>
))}
</ul>
</section>
);
}
body {
font: 16px/1.5 system-ui;
margin: 0;
color: #182b3c;
background: #f4f8fc;
}
header,
main {
max-width: 900px;
margin: auto;
padding: 20px;
}
header {
border-bottom: 1px solid #cbd5e1;
}
a {
color: #075985;
}
button,
input,
textarea,
select {
font: inherit;
padding: 8px;
margin: 4px;
}
button {
cursor: pointer;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
padding: 10px;
border: 1px solid #cbd5e1;
text-align: left;
vertical-align: top;
}
pre,
code {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.pass {
color: #166534;
}
.fail,
[role="alert"] {
color: #a01818;
}
section {
margin: 16px 0;
padding: 12px;
background: white;
border-radius: 8px;
}
nav {
display: flex;
gap: 16px;
}
import { run, examples } from "@/lib/contract.js";
// run returns the HTTP status for a domain code; it is the response's status
// and its body says which code produced it.
function respond(code) {
const status = run(code);
return Response.json({ code, status }, { status });
}
// GET answers for the first example, so "Ask the API" shows a real response.
export async function GET() {
return respond(examples[0][0]);
}
export async function POST(request) {
let input;
try {
input = await request.json();
} catch {
return Response.json({ code: "invalid_json" }, { status: 400 });
}
return respond(input);
}
export function run(code) {
return (
new Map(Object.entries({ invalid: 400, missing: 404, conflict: 409 })).get(
code,
) ?? 500
);
}
export const examples = [
["invalid", 400],
["missing", 404],
["unexpected", 500],
];
// A tiny stand-in for node:test and node:assert/strict, so tests can run in
// the browser. On your computer, write instead:
// import { test } from "node:test";
// import assert from "node:assert/strict";
const tests = [];
export function test(name, fn) {
tests.push({ name, fn });
}
const show = (value) => JSON.stringify(value) ?? String(value);
export const assert = {
equal(actual, expected) {
if (!Object.is(actual, expected))
throw new Error(`expected ${show(expected)}, got ${show(actual)}`);
},
deepEqual(actual, expected) {
if (show(actual) !== show(expected))
throw new Error(`expected ${show(expected)}, got ${show(actual)}`);
},
};
export async function runTests() {
const results = [];
for (const { name, fn } of tests) {
try {
await fn();
results.push({ name, pass: true, message: "" });
} catch (error) {
results.push({ name, pass: false, message: error.message });
}
}
return results;
}
import { test, assert } from "@/lib/test.js";
import { POST } from "@/app/api/example/route.js";
// Call the handler like Next.js does: with a Request. No server needed.
const post = (body) =>
POST(new Request("http://localhost/api/example", { method: "POST", body }));
test("a known domain code becomes its HTTP status", async () => {
const response = await post('"missing"');
assert.equal(response.status, 404);
});
test("an unknown code fails closed as 500", async () => {
const response = await post('"surprise"');
assert.equal(response.status, 500);
});
test("malformed JSON is a 400 with a code, not a crash", async () => {
const response = await post("{");
assert.equal(response.status, 400);
assert.deepEqual(await response.json(), { code: "invalid_json" });
});
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea
The status table belongs to the rule, so created is one more entry in the
map, not a change to the ?? 500 fallback, which is what keeps unknown codes
safe. The handler doesn't change at all; the new test proves that.
Hint 2: a first step
Write the handler test first, copying a known domain code becomes its HTTP
status, and run: it fails with expected 201, got 500. Then add the entry
to the map.
test("a created code is a 201", async () => { const response = await post('"created"'); assert.equal(response.status, 201);});
The handler passes whatever run returns as the status, so one map entry
changes both the table and the real response, and the handler test confirms
the response really carries 201. A Map built from Object.entries is used
instead of a plain object lookup so that codes like "constructor" can't find
inherited properties and still fall through to 500.
Explain it without the code
Your handler test passes but the browser shows a 404 page when the form posts.
Name two things the handler test can't see that could cause it.
Going further
In the downloadable project, tests/http.test.mjs uses the same technique
against the real handlers, with an in-memory SQLite database substituted for
the real one. Read the
route handler reference
for the Request and Response objects.
Completion is saved in this browser only. It does not measure mastery.