Testing

Testing is one of the most important parts of developing an application. Fastify is very flexible when it comes to testing and is compatible with most testing frameworks (such as Node Test Runner, which is used in the examples below).

Application

Let’s cd into a fresh directory called ‘testing-example’ and type npm init -y in our terminal.

Run npm i fastify && npm i pino-pretty -D

Separating concerns makes testing easy

First, we are going to separate our application code from our server code:

app.js:

  1. 'use strict'
  2. const fastify = require('fastify')
  3. function build(opts={}) {
  4. const app = fastify(opts)
  5. app.get('/', async function (request, reply) {
  6. return { hello: 'world' }
  7. })
  8. return app
  9. }
  10. module.exports = build

server.js:

  1. 'use strict'
  2. const server = require('./app')({
  3. logger: {
  4. level: 'info',
  5. transport: {
  6. target: 'pino-pretty'
  7. }
  8. }
  9. })
  10. server.listen({ port: 3000 }, (err, address) => {
  11. if (err) {
  12. server.log.error(err)
  13. process.exit(1)
  14. }
  15. })

Benefits of using fastify.inject()

Fastify comes with built-in support for fake HTTP injection thanks to light-my-request.

Before introducing any tests, we will use the .inject method to make a fake request to our route:

app.test.js:

  1. 'use strict'
  2. const build = require('./app')
  3. const test = async () => {
  4. const app = build()
  5. const response = await app.inject({
  6. method: 'GET',
  7. url: '/'
  8. })
  9. console.log('status code: ', response.statusCode)
  10. console.log('body: ', response.body)
  11. }
  12. test()

First, our code will run inside an asynchronous function, giving us access to async/await.

.inject ensures all registered plugins have booted up and our application is ready to test. Finally, we pass the request method we want to use and a route. Using await we can store the response without a callback.

Run the test file in your terminal node app.test.js

  1. status code: 200
  2. body: {"hello":"world"}

Testing with HTTP injection

Now we can replace our console.log calls with actual tests!

In your package.json change the “test” script to:

"test": "node --test --watch"

app.test.js:

  1. 'use strict'
  2. const { test } = require('node:test')
  3. const build = require('./app')
  4. test('requests the "/" route', async t => {
  5. t.plan(1)
  6. const app = build()
  7. const response = await app.inject({
  8. method: 'GET',
  9. url: '/'
  10. })
  11. t.assert.strictEqual(response.statusCode, 200, 'returns a status code of 200')
  12. })

Finally, run npm test in the terminal and see your test results!

The inject method can do much more than a simple GET request to a URL:

  1. fastify.inject({
  2. method: String,
  3. url: String,
  4. query: Object,
  5. payload: Object,
  6. headers: Object,
  7. cookies: Object
  8. }, (error, response) => {
  9. // your tests
  10. })

.inject methods can also be chained by omitting the callback function:

  1. fastify
  2. .inject()
  3. .get('/')
  4. .headers({ foo: 'bar' })
  5. .query({ foo: 'bar' })
  6. .end((err, res) => { // the .end call will trigger the request
  7. console.log(res.payload)
  8. })

or in the promisified version

  1. fastify
  2. .inject({
  3. method: String,
  4. url: String,
  5. query: Object,
  6. payload: Object,
  7. headers: Object,
  8. cookies: Object
  9. })
  10. .then(response => {
  11. // your tests
  12. })
  13. .catch(err => {
  14. // handle error
  15. })

Async await is supported as well!

  1. try {
  2. const res = await fastify.inject({ method: String, url: String, payload: Object, headers: Object })
  3. // your tests
  4. } catch (err) {
  5. // handle error
  6. }

Another Example:

app.js

  1. const Fastify = require('fastify')
  2. function buildFastify () {
  3. const fastify = Fastify()
  4. fastify.get('/', function (request, reply) {
  5. reply.send({ hello: 'world' })
  6. })
  7. return fastify
  8. }
  9. module.exports = buildFastify

test.js

  1. const { test } = require('node:test')
  2. const buildFastify = require('./app')
  3. test('GET `/` route', t => {
  4. t.plan(4)
  5. const fastify = buildFastify()
  6. // At the end of your tests it is highly recommended to call `.close()`
  7. // to ensure that all connections to external services get closed.
  8. t.after(() => fastify.close())
  9. fastify.inject({
  10. method: 'GET',
  11. url: '/'
  12. }, (err, response) => {
  13. t.assert.ifError(err)
  14. t.assert.strictEqual(response.statusCode, 200)
  15. t.assert.strictEqual(response.headers['content-type'], 'application/json; charset=utf-8')
  16. t.assert.deepStrictEqual(response.json(), { hello: 'world' })
  17. })
  18. })

Testing with a running server

Fastify can also be tested after starting the server with fastify.listen() or after initializing routes and plugins with fastify.ready().

Example:

Uses app.js from the previous example.

test-listen.js (testing with undici)

  1. const { test } = require('node:test')
  2. const { Client } = require('undici')
  3. const buildFastify = require('./app')
  4. test('should work with undici', async t => {
  5. t.plan(2)
  6. const fastify = buildFastify()
  7. await fastify.listen()
  8. const client = new Client(
  9. 'http://localhost:' + fastify.server.address().port, {
  10. keepAliveTimeout: 10,
  11. keepAliveMaxTimeout: 10
  12. }
  13. )
  14. t.after(() => {
  15. fastify.close()
  16. client.close()
  17. })
  18. const response = await client.request({ method: 'GET', path: '/' })
  19. t.assert.strictEqual(await response.body.text(), '{"hello":"world"}')
  20. t.assert.strictEqual(response.statusCode, 200)
  21. })

Alternatively, starting with Node.js 18, fetch may be used without requiring any extra dependencies:

test-listen.js

  1. const { test } = require('node:test')
  2. const buildFastify = require('./app')
  3. test('should work with fetch', async t => {
  4. t.plan(3)
  5. const fastify = buildFastify()
  6. t.after(() => fastify.close())
  7. await fastify.listen()
  8. const response = await fetch(
  9. 'http://localhost:' + fastify.server.address().port
  10. )
  11. t.assert.strictEqual(response.status, 200)
  12. t.assert.strictEqual(
  13. response.headers.get('content-type'),
  14. 'application/json; charset=utf-8'
  15. )
  16. const jsonResult = await response.json()
  17. t.assert.strictEqual(jsonResult.hello, 'world')
  18. })

test-ready.js (testing with SuperTest)

  1. const { test } = require('node:test')
  2. const supertest = require('supertest')
  3. const buildFastify = require('./app')
  4. test('GET `/` route', async (t) => {
  5. const fastify = buildFastify()
  6. t.after(() => fastify.close())
  7. await fastify.ready()
  8. const response = await supertest(fastify.server)
  9. .get('/')
  10. .expect(200)
  11. .expect('Content-Type', 'application/json; charset=utf-8')
  12. t.assert.deepStrictEqual(response.body, { hello: 'world' })
  13. })

How to inspect node tests

  1. Isolate your test by passing the {only: true} option
  1. test('should ...', {only: true}, t => ...)
  1. Run node --test
  1. > node --test --test-only --node-arg=--inspect-brk test/<test-file.test.js>
  • --test-only specifies to run tests with the only option enabled
  • --node-arg=--inspect-brk will launch the node debugger
  1. In VS Code, create and launch a Node.js: Attach debug configuration. No modification should be necessary.

Now you should be able to step through your test file (and the rest of Fastify) in your code editor.

Plugins

Let’s cd into a fresh directory called ‘testing-plugin-example’ and type npm init -y in our terminal.

Run npm i fastify fastify-plugin

plugin/myFirstPlugin.js:

  1. const fP = require("fastify-plugin")
  2. async function myPlugin(fastify, options) {
  3. fastify.decorateRequest("helloRequest", "Hello World")
  4. fastify.decorate("helloInstance", "Hello Fastify Instance")
  5. }
  6. module.exports = fP(myPlugin)

A basic example of a Plugin. See Plugin Guide

test/myFirstPlugin.test.js:

  1. const Fastify = require("fastify");
  2. const { test } = require("node:test");
  3. const myPlugin = require("../plugin/myFirstPlugin");
  4. test("Test the Plugin Route", async t => {
  5. // Create a mock fastify application to test the plugin
  6. const fastify = Fastify()
  7. fastify.register(myPlugin)
  8. // Add an endpoint of your choice
  9. fastify.get("/", async (request, reply) => {
  10. return ({ message: request.helloRequest })
  11. })
  12. // Use fastify.inject to fake a HTTP Request
  13. const fastifyResponse = await fastify.inject({
  14. method: "GET",
  15. url: "/"
  16. })
  17. console.log('status code: ', fastifyResponse.statusCode)
  18. console.log('body: ', fastifyResponse.body)
  19. })

Learn more about fastify.inject(). Run the test file in your terminal node test/myFirstPlugin.test.js

  1. status code: 200
  2. body: {"message":"Hello World"}

Now we can replace our console.log calls with actual tests!

In your package.json change the “test” script to:

"test": "node --test --watch"

Create the test for the endpoint.

test/myFirstPlugin.test.js:

  1. const Fastify = require("fastify");
  2. const { test } = require("node:test");
  3. const myPlugin = require("../plugin/myFirstPlugin");
  4. test("Test the Plugin Route", async t => {
  5. // Specifies the number of test
  6. t.plan(2)
  7. const fastify = Fastify()
  8. fastify.register(myPlugin)
  9. fastify.get("/", async (request, reply) => {
  10. return ({ message: request.helloRequest })
  11. })
  12. const fastifyResponse = await fastify.inject({
  13. method: "GET",
  14. url: "/"
  15. })
  16. t.assert.strictEqual(fastifyResponse.statusCode, 200)
  17. t.assert.deepStrictEqual(JSON.parse(fastifyResponse.body), { message: "Hello World" })
  18. })

Finally, run npm test in the terminal and see your test results!

Test the .decorate() and .decorateRequest().

test/myFirstPlugin.test.js:

  1. const Fastify = require("fastify");
  2. const { test }= require("node:test");
  3. const myPlugin = require("../plugin/myFirstPlugin");
  4. test("Test the Plugin Route", async t => {
  5. t.plan(5)
  6. const fastify = Fastify()
  7. fastify.register(myPlugin)
  8. fastify.get("/", async (request, reply) => {
  9. // Testing the fastify decorators
  10. t.assert.ifError(request.helloRequest)
  11. t.assert.ok(request.helloRequest, "Hello World")
  12. t.assert.ok(fastify.helloInstance, "Hello Fastify Instance")
  13. return ({ message: request.helloRequest })
  14. })
  15. const fastifyResponse = await fastify.inject({
  16. method: "GET",
  17. url: "/"
  18. })
  19. t.assert.strictEqual(fastifyResponse.statusCode, 200)
  20. t.assert.deepStrictEqual(JSON.parse(fastifyResponse.body), { message: "Hello World" })
  21. })