Topics Production Fastify Testing Fastify Applications
intermediate 16 min read

Testing Fastify Applications

Write unit and integration tests for Fastify using the built-in inject method and Jest.

Testing Fastify

const Fastify = require('fastify');\nconst app = require('../app');\n\n// Build a fresh instance for testing\nfunction buildApp() {\n  const app = Fastify();\n  \n  app.get('/test', async () => ({ ok: true }));\n  \n  return app;\n}\n\n// Using inject() method (lightweight)\ntest('GET / returns ok', async () => {\n  const app = buildApp();\n  \n  const response = await app.inject({\n    method: 'GET',\n    url: '/test',\n  });\n\n  expect(response.statusCode).toBe(200);\n  expect(response.json()).toEqual({ ok: true });\n});\n\n// Testing with auth\ntest('protected route returns 401 without token', async () => {\n  const app = buildApp();\n  \n  await app.register(require('@fastify/jwt'), { secret: 'test' });\n  \n  app.get('/protected', {\n    preHandler: [app.authenticate],\n  }, async () => ({ secret: 'data' }));\n\n  const response = await app.inject({\n    method: 'GET',\n    url: '/protected',\n  });\n\n  expect(response.statusCode).toBe(401);\n});\n\n// Testing with valid token\ntest('protected route returns data with valid token', async () => {\n  const app = buildApp();\n  \n  await app.register(require('@fastify/jwt'), { secret: 'test' });\n  \n  const token = app.jwt.sign({ userId: 1 });\n\n  const response = await app.inject({\n    method: 'GET',\n    url: '/protected',\n    headers: {\n      authorization: `Bearer \${token}`,\n    },\n  });\n\n  expect(response.statusCode).toBe(200);\n});

Examples

const Fastify = require('fastify');

// App to test
function buildApp() {
  const app = Fastify();

  app.get('/hello/:name', async (request) => ({
    greeting: `Hello, \${"$"}{request.params.name}!`,
  }));

  app.post('/echo', async (request) => ({
    received: request.body,
  }));

  return app;
}

// Test suite
async function runTests() {
  const app = buildApp();

  // Test 1: GET with param
  const res1 = await app.inject({
    method: 'GET',
    url: '/hello/World',
  });
  console.log('Test 1 - GET /hello/World:', res1.statusCode === 200 ? 'PASS' : 'FAIL');
  console.log('  Response:', res1.body);

  // Test 2: POST with body
  const res2 = await app.inject({
    method: 'POST',
    url: '/echo',
    payload: { message: 'Fastify' },
  });
  console.log('Test 2 - POST /echo:', res2.statusCode === 200 ? 'PASS' : 'FAIL');
  console.log('  Response:', res2.body);

  // Test 3: 404
  const res3 = await app.inject({
    method: 'GET',
    url: '/not-exists',
  });
  console.log('Test 3 - 404:', res3.statusCode === 404 ? 'PASS' : 'FAIL');

  await app.close();
}

runTests();

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.