Test authentication middleware
Test an Express auth middleware by calling it directly with fake req, res and next objects, covering a missing, a bad and a valid token.
Middleware is a function of (req, res, next), so you can call it without a server and see which branch it takes.
import { test, expect, vi } from 'vitest';
function requireToken(req, res, next) {
const header = req.headers.authorization ?? '';
if (!header.startsWith('Bearer ')) return res.status(401).json({ error: 'missing token' });
if (header.slice(7) !== 'secret') return res.status(403).json({ error: 'bad token' });
next();
}
function fakeRes() {
const res = {};
res.status = vi.fn(() => res);
res.json = vi.fn(() => res);
return res;
}
test('rejects a missing token', () => {
const res = fakeRes();
const next = vi.fn();
requireToken({ headers: {} }, res, next);
expect(res.status).toHaveBeenCalledWith(401);
expect(next).not.toHaveBeenCalled();
});
test('rejects a wrong token', () => {
const res = fakeRes();
requireToken({ headers: { authorization: 'Bearer nope' } }, res, vi.fn());
expect(res.status).toHaveBeenCalledWith(403);
});
test('passes a valid token', () => {
const next = vi.fn();
requireToken({ headers: { authorization: 'Bearer secret' } }, fakeRes(), next);
expect(next).toHaveBeenCalledOnce();
}); ✓ auth.test.js (3 tests)
Test Files 1 passed (1)
Tests 3 passed (3)The fake res returns itself from each method, which makes chained calls such as res.status(401).json(...) work. The contract of next is in the Express middleware guide.
Compare the real secret with crypto.timingSafeEqual in production code. This test only covers the branching.
Test with a header that has the wrong scheme, such as Basic instead of Bearer, because a prefix check is easy to write incorrectly and the failure is a security hole.