Vitest Unit Test for API Handlers

Write Vitest unit tests for an Express app with Supertest, covering success paths, validation errors, and HTTP status assertions per case.

JavascriptNodeCli Tooling

Code

snippet
import { describe, it, expect, beforeAll } from 'vitest';
import request from 'supertest';
import express from 'express';

function buildApp() {
  const app = express();
  app.use(express.json());

  app.post('/feedback', (req, res) => {
    const { rating, comment } = req.body ?? {};
    if (!Number.isInteger(rating) || rating < 1 || rating > 5) {
      return res.status(400).json({ error: 'rating must be 1-5' });
    }
    return res.status(201).json({ received: true, length: comment.length });
  });
  return app;
}

let app;
beforeAll(() => { app = buildApp(); });

describe('POST /feedback', () => {
  it('accepts a valid rating and returns 201', async () => {
    const res = await request(app)
      .post('/feedback')
      .send({ rating: 5, comment: 'great' });
    expect(res.status).toBe(201);
    expect(res.body.received).toBe(true);
  });

  it('rejects out-of-range rating with 400', async () => {
    const res = await request(app)
      .post('/feedback')
      .send({ rating: 9, comment: 'x' });
    expect(res.status).toBe(400);
    expect(res.body.error).toMatch(/rating/);
  });

  it('rejects missing body with 400', async () => {
    const res = await request(app).post('/feedback').send({});
    expect(res.status).toBe(400);
  });
});