Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 39 ยท Testing and Deployment

Testing Fastify Apps with inject

Test Fastify routes without opening a port: build the app in a factory, call app.inject, assert status, headers and JSON, and run it all with node:test.

A big reason teams pick Fastify is how easy it is to test. Every Fastify instance has an inject() method that sends a fake HTTP request straight into the router and returns the response, without binding a port, opening sockets or making network calls. Tests run in milliseconds, can run in parallel, and never fail because "port 3000 is already in use".

This lesson shows the testable shape for an app (a factory function), how to write assertions with inject, how to organize cases for validation, errors and authentication, and how the same tests run under Node's built-in runner, node:test.

The real fastify package is not installed on this site, so runnable examples use the Fastify-like stand-in that has the same inject shape: { method, url, headers, payload } in, { statusCode, headers, body, json() } out. The real node:test code is shown read-only, because its output includes timings that change on every run.

Why inject is great

No port Nothing to bind or clean up.
Fast Hundreds of tests per second.
Full pipeline Hooks, schemas, errors all run.
Parallel safe Each test gets its own app.

It is the real router, minus the network.

1 / 2

Step 1: export a factory, not a running server

The single most useful habit is to build the app in a function and start listening somewhere else. A common layout:

TEXT
src/
  app.js      exports buildApp(options) -> Fastify instance (no listen)
  server.js   imports buildApp, reads config, calls listen
test/
  items.test.js
JavaScript
// src/app.js (real Fastify)
import Fastify from 'fastify';
export function buildApp(options = {}) {
  const app = Fastify(options);
  app.register(import('./routes/items.js'));
  return app;
}

// src/server.js
import { buildApp } from './app.js';
const app = buildApp({ logger: true });
await app.listen({ port: 3000, host: '0.0.0.0' });

Tests import buildApp, get a fresh instance per test, and never call listen. This also lets you pass test options (such as logger: false) or fake dependencies.

Step 2: inject requests and assert

The example below has a small items API and a mini test harness (test and assert) written with only node:assert. Each test builds its own app, so tests cannot affect one another.

Node.js A tiny test suite using inject

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last case fails on purpose so you can see what a failure report looks like: the name of the test and the assertion message. In a real test run the assert message also shows the expected and actual values.

With real Fastify and the built-in runner, the same tests read like this:

JavaScript
// test/items.test.js, run with: node --test
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { buildApp } from '../src/app.js';

test('GET /items returns the list', async (t) => {
  const app = buildApp();
  t.after(() => app.close());                      // close plugins, DB pools, timers

  const res = await app.inject({ method: 'GET', url: '/items' });
  assert.equal(res.statusCode, 200);
  assert.deepEqual(res.json(), []);
});

Close the instance in t.after (or afterEach) so connections and timers opened by plugins do not keep the process alive.

What to test

A useful route test covers the contract, not the internals:

  • The success path: status, body shape, important headers (content-type, location after a 201).
  • Validation failures: missing fields, wrong types, extra fields. Assert the 400 and that the message is readable.
  • Not found and conflict responses.
  • Authentication and authorization: no token (401), wrong role (403), someone else's record (404).
  • Side effects: after a POST, a GET shows the new record.
Node.js Table-driven tests for auth and validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Table-driven tests keep large permission matrices short and make a missing case easy to spot.

Testing with a real server too

inject is perfect for most tests, but one or two end-to-end tests should use a real socket: they confirm that the server really listens, that keep-alive and graceful shutdown work, and that your proxy settings are right. Start on port 0 (the operating system picks a free port) and call it with fetch:

JavaScript
const address = await app.listen({ port: 0, host: '127.0.0.1' });
const res = await fetch(address + '/items');

Keep such tests few and put them in a separate folder so day-to-day runs stay fast.

Tips for stable tests

  • Create the app inside each test (or beforeEach) so no state leaks.
  • Pass dependencies in (database, clock, mailer) so tests can replace them with fakes; see Testing Plugins, Hooks and Fakes.
  • Turn the logger off (logger: false) in tests, or write logs to a stream you can inspect.
  • Do not assert on exact timestamps or random ids; assert on shape (typeof, patterns).
  • Run with node --test --experimental-test-coverage to see which routes no test reaches.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does app.inject() do?

    inject runs the full request pipeline (hooks, validation, handler, serialization) without opening a port.
  2. 2. Why export a buildApp factory instead of a running server?

    A factory lets tests create isolated instances with test options and fakes, and the real entry file calls listen separately.
  3. 3. Which assertion belongs in a test of a route that creates something?

    Test the contract: status, shape and side effects. Avoid exact timestamps and random values.
  4. 4. Why call app.close() after a test?

    Open handles keep the Node process alive. Closing runs onClose hooks that shut those resources down.

Summary

  • Build the app in a factory (buildApp) and call listen only in the entry file.
  • app.inject({ method, url, headers, payload }) returns statusCode, headers, body and json() with no network involved.
  • Cover success, validation errors, 404s, 401/403 and side effects; table-driven cases keep matrices compact.
  • Create a fresh app per test, close it afterwards, turn the logger off, and keep a few real-socket tests for end-to-end checks.

Next: Testing Plugins, Hooks and Fakes