0
0
Expressframework~5 mins

Testing authentication flows in Express

Choose your learning style9 modes available
Introduction

Testing authentication flows helps ensure users can safely log in and access protected parts of your app. It catches mistakes before real users do.

When you add a login or signup feature to your Express app.
When you want to check that only logged-in users can see certain pages.
When you update your authentication logic and want to confirm it still works.
When you want to automate tests to save time and avoid manual checking.
Syntax
Express
const request = require('supertest');
const app = require('./app');

describe('Authentication flow', () => {
  it('should log in with valid credentials', async () => {
    const response = await request(app)
      .post('/login')
      .send({ username: 'user', password: 'pass' });
    expect(response.statusCode).toBe(200);
    expect(response.body).toHaveProperty('token');
  });
});

Use supertest to simulate HTTP requests to your Express app.

Write tests inside describe and it blocks for clarity.

Examples
Sends a POST request to the login route with username and password.
Express
await request(app).post('/login').send({ username: 'user', password: 'pass' });
Checks that the response status code is 401 Unauthorized for wrong credentials.
Express
expect(response.statusCode).toBe(401);
Verifies the response includes a token property after successful login.
Express
expect(response.body).toHaveProperty('token');
Sample Program

This example shows a simple Express app with a login route. It uses supertest to test logging in with correct and incorrect passwords.

Express
const express = require('express');
const bodyParser = require('body-parser');
const request = require('supertest');

const app = express();
app.use(bodyParser.json());

// Simple user data
const users = [{ username: 'user', password: 'pass' }];

// Login route
app.post('/login', (req, res) => {
  const { username, password } = req.body;
  const user = users.find(u => u.username === username && u.password === password);
  if (user) {
    return res.status(200).json({ token: 'fake-jwt-token' });
  }
  return res.status(401).json({ error: 'Invalid credentials' });
});

// Test suite
describe('Authentication flow', () => {
  it('logs in with correct credentials', async () => {
    const response = await request(app)
      .post('/login')
      .send({ username: 'user', password: 'pass' });
    expect(response.statusCode).toBe(200);
    expect(response.body).toHaveProperty('token');
  });

  it('fails login with wrong password', async () => {
    const response = await request(app)
      .post('/login')
      .send({ username: 'user', password: 'wrong' });
    expect(response.statusCode).toBe(401);
    expect(response.body).toHaveProperty('error', 'Invalid credentials');
  });
});
OutputSuccess
Important Notes

Use descriptive test names to understand what each test checks.

Keep test data simple and clear for easy debugging.

Run tests often to catch errors early.

Summary

Testing authentication ensures your login works as expected.

Use supertest to simulate requests to your Express app.

Write tests for both success and failure cases.