Skip to content
jshacks.dev
Testing

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.

2 min read
Summarize in AI

Middleware is a function of (req, res, next), so you can call it without a server and see which branch it takes.

auth.test.jsJavaScript
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();
});
Text
 ✓ 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.

Also inSecurity
Taggedvitest
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.