Learn Express.js · 13/14

Testing Express Applications

9 min read

Before you write your next line of code, think about how you plan to verify it actually works.

Usually, this involves saving your file, waiting for Nodemon to restart, opening Postman (or your browser), making a request, checking the response, tweaking the code, and repeating the process. Now imagine your application has 50 different routes, with different user roles, edge cases, and database states. Clicking through Postman manually 500 times is soul-crushing, prone to human error, and frankly, a terrible way to spend your Friday afternoon.

Software testing is the practice of writing code that automates the verification of your actual application code. When tests are automated, you can confidently add new features without secretly dreading that you just broke an older, unrelated feature.

Let's learn how the industry tests Express applications efficiently.


1. The Testing Pyramid: Unit vs Integration Tests

The Problem

If you try to test your entire application by automating a web browser that clicks through the UI, logs in, and adds an item to a cart, your tests will be incredibly slow and break frequently whenever a frontend developer changes a button's color. On the other hand, if you only test tiny mathematical functions, you will have no idea if your API routes actually work together.

The Solution: The Testing Pyramid

The testing pyramid is an industry-standard strategy that dictates how many tests of each type you should write to maintain a healthy, fast, and reliable test suite.

1. Unit Tests (The Base)

  • Definition: Unit testing is the practice of isolating a single, small piece of code (like a function or a class) and verifying its behavior independently from the rest of the application.
  • Use Case: Testing a utility function that formats dates or calculates taxes.
  • In Express: You usually write unit tests for your standalone business logic or utility helpers.

2. Integration Tests (The Middle)

  • Definition: Integration testing verifies that multiple units of code or components work together correctly.
  • Use Case: Testing an Express API route.
  • In Express: This is your highest Return on Investment (ROI). An integration test will hit an endpoint (like GET /users), run the controller, interact with the database, and return the HTTP response. It checks the integration between the router, the controller, and the database.

3. End-to-End (E2E) Tests (The Tip)

  • Definition: E2E testing evaluates the entire application flow from start to finish, exactly as a real user would interact with it.
  • In Express: These are rare in pure backend repositories. They usually involve tools like Playwright or Cypress running a real browser against a fully deployed frontend and backend.

🏭 Simulation: Imagine a car factory.

  • Unit Test: You connect a battery to a single spark plug on a workbench to ensure it sparks.
  • Integration Test: You attach the engine to the transmission and turn the key to see if the axle spins.
  • E2E Test: You take the fully built car and drive it on the highway.

Industry Standard: In the modern Node.js ecosystem, backend engineers focus heavily on Integration Tests. Pure unit tests are reserved for complex standalone algorithms, while integration tests provide the actual confidence that your API endpoints work as documented.


2. Setting up the Testing Environment with Jest and Supertest

The Problem

Node.js applications typically run on a specific network port (like 3000). If you write an automated script to test your server, you would need to start the server, wait for it to bind to port 3000, send network requests, and then gracefully shut it down. If a test crashes, the server stays running, leaving port 3000 stuck. If you run tests in parallel, they fight over the port.

The Solution: Jest + Supertest

  • Jest: A JavaScript testing framework developed by Meta. It provides the test runner, the assertion library (the code that says expect(A).toEqual(B)), and mocking capabilities.
  • Supertest: A library designed specifically for testing Node.js HTTP servers. It allows you to send virtual HTTP requests directly to your Express app without ever binding to a real network port.

Installation & Boilerplate

Get the latest versions installed as development dependencies:

bash
npm install --save-dev jest supertest

Update your package.json to tell Node to use Jest when you run tests:

json
{
  "scripts": {
    "start": "node server.js",
    "test": "jest"
  }
}

The Golden Industry Rule: Separate app.js from server.js

To use Supertest effectively, you must separate your Express application definition from the code that tells it to listen on a port. This is the #1 mistake developers make when testing Express.

app.js (The Setup)
This file configures Express, attaches the routes, and exports the app. It does not listen to a port.

javascript
// app.js
const express = require('express');
const app = express();

app.use(express.json());

app.get('/api/health', (req, res) => {
  res.status(200).json({ status: 'OK', message: 'Server is healthy' });
});

// We export the app, we do NOT call app.listen()
module.exports = app;

server.js (The Entry Point)
This file is what you run in production. It imports the app and binds it to a port.

javascript
// server.js
const app = require('./app');
const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`🚀 Server flying on port ${PORT}`);
});

Under the hood: When you pass the app object to Supertest, Supertest feeds it directly to Node's internal http.createServer(). It routes requests to your Express middleware in memory, bypassing the network stack entirely. No port conflicts, lightning-fast execution.


3. Writing Integration Tests for API Endpoints

The Problem

You need to automatically verify that your /api/health endpoint returns a 200 OK status code and the exact JSON structure { status: 'OK', message: 'Server is healthy' }.

The Solution

We will write a Jest test file using Supertest to make a virtual GET request and assert the results. By convention, Jest looks for any files ending in .test.js or .spec.js.

app.test.js

javascript
const request = require('supertest');
const app = require('./app'); // Import the Express app (not the server)

// 'describe' groups related tests together
describe('Healthcheck API Endpoints', () => {
  
  // 'it' defines a single test case
  it('should return 200 and a healthy status message on GET /api/health', async () => {
    
    // 1. Arrange & Act: Make the virtual request
    const response = await request(app).get('/api/health');
    
    // 2. Assert: Check the HTTP status code
    expect(response.statusCode).toBe(200);
    
    // 3. Assert: Check the JSON body payload
    expect(response.body).toEqual({
      status: 'OK',
      message: 'Server is healthy'
    });
    
  });

  it('should return 404 for an unknown route', async () => {
    const response = await request(app).get('/api/does-not-exist');
    expect(response.statusCode).toBe(404);
  });

});

Running the Test

Run npm test in your terminal. You will see Jest's beautiful green checkmarks validating your code.

Sending Data (POST Requests)

Integration testing truly shines when you test data mutation. Here is how you test a POST request with Supertest:

javascript
it('should create a new user', async () => {
  const newUser = { name: 'Alice', email: '[email protected]' };

  const response = await request(app)
    .post('/api/users')
    .send(newUser) // Supertest automatically sets the Content-Type to application/json
    .set('Authorization', 'Bearer fake-token'); // How to set headers

  expect(response.statusCode).toBe(201);
  expect(response.body).toHaveProperty('id'); // We expect the DB to have generated an ID
  expect(response.body.name).toBe('Alice');
});

4. Mocking Databases and External Services for Isolated Tests

The Problem

Imagine your Express endpoint POST /api/checkout calls the Stripe API to charge a credit card. If you run your test suite automatically every time you push code (Continuous Integration), you will be hitting the real Stripe API hundreds of times a day. You might hit rate limits, or worse, accidentally charge real money.

Similarly, relying on a real production-like database during testing can lead to "flaky tests"—tests that fail randomly because a previous test left leftover data in the database.

The Solution: Mocking

Mocking is the process of replacing a real external system, function, or module with a fake, controllable version during testing.

In the industry, the standard practice is:

  1. For Databases: Spin up an isolated test database (often in memory, or a dedicated Docker container) that gets wiped clean before every test run.
  2. For External APIs (Stripe, Email providers, SMS): Always mock them. Never hit external third-party APIs during automated testing.

Mocking a 3rd Party Service with Jest

Let's look at how to fake an external module using jest.mock().

Suppose you have an email service:

javascript
// emailService.js
const sendEmail = async (to, subject) => {
  // Imagine this connects to SendGrid or AWS SES
  console.log(`Sending real email to ${to}...`);
  return true;
};

module.exports = { sendEmail };

And your Express route uses it:

javascript
// app.js
const express = require('express');
const { sendEmail } = require('./emailService');
const app = express();
app.use(express.json());

app.post('/api/register', async (req, res) => {
  const { email } = req.body;
  // Business logic here...
  
  // Call external service
  await sendEmail(email, 'Welcome to our App!');
  
  res.status(201).json({ message: 'User registered' });
});

module.exports = app;

If we test this route normally, it will attempt to send a real email. We prevent this by mocking the module in our test file.

app.test.js

javascript
const request = require('supertest');
const app = require('./app');
const emailService = require('./emailService');

// Tell Jest to replace the real emailService.js with a fake version
jest.mock('./emailService');

describe('POST /api/register', () => {
  
  // Clear mock history before each test to ensure tests don't pollute each other
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('should register user and trigger a welcome email', async () => {
    // 1. Instruct the fake function on how to behave
    emailService.sendEmail.mockResolvedValue(true);

    // 2. Act
    const response = await request(app)
      .post('/api/register')
      .send({ email: '[email protected]' });

    // 3. Assert the HTTP response
    expect(response.statusCode).toBe(201);

    // 4. Assert that our mock was actually called by the Express controller!
    expect(emailService.sendEmail).toHaveBeenCalledTimes(1);
    expect(emailService.sendEmail).toHaveBeenCalledWith(
      '[email protected]', 
      'Welcome to our App!'
    );
  });
});

By using jest.mock(), Jest hijacked the require('./emailService') call inside your Express controller and replaced it with a spy. This allows you to verify that the email logic was triggered, without actually dispatching a real email across the internet.

Welcome to the peace of mind that comes with robust testing!


Reference Links & Further Reading

Challenge

Challenge: Write Integration Tests for an Express API

Your task is to write a complete integration test suite for a small Express application using Jest and Supertest. The application has two API endpoints for managing users and interacts with a database and a notification service.

The core of this challenge is to test the application's logic without making real database calls or sending actual notifications. You must use Jest's mocking capabilities to isolate the application for testing.

Application Files (Provided in the initial code):

  • app.js: Defines the Express application and its routes. It correctly exports the app instance without starting the server.
  • services/database.js: A module that simulates database interactions.
  • services/notification.js: A module that simulates sending notifications.

Your Tasks:

  1. Set up Mocks: At the top of your app.test.js file, use jest.mock() to mock both the ./services/database.js and ./services/notification.js modules.

  2. Test the GET /api/users/:id Endpoint:

    • Write a test case for a successful request. Mock the findUserById function to return a user object (e.g., { id: 1, name: 'John Doe', email: '[email protected]' }). Assert that the response status code is 200 and the response body matches the user object.
    • Write a test case for a user not found scenario. Mock the findUserById function to return null. Assert that the response status code is 404.
  3. Test the POST /api/users Endpoint:

    • Write a test case for a successful user creation. Mock the createUser function to return the newly created user. Mock the sendWelcomeEmail function so it doesn't throw an error.
    • Assert that the response status code is 201 and the response body contains the created user's data.
    • Crucially, assert that the mocked sendWelcomeEmail function was called exactly once and was called with the correct email address from the user data you sent in the request.

Expected result

Your final app.test.js file should contain a complete Jest test suite that uses Supertest to make requests and Jest to mock dependencies and make assertions. The structure should be similar to the following:

javascript
// app.test.js
const request = require('supertest');
const app = require('./app');
const database = require('./services/database');
const notification = require('./services/notification');

// Mock the entire modules
jest.mock('./services/database.js');
jest.mock('./services/notification.js');

describe('User API', () => {
  afterEach(() => {
    jest.clearAllMocks(); // Clear mocks between tests
  });

  describe('GET /api/users/:id', () => {
    it('should return a user if found', async () => {
      const mockUser = { id: '1', name: 'John Doe', email: '[email protected]' };
      database.findUserById.mockResolvedValue(mockUser);

      const response = await request(app).get('/api/users/1');

      expect(response.statusCode).toBe(200);
      expect(response.body).toEqual(mockUser);
    });

    it('should return 404 if user is not found', async () => {
      database.findUserById.mockResolvedValue(null);

      const response = await request(app).get('/api/users/999');

      expect(response.statusCode).toBe(404);
    });
  });

  describe('POST /api/users', () => {
    it('should create a new user and send a welcome email', async () => {
      const newUserPayload = { name: 'Jane Doe', email: '[email protected]' };
      const createdUser = { id: '2', ...newUserPayload };

      database.createUser.mockResolvedValue(createdUser);
      notification.sendWelcomeEmail.mockResolvedValue(); // Mock success

      const response = await request(app)
        .post('/api/users')
        .send(newUserPayload);

      expect(response.statusCode).toBe(201);
      expect(response.body).toEqual(createdUser);

      // Verify that the notification service was called correctly
      expect(notification.sendWelcomeEmail).toHaveBeenCalledTimes(1);
      expect(notification.sendWelcomeEmail).toHaveBeenCalledWith('[email protected]');
    });
  });
});
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.