Automated tests and project structure

Write tests with Node's built-in test runner, and organise a growing codebase.

Module 7: Ship it · Lesson 23 of 26 · 16 min read · Free

Testing by hand gets slow and you forget cases. Automated tests check everything in seconds, every time you change something — so you can improve code without fear.

Node's built-in test runner

No packages needed. From 04-students-api/students.test.js:

import { test, before, after } from "node:test";
import assert from "node:assert/strict";
import { createApp } from "./app.js";

let server, base;
before(async () => {
  server = await new Promise((ok) => { const s = createApp().listen(0, () => ok(s)); });  // port 0 = any free port
  base = `http://127.0.0.1:${server.address().port}/api/students`;
});
after(() => server.close());

test("rejects a score above 100", async () => {
  const res = await fetch(base, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ name: "Test", className: "SS1", score: 101 }),
  });
  assert.equal(res.status, 400);
});

Run npm test in the course files. Each test starts the real app and sends real HTTP requests — the same approach as your project checker:

The project checker's output

Why createApp()?

Notice that app.js exports a function that builds the app, and server.js is the only file that calls listen(3000). Tests can then create a fresh app — with a fresh in-memory database (":memory:") — for every run. Keep this pattern in your projects.

What to test

  • Every endpoint's happy path.
  • Every validation rule and error (400/401/403/404/409).
  • Business rules: delivery fees at the boundaries (₦19,999 vs ₦20,000), rounding, discounts.
  • Bugs you've fixed — add a test so they never come back.

Structure as you grow

When one file gets too long, split by feature:

src/
  app.js            createApp(): middleware + routes
  db.js             connection and schema
  routes/
    menu.js         express.Router() for /api/menu
    orders.js
    auth.js
  lib/
    validate.js
    passwords.js
test/

express.Router() lets each file define its own routes, which app.js mounts: app.use("/api/orders", ordersRouter).

Check yourself

Answer in your head first, then open each question to see the answer and why.

  1. Why export createApp() instead of starting the server in app.js?

    • A Tests can build fresh apps with their own databases without starting the real server
    • B It makes the server faster
    • C Express requires it
    • D To hide the code
    Show the answer

    A) Tests can build fresh apps with their own databases without starting the real server — Separating construction from listen() makes testing easy.

  2. What does listen(0) do?

    • A Picks any free port
    • B Listens on port zero only
    • C Stops the server
    • D Disables networking
    Show the answer

    A) Picks any free port — Useful in tests to avoid port clashes.

  3. Which is the best test to add after fixing a bug?

    • A A test that reproduces the bug, so it never returns
    • B None — it's fixed
    • C A test for an unrelated feature
    • D A manual note
    Show the answer

    A) A test that reproduces the bug, so it never returns — Regression tests prevent repeats.

More free lessons: What the back end does · Install Node.js and use the terminal · Asynchronous code: promises and async/await · HTTP: requests, responses and status codes · Designing a REST API · Designing tables and relationships · Storing passwords safely