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.
Code
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,supertestandexpressare 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
CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Systemd Unit File GeneratorGenerate hardened systemd .service unit files ([Unit], [Service], [Install]) with security sandboxing presets, restart policies, and resource limits.
FAQ
- Does this require external packages?
- Yes — `vitest`, `supertest` and `express`. Add them to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.