Write User API Integration Tests

Create tests/users.test.js.

Supertest accepts an Express application and allows you to send HTTP requests without manually starting the application on a fixed port.

We will test:

  1. Health endpoint.
  2. User registration.
  3. Login.
  4. Invalid login.
  5. Protected endpoint access.

For this example, assume the test setup connects to the isolated test database and clears test records between test runs.

tests/users.test.js
import request from 'supertest';
import mongoose from 'mongoose';
import app from '../src/app.js';
import { User } from '../src/models/user.model.js';
import { connectDatabase } from '../src/config/database.js';

beforeAll(async () => {
  process.env.MONGODB_URI = process.env.MONGODB_TEST_URI;
  await connectDatabase();
});

afterEach(async () => {
  await User.deleteMany({});
});

afterAll(async () => {
  await mongoose.disconnect();
});

describe('Authentication API', () => {
  test('should register a new user', async () => {
    const response = await request(app)
      .post('/api/v1/auth/register')
      .send({
        name: 'John Doe',
        email: 'john@example.com',
        password: 'SecurePassword123!'
      });

    expect(response.status).toBe(201);
    expect(response.body.success).toBe(true);
    expect(response.body.data.password).toBeUndefined();
  });

  test('should reject invalid login credentials', async () => {
    const response = await request(app)
      .post('/api/v1/auth/login')
      .send({
        email: 'unknown@example.com',
        password: 'wrong-password'
      });

    expect(response.status).toBe(401);
  });
});

Creates integration tests using Supertest. The example assumes the test environment is configured before Jest imports the application and that the authentication routes are registered.

Key Takeaways
  • Supertest can test Express applications directly.

  • Use an isolated database for integration tests.

  • Verify both successful and unsuccessful API requests.