Integration tests for the API and database
Test Taskboard API against a real Postgres: build the app from a factory, reset data between tests, and choose between PGlite and a container.
The testing strategy for a full-stack appTyped queries with an ORM in a featureSeed data and the dev database workflow
Integration tests for the API and database
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Build the app from a factory such as createApp(db) so a test can hand it a test database and call it in-process, with no port to open.
- A real Postgres in the test run means constraints, defaults and error codes behave exactly as they do in production.
- Each test must start from a known state, so truncate the tables with restart identity before every test instead of depending on test order.
- PGlite is a fast in-process Postgres, while a container started by Testcontainers is the real server; use the second when you rely on extensions or server settings.
- Assert on both sides of the seam: the HTTP status and body, and the rows left in the database.
Why the database belongs in the test
The last lesson argued that the most useful tests cross the seam between your route and your database. This lesson builds that. The goal: a test that posts to a real route, goes through real validation and a real insert, and checks the response and the stored row, in under a second per test.
The obstacle people hit is not writing assertions. It is the setup. A test needs a database, that database needs the schema, and every test needs to start from the same data. Get those three right and the tests are boring, which is what you want.
Build the app from a factory
If your server file creates the app and immediately calls listen, a test has no way to swap the database. Split it:
export function createApp(db: PgDatabase<any>) {
const app = new Hono();
app.post("/api/projects/:id/tasks", async (c) => { /* validate, insert, respond */ });
return app;
}
src/server.ts builds the real database and calls serve(createApp(db)). A test builds a test database and calls createApp(testDb). This is dependency injection with no framework: the app receives the one thing that differs between environments.
Hono lets you call the app without a network at all, using app.request(path, init), which returns a standard Response. Express users do the same thing with Supertest (see testing HTTP APIs with Supertest).
A working suite
Here is the complete test file I ran for Taskboard. PGlite is Postgres compiled to run inside the Node process, so there is nothing to install or start:
import { beforeAll, beforeEach, expect, test } from "vitest";
import { PGlite } from "@electric-sql/pglite";
import { drizzle } from "drizzle-orm/pglite";
import { readFileSync } from "node:fs";
import { createApp } from "../src/app";
const pg = new PGlite();
const app = createApp(drizzle(pg));
beforeAll(async () => { await pg.exec(readFileSync("src/schema.sql", "utf8")); });
beforeEach(async () => {
await pg.exec(
"truncate comments, tasks, projects restart identity cascade;" +
"insert into projects(name) values ('Launch')");
});
const post = (path: string, body: unknown) =>
app.request(path, { method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body) });
test("creates a task and reads it back", async () => {
expect((await post("/api/projects/1/tasks", { title: "Write tests" })).status).toBe(201);
const list = await (await app.request("/api/projects/1/tasks")).json();
expect(list).toEqual([{ id: 1, projectId: 1, title: "Write tests", done: false }]);
});
test("rejects an empty title with 400", async () => {
expect((await post("/api/projects/1/tasks", { title: " " })).status).toBe(400);
});
test("a task for a missing project is a 404", async () => {
expect((await post("/api/projects/99/tasks", { title: "x" })).status).toBe(404);
});
I ran this on Node 26, Vitest 5.1.1, Hono 4.13.20, Drizzle 0.45.4, PGlite 0.5.17 and Zod 4.6.7. Three tests passed in about 0.9 seconds including startup.
Three details matter more than they look.
The schema is applied once, the data is reset every time. Running the DDL is slow relative to a truncate, so it goes in beforeAll. The truncate ... restart identity cascade in beforeEach empties every table and resets the serial counters, which is why the assertion can hard-code id: 1. Without restart identity, the second test would see id 2.
Never depend on test order. If test B only passes because test A inserted something, a single failing test, a filter like -t "B", or parallel execution breaks it. Reset in beforeEach and let each test create what it needs.
Assert across the seam. The first test checks the HTTP response and then reads the tasks back through the API. You can also query the table directly (pg.query("select * from tasks")) when you want to be sure the stored row, not just the response, is right.
PGlite or a real server
PGlite is fast and needs nothing installed, so it suits a repo where the whole team runs tests on a laptop. Its limits: it is a single connection, it supports a defined set of extensions, and it is not the exact server binary you deploy.
The alternative is a throwaway real Postgres in a container, started by a library called Testcontainers. The video this lesson embeds does exactly that with Vitest. It is slower to start (seconds, plus Docker) but it is the same engine and version as production. Pick it when your code uses an extension PGlite lacks, when you test concurrent writers, or when you want CI to match production exactly.
I could not run Docker on the machine I tested on, so the Testcontainers path below is from the video and docs, not something I executed. The PGlite path above I did run.
A reasonable rule: start with PGlite, and move a test to a real container the first time it passes on one and fails on the other.
Migrations in the test database
Notice that the suite applies schema.sql directly. In a real project you want the test database built by the same migrations that build production, so a bad migration fails in tests before it fails in a deploy. Run your migration tool against the test database in beforeAll instead of loading a hand-written file. For the mechanics of migration tools see schema migrations and change management, and the dev-database habits in seed data and the dev database workflow.
Things that make these tests flaky
- Shared database between parallel test files. Each file gets its own database or schema, or you run the file serially. PGlite gives each
new PGlite()its own memory, which sidesteps this. - Clock and randomness. Inject them or use fake timers, so the test does not depend on the second it ran.
- Leftover rows from a failed run. Reset at the start, not the end, because a crash skips the cleanup.
What the video covers
Alex Rusin’s “Node.js Integration Tests with a Real Postgres Database (Testcontainers + Vitest)” runs about 13 minutes and, from its title, shows exactly the container approach above with Vitest on Node. It is two months old at the time of writing, which matters because Testcontainers and Vitest both change. I could not read a transcript, so I cannot say how it handles migrations or parallel files. Dreams of Code’s Testcontainers video is linked for a general view of the idea.
Where this fits
API tests cover the server. They do not prove the browser and the server agree. For that you need a real browser, which is next: end-to-end tests with Playwright.
Check yourself
Why export createApp(db) instead of a ready-made app?
The test can pass in its own database and call app.request() directly, so nothing listens on a port and every test controls its own data.
What does truncate ... restart identity cascade do for tests?
It empties the tables and resets the auto-increment counters, so every test sees the same ids and the same empty starting point regardless of order.
When would you pick a container over PGlite?
When the code depends on a real server feature such as an extension, a specific version's behaviour, or concurrent connections, since PGlite is a single-connection build.
What should a good API integration test assert besides the status code?
The response body shape and the resulting database state, because a route can return 201 and still have stored the wrong row.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.