Your suite for Niamh’s schedule API now gives every test its own server and its own copy of shows.json, so each test passes alone, in any order, or with the rest. But every one of those tests sends a good request. The clients that call Niamh’s API won’t always do that. A volunteer editing the schedule can mistype an id, a script can send a five-hour show, and a bug in a client can send half a JSON body.
You know a 404 from the client’s side. In this lesson, you’ll write tests that check the API sends one, with the right status and the error shape { error: { code, message, details } }, as carefully as you test the answers that succeed. Start with what POST /shows sends back, the successful response the suite checks least.
Check What a Create Request Returns
The create test from the last lesson only checks the status. A handler that answered 201 with an empty body, or with the wrong show, would still pass the test. So the test should also look at the body and the Location header, which tells the client where the new show lives.
The body is harder to pin down than the one in your first test because the server gives each new show an id from crypto.randomUUID(), and that id is different on every run. You can see the problem by trying the check you already know. Replace the create test in shows.test.ts with this version:
shows.test.ts
test("POST /shows creates a show", async () => {
const res = await postShow();
assert.strictEqual(res.status, 201);
const show = await res.json();
assert.deepStrictEqual(show, saturdayFolk);
});
Run npm test, and the create test fails with a diff that has one line marked +:
✖ POST /shows creates a show (21.99034ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
{
day: 'Saturday',
host: 'Freya Lindqvist',
+ id: '4fd95d81-e6b8-4f35-87b5-3c1e9faed505',
minutes: 90,
start: '14:00',
title: 'Saturday Folk'
}
...
Every field you sent came back, and the server added an id. The assert.deepStrictEqual() function requires the two values to match completely, so the extra field makes the assertion fail. You can’t write the id into the expected value either, because the next run gets a new one.
The assert.partialDeepStrictEqual() function solves this. It checks that every property of the expected value is in the actual one, with the same value, and ignores properties the expected value doesn’t mention. Replace the assert.deepStrictEqual() call with these checks:
shows.test.ts
assert.partialDeepStrictEqual(show, saturdayFolk);
assert.strictEqual(typeof show.id, "string");
assert.strictEqual(
res.headers.get("location"),
`/shows/${show.id}`,
);
The first line checks the five fields you sent. The second checks that the id is a string, and the third that Location points at it. Run npm test again, and the create test passes.
A 201 with the right body still doesn’t prove the show was saved. A handler could build the show, send it back, and never write it. The proof is to read the show back through the API, the way any client would. Add this test below the others:
shows.test.ts
test("GET /shows/:id finds a show POST created", async () => {
const created = await postShow();
assert.strictEqual(created.status, 201);
const location = created.headers.get("location");
const res = await fetch(`${base}${location}`);
assert.strictEqual(res.status, 200);
assert.deepStrictEqual(await res.json(), await created.json());
});
The test follows Location to the new show and expects exactly the body the create request returned, generated id included. Here assert.deepStrictEqual() is the right check because both sides come from the server.
Test the Answers That Say No
An error answer is part of the API too. A client that edits the schedule has to show “No such show” or “That’s too long” based on that answer, so a wrong status or a missing code breaks that client as surely as an incorrect success response. Start with an id that doesn’t exist. Add a test for GET /shows/99:
shows.test.ts
test("GET /shows/:id answers 404 for an unknown id", async () => {
const res = await fetch(`${base}/shows/99`);
assert.strictEqual(res.status, 404);
assert.strictEqual(
res.headers.get("content-type"),
"application/json; charset=utf-8",
);
assert.deepStrictEqual(await res.json(), {
error: {
code: "show_not_found",
message: "No show has the id 99.",
details: null,
},
});
});
This test checks the whole error, with details: null included, because nothing in it changes between runs.
Invalid input is different. The schema in shows.ts allows shows of 15 to 240 minutes, and for anything else the API answers 422 with Zod’s report in details. Before you test that report, look at one. If you stopped the dev server, start it again with npm start in your first terminal. From your second terminal, send a five-hour show to the dev server. Here’s the output, shortened:
$ curl -i -X POST http://localhost:3000/shows \
-H "Content-Type: application/json" \
-d '{"title":"Saturday Folk","host":"Freya Lindqvist",
"day":"Saturday","start":"14:00","minutes":300}'
HTTP/1.1 422 Unprocessable Entity
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
...
{"error":{"code":"invalid_show","message":"The show has invalid fields.",...
..."properties":{"minutes":{"errors":["Too big: expected number to be <=240"]...
The details object is the report from Zod’s z.treeifyError(). Its properties object has one key for each field that failed, and each corresponding value holds that field’s messages. In this answer, the only key is minutes.
The API decides the code and the message, so a test can pin them down. Zod owns the wording of the messages and could change it in an update, so the test checks only which fields properties names. This test and the next one send their own bodies, so first add a helper below postShow():
shows.test.ts
function postBody(body: string) {
return fetch(`${base}/shows`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body,
});
}
Then add the test for a five-hour show:
shows.test.ts
test("POST /shows rejects a five-hour show", async () => {
const before = await fetch(`${base}/shows`);
const shows = await before.json();
const res = await postBody(
JSON.stringify({ ...saturdayFolk, minutes: 300 }),
);
assert.strictEqual(res.status, 422);
const { error } = await res.json();
assert.partialDeepStrictEqual(error, {
code: "invalid_show",
message: "The show has invalid fields.",
});
assert.deepStrictEqual(
Object.keys(error.details.properties),
["minutes"],
);
const after = await fetch(`${base}/shows`);
assert.deepStrictEqual(await after.json(), shows);
});
The assert.partialDeepStrictEqual() call checks the two fields the API writes itself, and Object.keys() turns error.details.properties into the list of fields that failed, so the check passes only when Zod’s report blames minutes alone.
The first and last fetches check that a rejected request doesn’t change the data. A handler that saved the show before validating it, or overwrote another show, would still answer 422, and only comparing the whole list would catch that.
Run npm test, and all six tests pass. A passing test is only worth something if it can fail, so break the API on purpose. In app.ts, change the 422 in the POST /shows handler to 400, and run npm test again:
✖ POST /shows rejects a five-hour show (7.315253ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
400 !== 422
...
The suite catches the wrong status and names the test that saw it. Change the 400 back to 422 before you go on.
Send a Body That Isn’t JSON
The last way in for bad data is a body that isn’t JSON at all, such as the first half of a show’s JSON body. The API’s rule is 400 for a body it can’t read as a JSON object or array, and 422 for one it can read that breaks the rules. Add a test that sends a broken body and expects a 400, a JSON Content-Type, and the whole error:
shows.test.ts
test("POST /shows answers 400 for broken JSON", async () => {
const res = await postBody('{"title": "Saturday Folk",');
assert.strictEqual(res.status, 400);
assert.strictEqual(
res.headers.get("content-type"),
"application/json; charset=utf-8",
);
assert.deepStrictEqual(await res.json(), {
error: {
code: "invalid_json",
message: "The body isn't valid JSON.",
details: null,
},
});
});
Every other route in app.ts answers with sendError(). Before you run npm test, decide: Does this test pass, and if it fails, which line fails?
The status check passes, and the test fails on the next assertion, which checks Content-Type:
✖ POST /shows answers 400 for broken JSON (7.635304ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ 'text/html; charset=utf-8'
- 'application/json; charset=utf-8'
...
The body that came back is an HTML page. You can see it from the terminal. Your dev server is still running in the first terminal, so send it the same broken body from the second. Here’s the output, shortened:
$ curl -i -X POST http://localhost:3000/shows \
-H "Content-Type: application/json" \
-d '{"title": "Saturday Folk",'
HTTP/1.1 400 Bad Request
X-Powered-By: Express
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
...
<!DOCTYPE html>
...
<pre>SyntaxError: Expected double-quoted property name in JSON at position 26...
... at parse (/home/you/riverside-schedule/node_modules/body-parser/...
...
No route handler ever ran. The express.json() middleware couldn’t parse the body and passed the error on, and with no error-handling middleware of its own, Niamh’s app fell back on Express’s default handler. It picked the right status, 400, but sent a page with the stack trace and the server’s file paths. A status-only test would have missed all of it.
The fix belongs in the API, so leave the test as it is. Errors from express.json() carry a status and a type, so add a Zod schema for them above sendError() in app.ts:
app.ts
const BodyError = z.object({ status: z.number(), type: z.string() });
Then add an error-handling middleware function at the end of createApp(), after the five routes and before return app;:
app.ts
app.use(
(error: unknown, req: Request, res: Response, next: NextFunction) => {
if (res.headersSent) {
return next(error);
}
const body = BodyError.safeParse(error);
if (body.success && body.data.type === "entity.parse.failed") {
sendError(res, 400, "invalid_json", "The body isn't valid JSON.");
} else if (body.success && body.data.status < 500) {
sendError(
res,
body.data.status,
"invalid_body",
"The server couldn't read the body.",
);
} else {
console.error(error);
sendError(
res,
500,
"server_error",
"Something went wrong on the server.",
);
}
},
);
Express treats a middleware function with four parameters as an error handler, so all four stay, even the unused req. The first check covers a route that has already started its response. The error shape can’t replace a response that’s under way, so next(error) hands the error to Express’s own handler, which closes the connection.
A body that can’t be parsed produces an error with the type entity.parse.failed and gets 400. Checking error instanceof SyntaxError instead would also catch a SyntaxError the server causes itself, such as readShows() reading a damaged shows.json.
Any other body problem with a status below 500 keeps its own status, such as 413 for a body over the 100 KB limit, and still gets the JSON error shape. Anything else is a server failure, so the handler logs it for Niamh and answers 500 with a message that gives nothing away.
This middleware is the one place that sends errors for bodies the parser refuses and for unhandled errors in a route. A path or method that no route matches, such as GET /hosts, never reaches it and still gets Express’s own HTML 404. Add NextFunction and Request to the type import at the top of app.ts:
app.ts
import type { NextFunction, Request, Response } from "express";
Run npm test, and all seven tests pass:
✔ GET /shows lists the six shows (107.809412ms)
✔ POST /shows creates a show (35.913987ms)
✔ GET /shows lists the new show with the others (19.282709ms)
✔ GET /shows/:id finds a show POST created (14.510757ms)
✔ GET /shows/:id answers 404 for an unknown id (6.151443ms)
✔ POST /shows rejects a five-hour show (17.828639ms)
✔ POST /shows answers 400 for broken JSON (5.805743ms)
ℹ tests 7
ℹ suites 0
ℹ pass 7
ℹ fail 0
...
The dev server is still running the code it started with, so stop it with Ctrl+C and start it again with npm start. Then send the same broken body from the second terminal. Here’s the output, shortened:
$ curl -i -X POST http://localhost:3000/shows \
-H "Content-Type: application/json" \
-d '{"title": "Saturday Folk",'
HTTP/1.1 400 Bad Request
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
...
{"error":{"code":"invalid_json","message":"The body isn't valid JSON.",...
The client gets the error shape without the stack trace or the server’s file paths. Only a bad body triggers that parsing error, so no happy-path test could have found this bug.
If it still isn’t clear why a correct status hid a wrong answer, then click the button below. It opens a conversation with the AI mentor with this question already asked, and you can follow up in your own words:
You may meet libraries such as supertest in other projects. They start the app and send requests through a chain of calls. They do the same job as fetch() with node:test, but you have one more package to install.
Check Your Tests
Answer these with shows.test.ts open:
- Your create test checks the body with
assert.partialDeepStrictEqual(), and the read-back test usesassert.deepStrictEqual(). Why does each test use the check it does? - In the test for a five-hour show, Ravi deletes the lines that fetch and compare the list. Which bug in
POST /showscould the test then miss? - Write a test that sends
PATCH /shows/99with the body{ "minutes": 60 }and checks the status and the whole error.
Question 1: The create test compares the server’s body with saturdayFolk, which has no id, and the id changes on every run. The partial check ignores it, and a separate line checks it’s a string. The read-back test compares two answers from the server, which share the same id, so it can compare everything.
Question 2: A handler could save the show before validating it or change another show. It would still answer 422 with invalid_show, so the status and error checks would pass. Only comparing the lists from before and after the request would reveal the change.
Question 3: The PATCH handler sends the same error as GET for an id that doesn’t exist:
shows.test.ts
test("PATCH /shows/:id answers 404 for an unknown id", async () => {
const res = await fetch(`${base}/shows/99`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ minutes: 60 }),
});
assert.strictEqual(res.status, 404);
assert.deepStrictEqual(await res.json(), {
error: {
code: "show_not_found",
message: "No show has the id 99.",
details: null,
},
});
});
The suite reports eight passes.
Before you move on, test yourself on choosing a check. This button asks the AI mentor to quiz you, one question at a time, and to tell you how each answer went:
Your suite now checks the answers that say yes and the ones that say no. Next comes the course’s first coding exercise. It runs in your browser. You edit the code in an editor and click Run Tests, and automated tests tell you what works and what doesn’t yet. If you’re new to coding exercises on RealJS, then the Contents tab below the editor explains how they work.
In Exercise: Give Every Test Its Own Server, you’ll write the helper the station’s tests rely on to start a fresh copy of Niamh’s API, with its own list of shows, for each test.