Testing With Vitest

Fast, Vite-Native, Familiar API

Testing With Vitest

Vitest is a great match for Fastify — ESM-friendly, watch mode, parallel by default, and a familiar describe/it/expect API.

4 min read Level 2/5 #fastify#testing#vitest
What you'll learn
  • Install vitest and configure scripts
  • Write describe/it/expect tests
  • Combine Vitest with app.inject

node:test is fine, but Vitest gives you a familiar describe/it/expect API, watch mode, and parallel execution out of the box — and it speaks ESM natively.

Install

npm i -D vitest

Add scripts to package.json:

{
  "scripts": {
    "test": "vitest run",
    "test:watch": "vitest"
  }
}

A buildApp Factory

Share an app factory across tests so every test gets a fresh, isolated instance.

// src/app.ts
import Fastify, { type FastifyInstance } from 'fastify';

export function buildApp(): FastifyInstance {
  const app = Fastify({ logger: false });
  app.get('/users', async () => []);
  return app;
}

describe / it / expect

// test/users.test.ts
import { describe, it, expect, afterEach } from 'vitest';
import { buildApp } from '../src/app.js';

describe('users', () => {
  const app = buildApp();
  afterEach(() => app.close());

  it('lists users', async () => {
    const res = await app.inject({ method: 'GET', url: '/users' });
    expect(res.statusCode).toBe(200);
    expect(res.json()).toEqual([]);
  });
});

Run npm test and you’ll get colored output, a coverage summary if enabled, and watch mode in under a second. Vitest plus app.inject is the sweet spot for most Fastify projects.

Monitoring & Health Checks →