Node HTTP Mocks

1.17.2 · active · verified Tue Apr 21

node-mocks-http is a testing utility for Node.js environments that provides mock implementations of `http.IncomingMessage` (request) and `http.ServerResponse` (response) objects. It is designed to facilitate unit testing of web server applications, particularly those built with frameworks like Express, Next.js, and Koa, by allowing developers to simulate HTTP requests and responses without needing to spin up a full HTTP server. The current stable version is 1.17.2, and the project shows a positive release cadence with recent updates. Key differentiators include its focus on low-level `http` object mocking, bundled TypeScript typings, and explicit support for framework-specific request/response types (e.g., Express, Next.js API routes, Next.js App Router). This makes it suitable for isolating and testing individual route handlers or middleware functions efficiently.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to unit test an Express-style route handler using `node-mocks-http` with TypeScript. It shows how to create mock request and response objects, pass them to a handler, and assert on the mocked response's state and data.

import httpMocks from 'node-mocks-http';
import type { Request, Response } from 'express';

// Imagine this is your Express route handler
const routeHandler = function(request: Request, response: Response) {
    const { id } = request.params;
    if (id === '42') {
        response.statusCode = 200;
        response.setHeader('Content-Type', 'application/json');
        response.send(JSON.stringify({
            name: 'Bob Dog',
            age: 42,
            email: 'bob@dog.com'
        }));
    } else {
        response.statusCode = 404;
        response.send('User not found');
    }
};

describe('routeHandler', () => {
    it('should return user data for a valid ID', () => {
        const request = httpMocks.createRequest<Request>({
            method: 'GET',
            url: '/user/42',
            params: {
                id: '42'
            }
        });

        const response = httpMocks.createResponse<Response>();

        routeHandler(request, response);

        // Assertions using common test patterns (e.g., Jest/Chai style)
        expect(response.statusCode).toBe(200);
        expect(response._isEndCalled()).toBe(true);
        expect(response._isJSON()).toBe(true);
        expect(response._getData()).toEqual(JSON.stringify({
            name: 'Bob Dog',
            age: 42,
            email: 'bob@dog.com'
        }));
    });

    it('should return 404 for an invalid ID', () => {
        const request = httpMocks.createRequest<Request>({
            method: 'GET',
            url: '/user/99',
            params: {
                id: '99'
            }
        });

        const response = httpMocks.createResponse<Response>();

        routeHandler(request, response);

        expect(response.statusCode).toBe(404);
        expect(response._isEndCalled()).toBe(true);
        expect(response._getData()).toEqual('User not found');
    });
});

// Minimal Jest-like environment for standalone execution
function describe(name: string, fn: () => void) {
    console.log(`
${name}`);
    fn();
}
function it(name: string, fn: () => void) {
    process.stdout.write(`  - ${name}...`);
    try {
        fn();
        console.log(' ✅');
    } catch (e: any) {
        console.log(' ❌');
        console.error(e.message);
    }
}
const expect = (value: any) => ({
    toBe: (expected: any) => {
        if (value !== expected) throw new Error(`Expected ${value} to be ${expected}`);
    },
    toEqual: (expected: any) => {
        if (JSON.stringify(value) !== JSON.stringify(expected)) throw new Error(`Expected ${JSON.stringify(value)} to equal ${JSON.stringify(expected)}`);
    }
});

view raw JSON →