Our To-Do API works: sign-up, login and five task endpoints. So far we checked it by hand with curl. That's fine once, but every change can quietly break something you tested last week. In this lesson we write 22 automated tests for the API, from tiny unit tests to full HTTP requests against a real database, then make them run on every push.
Every file below was run before publishing: 22 tests pass, with 100% line coverage.
Why test an API?
- Catch bugs before users do. A test fails the moment you break something, not three days later in a support email.
- Change code without fear. Want to clean up a service? If the tests still pass, you didn't break it.
- Security rules stay true. “Ravi can't see Asha's tasks” is easy to break by accident. A test checks it every single time.
- Interviews and jobs expect it. “How do you test your API?” is a standard backend interview question, and real teams don't merge code without tests.
The three kinds of tests
| Kind | What it checks | Speed | In our API |
|---|---|---|---|
| Unit test | One small piece on its own, no database, no HTTP | Milliseconds | The Zod schemas |
| Integration (API) test | A real HTTP request through routes, middleware, service and database | Tens of milliseconds | Register, login, every task endpoint |
| End-to-end test | The whole product, usually through a real browser | Seconds | Later, with the React app |
For a backend, API tests give the most value: they test what your users actually call. Unit tests are great for tricky rules that don't need a database. We'll write both.
Step 1: Install Supertest
Bun has a test runner built in (bun test), so the only thing we add is Supertest, which sends HTTP requests to our Express app inside a test:
$bun add -d supertest @types/supertest# npm users: npm install -D supertest @types/supertest (and a runner such as Vitest)
Step 2: A separate database for tests
Our tests will create users and tasks, and empty the tables before each test. So they need their own database, never the one you develop with. Create it next to the dev database:
$createdb tasks_app_test
Then add a .env.test file. It only holds local test settings, so it's safe to commit:
PORT=3001
DATABASE_URL="postgresql://postgres@localhost:55432/tasks_app_test?schema=public"
JWT_SECRET="test-secret-at-least-16-chars"bun test sets NODE_ENV=test and loads .env.test automatically, on top of .env. So during tests, DATABASE_URL points at tasks_app_test with no extra code. Add three scripts to package.json:
"test": "bun test",
"test:coverage": "bun test --coverage",
"db:test:migrate": "bun --bun --env-file=.env.test run prisma migrate deploy"Now create the tables in the test database. Run this again whenever you add a migration:
$bun run db:test:migrate
We use migrate deploy, not migrate dev: it applies the migrations you already have and never creates new ones, exactly like on a server.
Step 3: Your first test (a unit test)
Start with the easiest thing to test: the Zod schemas. No database, no HTTP, just “given this input, do I get this output?”. bun test runs every file whose name ends in .test.ts.
import { describe, test, expect } from "bun:test";
import { createTaskSchema, updateTaskSchema } from "../src/modules/tasks/task.schema";
describe("createTaskSchema", () => {
test("accepts a normal title and trims spaces", () => {
const result = createTaskSchema.parse({ title: " Buy milk " });
expect(result).toEqual({ title: "Buy milk" });
});
test("rejects an empty title", () => {
const result = createTaskSchema.safeParse({ title: " " });
expect(result.success).toBe(false);
});
test("rejects a title longer than 200 characters", () => {
const result = createTaskSchema.safeParse({ title: "a".repeat(201) });
expect(result.success).toBe(false);
});
});
describe("updateTaskSchema", () => {
test("allows sending only done", () => {
expect(updateTaskSchema.parse({ done: true })).toEqual({ done: true });
});
test("rejects done as a string", () => {
expect(updateTaskSchema.safeParse({ done: "yes" }).success).toBe(false);
});
});$bun test tests/task.schema.test.ts
bun test v1.4.5
5 pass
0 fail
5 expect() calls
Ran 5 tests across 1 file. [113.00ms]Five tests, all green. Bun keeps the output short when everything passes and prints the details only for tests that fail (you'll see one fail later in this lesson).
Three words do all the work:
| Word | What it does |
|---|---|
| describe("name", fn) | Groups related tests under one heading (optional, but keeps output readable) |
| test("name", fn) | One test. The name should read like a sentence: what should happen |
| expect(value) | Starts a check: .toBe(x) for exact values, .toEqual(obj) for whole objects, .toMatchObject(obj) for "has at least these fields" |
How every test is built: Arrange, Act, Assert
import { test, expect } from "bun:test";
test("creates a task", async () => {
// 1. ARRANGE: get things ready (a logged-in user, maybe some data)
// 2. ACT: do the one thing you're testing
const res = await request(app).post("/api/tasks").set(auth()).send({ title: "Buy milk" });
// 3. ASSERT: check what came back
expect(res.status).toBe(201);
expect(res.body).toMatchObject({ title: "Buy milk", done: false });
});Keep one behaviour per test. When “creates a task” fails, you know exactly what broke. When a test called “tasks work” fails, you have to go digging.
Step 4: Two helpers every API test needs
Every API test needs a clean database, and most need a logged-in user. Write those once:
import request from "supertest";
import { app } from "../src/app";
import { prisma } from "../src/lib/prisma";
// Empty the test database so every test starts from zero.
export async function resetDb() {
// Safety net: never wipe a database unless its name contains _test.
if (!process.env.DATABASE_URL?.includes("_test")) {
throw new Error("Refusing to reset: DATABASE_URL is not a test database");
}
await prisma.task.deleteMany();
await prisma.user.deleteMany();
}
// Sign up a user through the real API and return their login token.
export async function signUp(email = "[email protected]") {
const res = await request(app)
.post("/api/auth/register")
.send({ name: "Asha", email, password: "password123" });
return res.body.token as string;
}resetDb()deletes tasks first, then users (tasks point at users). The guard at the top refuses to wipe anything unless the database name contains_test. We tested that too: pointing it at the dev database stops with “Refusing to reset: DATABASE_URL is not a test database”.signUp()registers through the real API and returns the token, so tests log in exactly like the React app will.
Step 5: Test sign-up and login
import { describe, test, expect, beforeEach, afterAll } from "bun:test";
import request from "supertest";
import { app } from "../src/app";
import { prisma } from "../src/lib/prisma";
import { resetDb, signUp } from "./helpers";
beforeEach(resetDb);
afterAll(() => prisma.$disconnect());
describe("POST /api/auth/register", () => {
test("creates a user and returns a token, never the password", async () => {
const res = await request(app)
.post("/api/auth/register")
.send({ name: "Asha", email: "[email protected]", password: "password123" });
expect(res.status).toBe(201);
expect(res.body.token).toBeString();
expect(res.body.user).toEqual({ id: expect.any(Number), name: "Asha", email: "[email protected]" });
expect(res.body.user.password).toBeUndefined();
});
test("returns 409 when the email is already used", async () => {
await signUp("[email protected]");
const res = await request(app)
.post("/api/auth/register")
.send({ name: "Asha again", email: "[email protected]", password: "password123" });
expect(res.status).toBe(409);
expect(res.body).toEqual({ error: "An account with this email already exists" });
});
test("returns 400 with field details for a short password", async () => {
const res = await request(app)
.post("/api/auth/register")
.send({ name: "Asha", email: "[email protected]", password: "123" });
expect(res.status).toBe(400);
expect(res.body.details).toContainEqual({ field: "password", message: "Password must be at least 8 characters" });
});
});
describe("POST /api/auth/login", () => {
test("logs in with the right password", async () => {
await signUp("[email protected]");
const res = await request(app).post("/api/auth/login").send({ email: "[email protected]", password: "password123" });
expect(res.status).toBe(200);
expect(res.body.token).toBeString();
});
test("returns 401 with the wrong password", async () => {
await signUp("[email protected]");
const res = await request(app).post("/api/auth/login").send({ email: "[email protected]", password: "wrong-password" });
expect(res.status).toBe(401);
expect(res.body).toEqual({ error: "Wrong email or password" });
});
});What to notice:
beforeEach(resetDb)runs before every test, so each one starts from an empty database. Tests never depend on each other or on their order.- The first test sends
[email protected]and expects[email protected]back: it proves the schema's.toLowerCase()really works. toEqualcompares the whole user object. If the password hash ever leaks into the response, the extra field makes the test fail.afterAll(() => prisma.$disconnect())closes the database connection when the file is done.
Step 6: Test the task endpoints
This is the big one: login protection, all five CRUD endpoints, the ownership rule, and what happens when the database fails.
import { describe, test, expect, beforeEach, afterAll, spyOn } from "bun:test";
import request from "supertest";
import { app } from "../src/app";
import { prisma } from "../src/lib/prisma";
import { resetDb, signUp } from "./helpers";
import * as taskService from "../src/modules/tasks/task.service";
let token: string;
beforeEach(async () => {
await resetDb();
token = await signUp("[email protected]");
});
afterAll(() => prisma.$disconnect());
// A small helper so every request carries Asha's token.
const auth = () => ({ Authorization: `Bearer ${token}` });
describe("tasks need a login", () => {
test("returns 401 without a token", async () => {
const res = await request(app).get("/api/tasks");
expect(res.status).toBe(401);
expect(res.body).toEqual({ error: "Please log in first" });
});
test("returns 401 with a fake token", async () => {
const res = await request(app).get("/api/tasks").set("Authorization", "Bearer not-a-real-token");
expect(res.status).toBe(401);
});
});
describe("CRUD", () => {
test("creates a task", async () => {
const res = await request(app).post("/api/tasks").set(auth()).send({ title: "Buy milk" });
expect(res.status).toBe(201);
expect(res.body).toMatchObject({ title: "Buy milk", done: false });
});
test("rejects a task with no title", async () => {
const res = await request(app).post("/api/tasks").set(auth()).send({});
expect(res.status).toBe(400);
});
test("lists tasks with pagination, newest first", async () => {
for (const title of ["one", "two", "three"]) {
await request(app).post("/api/tasks").set(auth()).send({ title });
}
const res = await request(app).get("/api/tasks?page=1&limit=2").set(auth());
expect(res.status).toBe(200);
expect(res.body.total).toBe(3);
expect(res.body.tasks.map((t: { title: string }) => t.title)).toEqual(["three", "two"]);
});
test("marks a task done, then deletes it", async () => {
const created = await request(app).post("/api/tasks").set(auth()).send({ title: "Buy milk" });
const id = created.body.id;
const updated = await request(app).patch(`/api/tasks/${id}`).set(auth()).send({ done: true });
expect(updated.status).toBe(200);
expect(updated.body.done).toBe(true);
const deleted = await request(app).delete(`/api/tasks/${id}`).set(auth());
expect(deleted.status).toBe(204);
const after = await request(app).get(`/api/tasks/${id}`).set(auth());
expect(after.status).toBe(404);
});
test("returns 400 for an id that isn't a number", async () => {
const res = await request(app).get("/api/tasks/abc").set(auth());
expect(res.status).toBe(400);
});
});
describe("users can't touch each other's tasks", () => {
test("Ravi gets 404 for Asha's task", async () => {
const created = await request(app).post("/api/tasks").set(auth()).send({ title: "Asha's secret" });
const raviToken = await signUp("[email protected]");
const read = await request(app).get(`/api/tasks/${created.body.id}`).set("Authorization", `Bearer ${raviToken}`);
const del = await request(app).delete(`/api/tasks/${created.body.id}`).set("Authorization", `Bearer ${raviToken}`);
expect(read.status).toBe(404);
expect(del.status).toBe(404);
// ...and Asha's task is still there
expect(await prisma.task.count()).toBe(1);
});
});
describe("when the database fails", () => {
test("users get a safe 500, not the real error", async () => {
// Make listTasks fail once, as if the database were down, and keep the error log quiet.
const dbSpy = spyOn(taskService, "listTasks").mockRejectedValueOnce(new Error("connection lost"));
const logSpy = spyOn(console, "error").mockImplementation(() => {});
const res = await request(app).get("/api/tasks").set(auth());
expect(res.status).toBe(500);
expect(res.body).toEqual({ error: "Something went wrong" });
expect(logSpy).toHaveBeenCalled(); // the real error was logged for us
dbSpy.mockRestore();
logSpy.mockRestore();
});
});Three tests here are worth a closer look:
- “lists tasks with pagination, newest first” creates three tasks, asks for page 1 with 2 per page, and checks both the total and the order. It tests the data, not just the status code.
- “Ravi gets 404 for Asha's task” signs up a second user and tries to read and delete Asha's task. Then it checks the database directly: the task must still be there.
- “when the database fails” uses a spy.
spyOn(taskService, "listTasks")replaces the real function for one call and makes it throw, as if PostgreSQL were down. We check users get the safe500message, not the real error.mockRestore()puts the real function back.
Step 7: Run everything
$bun test
bun test v1.4.5
22 pass
0 fail
43 expect() calls
Ran 22 tests across 4 files. [1.62s]Bun runs the test files one after another in a single process, which is why sharing one test database is safe. While you work, keep bun test --watch running: it re-runs the tests every time you save a file.
Watch a test catch a real bug
A test suite is only useful if it fails when the code is wrong. So we broke the code on purpose. Here's what happened when we removed the userId filter from getTask, a one-word mistake that lets any user read any task:
tests/tasks.test.ts:
84 | expect(read.status).toBe(404);
^
error: expect(received).toBe(expected)
Expected: 404
Received: 200
(fail) users can't touch each other's tasks > Ravi gets 404 for Asha's task
7 pass
1 failThe output shows the exact line, what it expected and what it got. We did the same with five more bugs. Try them yourself:
Break the API: which tests catch it?
Pick a bug to sneak into the code:
Each bug was really added to the finished To-Do API, then bun test was run. The red tests are the real results. (Bun itself prints only the failing tests; every test is listed here so you can see which ones stay green.)
Step 8: Find what you forgot (coverage)
Coverage shows which lines of your code ran during the tests. First tell Bun to skip the test files and Prisma's generated code in the report:
[test]
coverageSkipTestFiles = true
coveragePathIgnorePatterns = ["generated/**"]$bun run test:coverage
Our first coverage run, before we wrote app.test.ts and the database-failure test, looked like this:
--------------------------------------|---------|---------|-------------------
File | % Funcs | % Lines | Uncovered Line #s
--------------------------------------|---------|---------|-------------------
All files | 92.50 | 96.74 |
src/app.ts | 0.00 | 94.74 | 18
src/middlewares/auth.ts | 100.00 | 100.00 |
src/middlewares/error-handler.ts | 50.00 | 40.00 | 5-6,14-15,17-18
src/modules/tasks/task.service.ts | 100.00 | 100.00 |
…error-handler.ts was only 40% covered: no test ever hit an unknown URL, sent broken JSON, or made the server crash. Those are exactly the cases that embarrass you in production. So we added three small tests:
import { test, expect } from "bun:test";
import request from "supertest";
import { app } from "../src/app";
test("GET /health says ok", async () => {
const res = await request(app).get("/health");
expect(res.status).toBe(200);
expect(res.body).toEqual({ status: "ok" });
});
test("unknown routes return a JSON 404", async () => {
const res = await request(app).get("/api/nope");
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: "Route GET /api/nope not found" });
});
test("broken JSON returns 400, not a crash", async () => {
const res = await request(app)
.post("/api/auth/login")
.set("Content-Type", "application/json")
.send('{"email": "[email protected]",'); // cut off half-way
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: "Request body is not valid JSON" });
});Together with the database-failure test from Step 6, every line is now covered:
--------------------------------------|---------|---------|-------------------
File | % Funcs | % Lines | Uncovered Line #s
--------------------------------------|---------|---------|-------------------
All files | 100.00 | 100.00 |
src/app.ts | 100.00 | 100.00 |
src/middlewares/error-handler.ts | 100.00 | 100.00 |
…
22 pass
0 failStep 9: Run the tests on every push
Tests only protect you if they run. GitHub Actions can run them on every push and pull request, with its own throwaway PostgreSQL. Add this file and push:
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
# A throwaway PostgreSQL just for this run
services:
postgres:
image: postgres:18
env:
POSTGRES_PASSWORD: postgres
POSTGRES_DB: tasks_app_test
ports: ["5432:5432"]
options: >-
--health-cmd pg_isready --health-interval 5s
--health-timeout 5s --health-retries 10
# These override .env.test, because values already set in the environment win
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/tasks_app_test?schema=public
JWT_SECRET: ci-secret-at-least-16-chars
steps:
- uses: actions/checkout@v5
- uses: oven-sh/setup-bun@v2
- run: bun install --frozen-lockfile
- run: bun run db:test:migrate
- run: bun run db:generate
- run: bun testThe env block overrides .env.test, because values already set in the environment always win over .env files. We checked these exact steps in a clean copy of the project with no .env file: install, migrate, generate, and 22 tests passing. A red ❌ next to a commit on GitHub now means a test failed, before anyone deploys it.
The finished project
tasks-api/ ├── src/ (unchanged: app.ts, modules/, middlewares/ …) ├── tests/ │ ├── helpers.ts resetDb() and signUp() │ ├── task.schema.test.ts unit tests: no database │ ├── auth.test.ts register + login │ ├── tasks.test.ts CRUD, auth, ownership, failures │ └── app.test.ts health, 404, broken JSON ├── .env.test points at tasks_app_test (committed) ├── bunfig.toml coverage settings └── .github/workflows/test.yml runs the tests on every push
What to test in any API
- 1
✅
Happy path
Each endpoint works with good input: right status, right data.
- 2
🚫
Bad input
Missing, empty, too long, wrong type, broken JSON → 400 with a clear message.
- 3
🔐
Auth
No token, fake token → 401. Every protected route.
- 4
👥
Ownership
Another user's id → 404. Check the data is untouched.
- 5
💥
Failures
Database or service down → safe 500, real error logged.
Common mistakes
| Mistake | What goes wrong | Do this instead |
|---|---|---|
| Tests use the dev database | Every run wipes your data | A separate _test database, plus a guard in resetDb |
| Tests depend on each other | Pass alone, fail together (or the other way round) | Reset the database in beforeEach |
| Only checking the status code | Wrong data, wrong order or leaked fields go unnoticed | Check the body too: toEqual / toMatchObject |
| Only testing the happy path | Security bugs ship | Test no token, bad input and someone else's id |
| Forgetting to migrate the test database | "table does not exist" errors | bun run db:test:migrate after every new migration |
| Leaving spies in place | Later tests use the fake function | mockRestore() at the end of the test |
Key takeaways
- ✓We wrote 22 tests: 5 unit tests for the schemas and 17 API tests that go through HTTP to a real database.
- ✓Splitting app.ts from server.ts lets Supertest test the app without starting a server.
- ✓A separate test database plus resetDb() before each test keeps tests independent and your data safe.
- ✓The most important tests try to break the rules: no token, bad input, another user's task, a crashed database.
- ✓Coverage showed what we forgot (the error handler), and GitHub Actions now runs everything on every push.
Next: the last lesson collects every rule from this course into one checklist and cheat sheet, Express API Best Practices.
Frequently asked questions
What is the difference between unit tests and integration tests?
A unit test checks one small piece on its own, like a Zod schema or a helper function, with no database or network. An integration test checks several pieces working together, like a real HTTP request going through routes, middleware, the service and the database. APIs need both: unit tests are fast, integration tests prove the endpoints really work.
What is Supertest?
Supertest is a small library that sends HTTP requests to your Express app inside the test, without starting a real server on a port. You write request(app).post("/api/tasks").send({...}) and get back the status, headers and body to check.
Should tests use my real database?
Use a real PostgreSQL database, but a separate one just for tests (for example tasks_app_test). Tests delete all data before each test, so never point them at your development or production database. Our resetDb helper refuses to run unless the database name contains _test.
Can I use Jest or Vitest instead of bun test?
Yes. bun test uses the same describe / test / expect style as Jest and Vitest, so these tests move over with almost no change: install the runner, change the import from "bun:test" to "vitest" (or use Jest's globals), and load .env.test yourself. Supertest works the same with all three.
What code coverage should I aim for?
There's no magic number. 70 to 90 percent is common for APIs. More important than the number: every endpoint has a happy-path test, and every rule that protects users (auth, ownership, validation) has a test that tries to break it. Coverage shows you what you forgot; it doesn't prove your tests are good.
Why does every test start by emptying the database?
So tests don't depend on each other. If test A leaves a user behind, test B might pass or fail depending on the order. Starting from an empty database every time makes each test give the same answer every run.
🧠 Quick check: testing your API
1. Why can Supertest test our API without starting the server?
2. What does bun test do with .env.test?
3. Removing the userId filter lets anyone read anyone's tasks. Which test catches it?
4. You want one test to act as if the database is down. What do you use?
Checking your access…