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

javascriptsnippet
43 lines
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);
  });
});

How the snippet works

Vitest Unit Test for API Handlers keeps everything in the function buildApp.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Reach for vitest and what you get is describe, it, expect, beforeAll — that is the whole API contact area.

What to watch for

  • Plan for an install step: vitest, supertest and express are a real dependency, resolved by the package manager.

Using it

Entry signature: function buildApp()

Key statements

return res.status(201).json({ received: true, length: comment.length });
return res.status(400).json({ error: 'rating must be 1-5' });
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);
});

Interactive Tools for This Topic

FAQ

Does this require external packages?
Yes — `vitest`, `supertest` and `express`. Add them to your project before running the snippet.