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

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

Mocking and Stubbing in Tests

Updated 2026-05-15
10 min read

Mocking and Stubbing in Tests

Introduction

In the world of software development, testing is a crucial part of ensuring that our applications work as expected. When it comes to testing Express.js applications, we often need to isolate specific parts of our code to ensure they behave correctly under various conditions. This is where mocking and stubbing come into play.

Mocking involves creating objects that simulate the behavior of real objects in controlled ways. Stubbing, on the other hand, is a form of mocking where you replace certain methods or properties with predefined behaviors. Both techniques help improve test isolation by allowing us to control external dependencies and focus on testing the functionality we care about.

Concept

When writing tests for Express.js applications, we might encounter scenarios where we need to isolate our routes from database interactions, third-party APIs, or other complex services. Mocking and stubbing allow us to replace these dependencies with simpler, controlled versions that mimic their behavior without introducing real-world complexity.

For example, if you have a route that fetches data from a database, you can mock the database call so that it returns predefined results instead of hitting an actual database. This way, your tests can run quickly and reliably without relying on external systems.

Examples

Let's walk through some practical examples to illustrate how mocking and stubbing work in Express.js applications.

Example 1: Mocking a Database Call

Suppose we have an Express route that fetches user data from a database:

// src/routes/users.js
const express = require('express');
const router = express.Router();
const db = require('../db');

router.get('/users', async (req, res) => {
  try {
    const users = await db.getAllUsers();
    res.json(users);
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' });
  }
});

module.exports = router;

To test this route, we can mock the getAllUsers method from our database module. We'll use the jest testing framework along with jest-mock for mocking.

// src/routes/__tests__/users.test.js
const request = require('supertest');
const app = require('../../app'); // Assuming your Express app is exported from here

jest.mock('../db', () => ({
  getAllUsers: jest.fn(),
}));

describe('GET /users', () => {
  it('should return a list of users', async () => {
    const mockUsers = [{ id: 1, name: 'John Doe' }, { id: 2, name: 'Jane Smith' }];
    db.getAllUsers.mockResolvedValue(mockUsers);

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

    expect(response.status).toBe(200);
    expect(response.body).toEqual(mockUsers);
  });

  it('should handle database errors', async () => {
    const mockError = new Error('Database connection failed');
    db.getAllUsers.mockRejectedValue(mockError);

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

    expect(response.status).toBe(500);
    expect(response.body).toEqual({ error: 'Internal Server Error' });
  });
});

In this example, we use jest.mock to replace the actual database module with a mock version. We then define the behavior of the getAllUsers method using mockResolvedValue and mockRejectedValue. This allows us to test our route logic without making real database calls.

Example 2: Stubbing an External API Call

Let's consider another scenario where we have a route that fetches data from an external API:

// src/routes/weather.js
const express = require('express');
const router = express.Router();
const axios = require('axios');

router.get('/weather', async (req, res) => {
  try {
    const response = await axios.get('https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London');
    res.json(response.data);
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' });
  }
});

module.exports = router;

To test this route, we can stub the axios.get method to return predefined weather data.

// src/routes/__tests__/weather.test.js
const request = require('supertest');
const app = require('../../app'); // Assuming your Express app is exported from here

jest.mock('axios');

describe('GET /weather', () => {
  it('should return current weather data', async () => {
    const mockWeatherData = { location: { name: 'London' }, current: { temp_c: 15 } };
    axios.get.mockResolvedValue({ data: mockWeatherData });

    const response = await request(app).get('/weather');

    expect(response.status).toBe(200);
    expect(response.body).toEqual(mockWeatherData);
  });

  it('should handle API errors', async () => {
    const mockError = new Error('API Request Failed');
    axios.get.mockRejectedValue(mockError);

    const response = await request(app).get('/weather');

    expect(response.status).toBe(500);
    expect(response.body).toEqual({ error: 'Internal Server Error' });
  });
});

Here, we use jest.mock to replace the axios module with a mock version. We then define the behavior of the axios.get method using mockResolvedValue and mockRejectedValue. This allows us to test our route logic without making real API calls.

What's Next?

In this tutorial, we explored how to use mocking and stubbing techniques to improve test isolation in Express.js applications. By controlling external dependencies, we can write more reliable and efficient tests that focus on the functionality we care about.

Next, you might want to explore performance benchmarking for Express.js applications. Understanding how your application performs under different loads is crucial for optimizing its efficiency and scalability. Stay tuned for more tutorials on this topic!


PreviousAdvanced Testing Techniques for Express.jsNext Performance Benchmarking for Express.js Applications

Recommended Gear

Advanced Testing Techniques for Express.jsPerformance Benchmarking for Express.js Applications