Testing
Fifteenth chapter of the "Fastify with TypeScript" series. Thanks to the app.ts / server.ts separation and the config overrides from chapter 4, testing Fastify is simple and fast: no network ports, no test framework to install, just simulated requests through Node's built-in test runner. We'll write the tests, then automate everything around them: lint, coverage and CI.
Fastify's inject() method simulates an HTTP request without opening a network port. The request goes through the whole lifecycle (hooks, validation, handler, serialization) and you get the response back as an object. It's the fastest way to test routes and plugins.
A test helper
Create test/helper.ts:
// test/helper.ts
import { buildApp, type App } from '../src/app.ts';
export async function build(): Promise<App> {
const app = buildApp(
{ logger: false },
{
JWT_SECRET: 'test-secret-test-secret-test-secret-1234',
DATABASE_URL: process.env.DATABASE_URL ?? 'postgres://postgres:postgres@localhost:5432/app_test',
},
);
await app.ready();
return app;
}
The second argument to buildApp() overrides the environment, so tests never depend on a .env file. await app.ready() loads every plugin without listening on a port. And because buildApp() creates everything from scratch on each call, every test file gets an application of its own, with nothing shared.
The first tests
Create test/users.test.ts:
// test/users.test.ts
import { describe, it, before, after } from 'node:test';
import { build } from './helper.ts';
import type { App } from '../src/app.ts';
describe('User API', () => {
let app: App;
before(async () => {
app = await build();
});
after(async () => {
await app.close();
});
it('answers on /health', async (t) => {
const response = await app.inject({ method: 'GET', url: '/health' });
t.assert.equal(response.statusCode, 200);
t.assert.deepEqual(response.json(), { status: 'ok' });
});
it('rejects invalid emails', async (t) => {
const response = await app.inject({
method: 'POST',
url: '/api/v1/users',
payload: { name: 'John', email: 'not-an-email', password: 'supersecret' },
});
t.assert.equal(response.statusCode, 400);
});
it('requires a token on GET /api/v1/users/:id', async (t) => {
const response = await app.inject({
method: 'GET',
url: '/api/v1/users/3f2f9c2e-9b0a-4a5c-8d1e-7b6f5a4c3d2e',
});
t.assert.equal(response.statusCode, 401);
// same shape as every other error, thanks to the central error handler
t.assert.deepEqual(response.json(), {
statusCode: 401,
error: 'UNAUTHORIZED',
message: 'Missing or invalid token',
});
});
it('creates a user', { skip: !process.env.DATABASE_URL }, async (t) => {
const response = await app.inject({
method: 'POST',
url: '/api/v1/users',
payload: { name: 'John Doe', email: `john-${Date.now()}@example.com`, password: 'supersecret' },
});
t.assert.equal(response.statusCode, 201);
t.assert.equal(typeof response.json().id, 'string');
t.assert.equal(response.json().password_hash, undefined);
});
});
Run them:
npm test
A few things worth noticing:
-
let app: Appuses the type exported fromapp.ts, soapp.inject()is fully typed. Without the annotation,strictmode would reject thet.assertcalls (assertion functions need every name in the call to be explicitly typed). -
t.assertis the test context's assertion API (Node 22.2+), so there's nothing to import. - The first three tests never reach the database: validation and authentication reject the request before any query runs. They pass on any machine.
- The last one needs a database and is skipped unless
DATABASE_URLis set. Its final assertion proves the response schema stripspassword_hash, which is exactly the kind of regression you want a test for.
A database for the tests
Tests create users, so they shouldn't run against the database you develop with. Create a second one in the same PostgreSQL and give it the same table:
docker exec fastify-pg createdb -U postgres app_test
docker exec -i fastify-pg psql -U postgres -d app_test < sql/001-users.sql
DATABASE_URL=postgres://postgres:postgres@localhost:5432/app_test npm test
Now the fourth test runs too.
End-to-end against a real PostgreSQL
Small tests are fast, but the bugs that hurt most live at the seams. Does the 409 fire on a duplicate email, even when two requests arrive together? Does a wrong email get the same answer as a wrong password? Does the login rate limit kick in? One file that walks the whole flow answers all of that. Create test/e2e.test.ts:
// test/e2e.test.ts — full flow against a real PostgreSQL (needs DATABASE_URL)
import { describe, it, before, after } from 'node:test';
import { build } from './helper.ts';
import type { App } from '../src/app.ts';
describe('End-to-end user flow', { skip: !process.env.DATABASE_URL }, () => {
let app: App;
const email = `e2e-${Date.now()}@example.com`;
const password = 'correct horse battery staple';
let userId: string;
let token: string;
before(async () => {
app = await build();
});
after(async () => {
await app.pg.query('DELETE FROM users WHERE email LIKE $1', ['e2e-%@example.com']);
await app.close();
});
it('creates a user and never returns the password hash', async (t) => {
const res = await app.inject({
method: 'POST',
url: '/api/v1/users',
payload: { name: 'E2E User', email, password },
});
t.assert.equal(res.statusCode, 201);
const body = res.json();
t.assert.equal(typeof body.id, 'string');
t.assert.equal(body.email, email);
t.assert.equal(body.role, 'user');
t.assert.equal('password_hash' in body, false);
userId = body.id;
const { rows } = await app.pg.query('SELECT password_hash FROM users WHERE id = $1', [userId]);
t.assert.match(rows[0].password_hash, /^\$argon2id\$/);
});
it('rejects a duplicate email with 409 and a stable error code', async (t) => {
const res = await app.inject({
method: 'POST',
url: '/api/v1/users',
payload: { name: 'Again', email, password },
});
t.assert.equal(res.statusCode, 409);
t.assert.equal(res.json().error, 'EMAIL_TAKEN');
});
it('two concurrent sign-ups with the same email give one 201 and one 409', async (t) => {
const payload = { name: 'Racer', email: `e2e-race-${Date.now()}@example.com`, password };
const results = await Promise.all([
app.inject({ method: 'POST', url: '/api/v1/users', payload }),
app.inject({ method: 'POST', url: '/api/v1/users', payload }),
]);
t.assert.deepEqual(results.map((r) => r.statusCode).sort(), [201, 409]);
});
it('rejects login with a wrong password', async (t) => {
const res = await app.inject({
method: 'POST',
url: '/auth/login',
payload: { email, password: 'nope' },
});
t.assert.equal(res.statusCode, 401);
t.assert.equal(res.json().error, 'INVALID_CREDENTIALS');
});
it('answers an unknown email exactly like a wrong password', async (t) => {
const res = await app.inject({
method: 'POST',
url: '/auth/login',
payload: { email: 'e2e-nobody@example.com', password },
});
t.assert.equal(res.statusCode, 401);
t.assert.equal(res.json().error, 'INVALID_CREDENTIALS');
});
it('logs in and returns a JWT', async (t) => {
const res = await app.inject({
method: 'POST',
url: '/auth/login',
payload: { email, password },
});
t.assert.equal(res.statusCode, 200);
token = res.json().token;
t.assert.equal(typeof token, 'string');
});
it('GET /auth/me returns the token payload', async (t) => {
const res = await app.inject({ url: '/auth/me', headers: { authorization: `Bearer ${token}` } });
t.assert.equal(res.statusCode, 200);
t.assert.equal(res.json().user.id, userId);
t.assert.equal(res.json().user.role, 'user');
});
it('GET /api/v1/users/:id works with a token', async (t) => {
const res = await app.inject({
url: `/api/v1/users/${userId}`,
headers: { authorization: `Bearer ${token}` },
});
t.assert.equal(res.statusCode, 200);
t.assert.equal(res.json().email, email);
t.assert.equal('password_hash' in res.json(), false);
});
it('GET /api/v1/users/:id returns 404 with USER_NOT_FOUND for an unknown id', async (t) => {
const res = await app.inject({
url: '/api/v1/users/00000000-0000-4000-8000-000000000000',
headers: { authorization: `Bearer ${token}` },
});
t.assert.equal(res.statusCode, 404);
t.assert.equal(res.json().error, 'USER_NOT_FOUND');
});
it('GET /api/v1/users is forbidden for a plain user', async (t) => {
const res = await app.inject({ url: '/api/v1/users', headers: { authorization: `Bearer ${token}` } });
t.assert.equal(res.statusCode, 403);
t.assert.equal(res.json().error, 'FORBIDDEN');
});
it('GET /api/v1/users works for an admin', async (t) => {
await app.pg.query("UPDATE users SET role = 'admin' WHERE id = $1", [userId]);
const adminToken = app.jwt.sign({ id: userId, email, role: 'admin' });
const headers = { authorization: `Bearer ${adminToken}` };
const res = await app.inject({ url: '/api/v1/users', headers });
t.assert.equal(res.statusCode, 200);
t.assert.equal(Array.isArray(res.json()), true);
t.assert.equal('password_hash' in res.json()[0], false);
// the limit comes from the query string as text and reaches the database as a number
const one = await app.inject({ url: '/api/v1/users?limit=1', headers });
t.assert.equal(one.json().length, 1);
const invalid = await app.inject({ url: '/api/v1/users?limit=0', headers });
t.assert.equal(invalid.statusCode, 400);
});
it('login is rate limited after 5 attempts per minute', async (t) => {
let last = 0;
for (let i = 0; i < 6; i++) {
const res = await app.inject({
method: 'POST',
url: '/auth/login',
payload: { email, password: 'wrong' },
});
last = res.statusCode;
}
t.assert.equal(last, 429);
});
it('the login limit does not apply to GET /auth/me', async (t) => {
const res = await app.inject({ url: '/auth/me', headers: { authorization: `Bearer ${token}` } });
t.assert.equal(res.statusCode, 200);
});
});
The whole describe is skipped without DATABASE_URL, and the after hook removes the users it created.
We test against a real PostgreSQL on purpose. A mocked database driver would happily accept SQL with a typo in it, and could never tell you that ON CONFLICT really resolves the race between two sign-ups. For the normal path, use the real thing.
Testing a service without Fastify
The services from chapter 13 are factories that receive their dependencies, so a test can pass fake ones: no app, no database, and the business rules are checked in milliseconds. Create test/users.service.test.ts:
// test/users.service.test.ts — the service against a fake repository: no Fastify, no database
import { describe, it } from 'node:test';
import { createUserService } from '../src/users/users.service.ts';
import type { UserRepository, UserRow } from '../src/users/users.repository.ts';
function fakeRepository(rows: UserRow[] = []): UserRepository {
return {
async findById(id) {
return rows.find((u) => u.id === id) ?? null;
},
async findByEmail(email) {
return rows.find((u) => u.email === email) ?? null;
},
async create({ name, email, passwordHash }) {
const row: UserRow = { id: crypto.randomUUID(), name, email, role: 'user', password_hash: passwordHash };
rows.push(row);
return row;
},
async findAll(limit) {
return rows.slice(0, limit);
},
};
}
describe('User service', () => {
it('hashes the password before storing it', async (t) => {
const service = createUserService(fakeRepository());
const user = await service.create({ name: 'Ada', email: 'ada@example.com', password: 'supersecret' });
t.assert.match(user.password_hash, /^\$argon2id\$/);
});
it('rejects a duplicate email with EMAIL_TAKEN', async (t) => {
const service = createUserService(fakeRepository());
const input = { name: 'Ada', email: 'ada@example.com', password: 'supersecret' };
await service.create(input);
await t.assert.rejects(service.create(input), { code: 'EMAIL_TAKEN', statusCode: 409 });
});
it('still answers EMAIL_TAKEN when it loses a race on the insert', async (t) => {
// The pre-check finds nothing, but by the time we insert another request got there first.
const racing: UserRepository = { ...fakeRepository(), create: async () => null };
const service = createUserService(racing);
const input = { name: 'Ada', email: 'ada@example.com', password: 'supersecret' };
await t.assert.rejects(service.create(input), { code: 'EMAIL_TAKEN', statusCode: 409 });
});
it('throws USER_NOT_FOUND for an unknown id', async (t) => {
const service = createUserService(fakeRepository());
await t.assert.rejects(service.getById('nope'), { code: 'USER_NOT_FOUND', statusCode: 404 });
});
});
Typing the fake as UserRepository means the compiler tells you when the real repository gains a method the fake is missing. The race test shows where a fake is the right tool: a situation that needs two perfectly timed requests against a real database takes one line here.
The auth service gets the same treatment, with a fake repository and a fake token signer. Create test/auth.service.test.ts:
// test/auth.service.test.ts — the login rules against a fake repository and a fake signer
import { describe, it, before } from 'node:test';
import { hash } from 'argon2';
import { createAuthService } from '../src/auth/auth.service.ts';
import type { UserRepository, UserRow } from '../src/users/users.repository.ts';
describe('Auth service', () => {
let ada: UserRow;
let repository: UserRepository;
before(async () => {
ada = {
id: crypto.randomUUID(),
name: 'Ada',
email: 'ada@example.com',
role: 'user',
password_hash: await hash('supersecret'),
};
repository = {
findById: async (id) => (id === ada.id ? ada : null),
findByEmail: async (email) => (email === ada.email ? ada : null),
create: async () => null,
findAll: async () => [ada],
};
});
it('signs a token with the user id, email and role', async (t) => {
const auth = createAuthService(repository, (payload) => JSON.stringify(payload));
const token = await auth.login({ email: ada.email, password: 'supersecret' });
t.assert.deepEqual(JSON.parse(token), { id: ada.id, email: ada.email, role: 'user' });
});
it('rejects a wrong password with INVALID_CREDENTIALS', async (t) => {
const auth = createAuthService(repository, () => 'token');
await t.assert.rejects(
auth.login({ email: ada.email, password: 'wrong' }),
{ code: 'INVALID_CREDENTIALS', statusCode: 401 },
);
});
it('rejects an unknown email with the very same error', async (t) => {
const auth = createAuthService(repository, () => 'token');
await t.assert.rejects(
auth.login({ email: 'nobody@example.com', password: 'supersecret' }),
{ code: 'INVALID_CREDENTIALS', statusCode: 401 },
);
});
});
Testing a plugin in isolation
A plugin can be tested on its own, on a bare Fastify instance, without the rest of the application. Create test/auth.test.ts:
// test/auth.test.ts
import Fastify from 'fastify';
import { it } from 'node:test';
import auth from '../src/plugins/auth.ts';
import type { App } from '../src/app.ts';
it('rejects requests without a token', async (t) => {
const app = Fastify();
app.decorate('config', { JWT_SECRET: 'x'.repeat(32) } as App['config']);
await app.register(auth);
app.get('/secret', { onRequest: [app.authenticate] }, async () => ({ ok: true }));
const response = await app.inject({ url: '/secret' });
t.assert.equal(response.statusCode, 401);
t.assert.equal(response.json().code, 'UNAUTHORIZED');
});
The auth plugin reads fastify.config, so the test provides just that one decorator. This is encapsulation paying off once more: a plugin only needs what it declares it needs.
Testing the contract
The OpenAPI document is what the consumers of the API rely on, so it deserves a test too. Create test/openapi.test.ts:
// test/openapi.test.ts — the API contract, no database needed
import { describe, it, before, after } from 'node:test';
import { build } from './helper.ts';
import type { App } from '../src/app.ts';
describe('API contract', () => {
let app: App;
before(async () => {
app = await build();
});
after(async () => {
await app.close();
});
it('publishes an OpenAPI document generated from the route schemas', async (t) => {
const response = await app.inject({ url: '/openapi.json' });
t.assert.equal(response.statusCode, 200);
const spec = response.json();
t.assert.equal(spec.openapi, '3.1.0');
t.assert.deepEqual(Object.keys(spec.paths).sort(), [
'/api/v1/users/',
'/api/v1/users/{id}',
'/auth/login',
'/auth/me',
]);
// the body schema of POST /users is the TypeBox schema, not a second copy
const body = spec.paths['/api/v1/users/'].post.requestBody.content['application/json'].schema;
t.assert.deepEqual(body.required, ['name', 'email', 'password']);
// protected routes declare the bearer token
t.assert.deepEqual(spec.paths['/api/v1/users/{id}'].get.security, [{ bearerAuth: [] }]);
});
});
If someone removes a route or forgets to declare that it needs a token, this test fails before a client finds out.
Lint
Tests are one automated check. A linter is another: it reads the code without running it and reports what looks like a mistake, such as unused variables and imports, unreachable code, conditions that are always true. We use ESLint with neostandard, a ready-made set of rules:
npm install -D eslint@9 neostandard
Create eslint.config.js in the root of the project:
// eslint.config.js
import neostandard from 'neostandard';
export default neostandard({
ts: true, // lint .ts files too
noStyle: true, // correctness rules only: formatting is not this tool's job here
ignores: ['dist/**'],
});
noStyle: true switches off the formatting rules (quotes, semicolons, spacing) and keeps the ones about correctness. Add the script to package.json:
"lint": "eslint ."
npm run lint prints nothing: the project is clean. To see it catch something, add import { Type } from 'typebox'; at the top of src/users/users.service.ts, where it isn't needed:
src/users/users.service.ts
4:10 error 'Type' is defined but never used @typescript-eslint/no-unused-vars
Harmless on its own, but exactly the kind of leftover that accumulates when nobody is checking. Remove the line.
Coverage
Node's test runner can report which lines the tests actually executed, with no extra package. Add this script:
"test:coverage": "node --test --experimental-test-coverage 'test/**/*.test.ts'"
DATABASE_URL=postgres://postgres:postgres@localhost:5432/app_test npm run test:coverage
Most files are at 100%, but one line stands out:
# file | line % | branch % | funcs % | uncovered lines
# error-handler.ts | 87.50 | 61.54 | 66.67 | 12 42-46
Line 12 is the request.log.error of the 5xx branch, and lines 42-46 are the handler for unknown URLs. No test makes a route throw an unexpected error, and no test requests a URL that doesn't exist, so more than a third of the branches never ran, including the code that hides the details of a 5xx. That is one of the most important behaviors of the whole API, and nothing checks it. Create test/errors.test.ts:
// test/errors.test.ts — the error handler on its own: no config, no database
import { describe, it, before, after } from 'node:test';
import Fastify, { type FastifyInstance } from 'fastify';
import errorHandler from '../src/plugins/error-handler.ts';
describe('Error handler', () => {
let app: FastifyInstance;
before(async () => {
app = Fastify();
await app.register(errorHandler);
app.get('/boom', async () => {
// what a failed database connection looks like: a message and a code, both internal
throw Object.assign(new Error('connect ECONNREFUSED db-prod-01:5432'), { code: 'ECONNREFUSED' });
});
await app.ready();
});
after(async () => {
await app.close();
});
it('hides the message and the code of an unexpected error', async (t) => {
const response = await app.inject({ url: '/boom' });
t.assert.deepEqual(response.json(), {
statusCode: 500,
error: 'INTERNAL_ERROR',
message: 'Internal Server Error',
});
});
it('answers unknown URLs with the same shape', async (t) => {
const response = await app.inject({ url: '/nope' });
t.assert.deepEqual(response.json(), {
statusCode: 404,
error: 'ROUTE_NOT_FOUND',
message: 'Route GET /nope not found',
});
});
});
Run the coverage again and error-handler.ts is at 100% on every column.
That's how to use coverage: read the report for what it shows you, the code no test touches, rather than chasing a percentage. A suite can reach 100% and still never try a wrong password.
CI
A check that depends on someone remembering to run it will eventually be skipped, so run all of them on every push. Create .github/workflows/ci.yml:
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: postgres
POSTGRES_DB: app_test
ports: ['5432:5432']
options: >-
--health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with: { node-version: 24 }
- run: npm ci
- run: npm audit --omit=dev --audit-level=high
- run: npm run lint
- run: npm run typecheck
- run: psql postgres://postgres:postgres@localhost:5432/app_test -f sql/001-users.sql
- run: npm run test:coverage
env:
DATABASE_URL: postgres://postgres:postgres@localhost:5432/app_test
Three details:
-
npm ciinstalls exactly the versions inpackage-lock.json, so CI tests the same dependency tree you have locally. -
npm auditfails the build when a production dependency has a known vulnerability of high severity. Running it while preparing this series reported advisories for four packages, all fixed bynpm audit fix. Known vulnerabilities in dependencies are routine, which is why the check has to be automatic. - PostgreSQL runs as a service next to the job, so the end-to-end tests run on every push too.
⬅️ Previous chapter: Security: CORS, Helmet, rate limiting · ➡️ Next chapter: Logging
This article is part of the "Fastify with TypeScript" series — chapter 15 of 18.
Top comments (1)
coverage reached hundred