Testing and Deploying Express APIsLesson 6.2
How to test authenticated Express routes in Jest
JWT in tests, test token generation, Authorization header in supertest, beforeAll token setup, test user fixture, authenticated request helper, 401 testing
Testing Authenticated Routes
For authenticated routes, generate a test JWT in beforeAll and attach it to every request that needs it.
Testing with JWT tokens
const request = require('supertest');
const jwt = require('jsonwebtoken');
const app = require('../app');
const TEST_SECRET = process.env.JWT_SECRET || 'test_secret';
describe('Protected Routes', () => {
let token;
let adminToken;
beforeAll(() => {
token = jwt.sign({ userId: 1, role: 'user' }, TEST_SECRET, { expiresIn: '1h' });
adminToken = jwt.sign({ userId: 2, role: 'admin' }, TEST_SECRET, { expiresIn: '1h' });
});
it('GET /profile returns 401 without token', async () => {
const res = await request(app).get('/profile');
expect(res.statusCode).toBe(401);
});
it('GET /profile returns user data with valid token', async () => {
const res = await request(app)
.get('/profile')
.set('Authorization', `Bearer ${token}`);
expect(res.statusCode).toBe(200);
expect(res.body.userId).toBe(1);
});
it('GET /admin returns 403 for non-admin', async () => {
const res = await request(app)
.get('/admin')
.set('Authorization', `Bearer ${token}`);
expect(res.statusCode).toBe(403);
});
it('GET /admin returns 200 for admin', async () => {
const res = await request(app)
.get('/admin')
.set('Authorization', `Bearer ${adminToken}`);
expect(res.statusCode).toBe(200);
});
});Set JWT_SECRET in a .env.test file or Jest's testEnvironment config. Keep test tokens short-lived and use fixed payloads for predictable assertions.
