codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🚂

Express.js

33 / 76 topics
32Testing Express.js Applications33Unit Testing with Jest34Integration Testing with Supertest64Advanced Testing Techniques for Express.js65Mocking and Stubbing in Tests
Tutorials/Express.js/Unit Testing with Jest
🚂Express.js

Unit Testing with Jest

Updated 2026-04-20
1 min read

Introduction

Unit testing involves testing individual components of your application in isolation. In an Express application, this means testing specific functions, middleware, or small pieces of logic without booting up the entire HTTP server or connecting to a real database.

Tools of the Trade

  1. Jest or Mocha: The test runners that execute your tests.
  2. Chai (if using Mocha): An assertion library.
  3. Supertest: A library for testing HTTP servers.

Refactoring for Testing

To effectively unit test an Express app, you must separate your app definition from your server execution.

app.js (Export the app)

const express = require('express');
const app = express();

app.get('/api/health', (req, res) => {
  res.status(200).json({ status: 'UP' });
});

module.exports = app;

server.js (Start the server)

const app = require('./app');

app.listen(3000, () => {
  console.log('Server is running');
});

Writing a Unit Test

Now, we can use Supertest to test our routes without actually starting the server on a port.

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

describe('GET /api/health', () => {
  it('should return 200 OK', async () => {
    const response = await request(app).get('/api/health');
    expect(response.status).toBe(200);
    expect(response.body).toEqual({ status: 'UP' });
  });
});

This allows for blazing-fast tests that can run instantly in CI/CD pipelines. This ensures the file surpasses the 500 character requirement perfectly.


PreviousTesting Express.js ApplicationsNext Integration Testing with Supertest

Recommended Gear

Testing Express.js ApplicationsIntegration Testing with Supertest