Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 39 ยท Testing and Deployment

Testing Plugins, Hooks and Fakes

Test Fastify plugins and hooks in isolation, replace the database, clock and mailer with fakes through dependency injection, and add a few real-socket end-to-end tests.

Once you can call routes with inject (Testing Fastify Apps with inject), the next question is how to test the parts that surround routes: plugins, hooks, and code that talks to the outside world (databases, mail servers, payment APIs, the clock). The answer is the same for all of them: make the dependency something you pass in, then pass a fake in tests.

Fastify is not installed on this site. The examples use the Fastify-like stand-in (same inject shape) plus plain Node. The real-socket example uses node:http on loopback, which does run on the course runner.

Test small, fake the world

Plugin alone Register it on an empty app.
Fake dependencies Pass a stub mailer or clock.
Assert effects Status, body and what the fake saw.

No network, no database, no waiting.

1 / 2

Testing a plugin on an empty app

A plugin is a function that adds routes, hooks or decorators. To test it, register it on a brand-new instance and call it with inject. You do not need the rest of your application. Real Fastify:

JavaScript
import Fastify from 'fastify';
import healthPlugin from '../src/plugins/health.js';

test('health plugin exposes /health', async (t) => {
  const app = Fastify();
  t.after(() => app.close());
  await app.register(healthPlugin, { prefix: '/internal' });   // options are part of the test
  const res = await app.inject({ url: '/internal/health' });
  assert.equal(res.statusCode, 200);
});

The same idea works for a hook: put it in a plugin (or a function that takes the app), add one throwaway route, and check what the hook did to the response. Test the hook's decisions (block, allow, modify), not its internals.

Dependency injection with factories

Look at a signup route that sends a welcome e-mail and stores a timestamp. If it imports a real mail client and calls Date.now() directly, a test would send mail and cannot assert on time. Instead the app takes its collaborators as options:

Node.js Fake mailer and fake clock

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.

Three things make this style pleasant:

  • Time is controllable. clock: () => 1_700_000_000_000 means the test can assert on exact values.
  • Failures are easy to create. Try making a real SMTP server fail on demand; with a fake it is one option.
  • You can assert on what the fake saw, not only on the HTTP response.

In real Fastify you can also pass dependencies through decorators (app.decorate('mailer', mailer)) and override them in a test after building the app, as long as the override happens before the app is ready.

Hooks and plugins with simulated time

Time-based behavior (rate limits, token expiry, caches) is the classic source of slow, flaky tests. Do not await sleep(10000). Pass the clock in, and move it forward:

Node.js Test an expiring cache hook without waiting

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.

Node's own test runner also has mock timers (t.mock.timers.enable()) when the code under test uses setTimeout. Passing a clock function is simpler when you control the code.

A few real end-to-end tests

Fake requests cannot catch problems that only appear on a real socket: keep-alive behavior, request body streaming, proxy headers, listen host/port mistakes, and graceful shutdown. Keep a handful of tests that start a real server on port 0 (any free port) and call it with fetch. This runs on loopback, so it works on the course runner:

Node.js A real server on port 0 called with fetch

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.

Habits that keep a suite healthy

  1. One behavior per test, named like a sentence ("duplicate signup is a 409").
  2. Fresh app and fresh fakes per test. Shared state makes order matter.
  3. Arrange, act, assert, in that order, with the inject call as the single act.
  4. Test failures as carefully as successes: bad input, missing auth, dependency errors.
  5. Do not mock what you do not own too deeply. A fake that mimics a database badly hides real bugs. For SQL code, an in-memory SQLite or a throwaway container often gives more confidence than a hand-written fake.
  6. Run the suite in CI on every push, with coverage reporting to find untested branches.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you test a plugin in isolation?

    A new instance with just the plugin (and its options) isolates the behavior you want to check.
  2. 2. Why pass a clock function into your app instead of calling Date.now() directly?

    An injectable clock makes time-dependent code deterministic and fast to test.
  3. 3. A signup test should confirm that a welcome e-mail was sent. What is the best approach?

    A recording fake keeps the test fast, offline and precise about what was sent.
  4. 4. Why use port 0 in an end-to-end test?

    Port 0 asks the operating system for any free port, which avoids 'address already in use' failures.

Summary

  • Test plugins and hooks by registering them on a fresh instance with a throwaway route.
  • Pass collaborators (mailer, database, clock) into a factory so tests can supply fakes that record calls or fail on demand.
  • Control time with an injected clock instead of sleeping.
  • Keep a few real-socket tests on port 0 for end-to-end behavior and always close the server.
  • Fresh app per test, one behavior per test, and test failure paths as seriously as success paths.

Next: Deploying Fastify: Docker, Environments and Graceful Shutdown