Mock HTTP Server for Testing

1.4.5 · active · verified Sun Apr 19

mock-http-server is a Node.js library designed to create controllable HTTP and HTTPS server mocks, primarily for use in functional and integration tests. It allows developers to define expected incoming requests by method and path, and then configure custom responses including status codes, headers, and body content. The current stable version is 1.4.5, with recent minor releases adding features like request history clearing, improved body parsing for various content types (text/plain, urlencoded), and specific port retrieval methods. Its release cadence appears to be feature-driven, with new functionalities and minor fixes arriving periodically. Key differentiators include its explicit control over request matching and response generation, the ability to inspect received requests for assertions, and support for both HTTP and HTTPS protocols. It aims to provide a reliable and isolated testing environment without actual network calls to external services, allowing for consistent and fast test execution.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up, start, and stop a mock HTTP server, define a request handler, make a request against it, and assert on the response and recorded requests within a test suite (e.g., Jest or Mocha).

import ServerMock from 'mock-http-server';
import util from 'node:util';

describe('Test with Mock HTTP Server', function() {

    // Run an HTTP server on localhost:9000
    var server = new ServerMock({ host: "localhost", port: 9000 });

    const startServer = util.promisify(server.start).bind(server);
    const stopServer = util.promisify(server.stop).bind(server);

    beforeEach(async () => {
        await startServer();
    });

    afterEach(async () => {
        server.resetHandlers(); // Clear handlers between tests
        server.clearRequests(); // Clear request history
        await stopServer();
    });

    it('should mock a GET request to /resource', async () => {
        server.on({
            method: 'GET',
            path: '/resource',
            reply: {
                status:  200,
                headers: { "content-type": "application/json" },
                body:    JSON.stringify({ message: "hello world from mock" })
            }
        });

        // Simulate an HTTP request
        const response = await fetch('http://localhost:9000/resource');
        const data = await response.json();

        expect(response.status).toBe(200);
        expect(data).toEqual({ message: "hello world from mock" });

        // Verify the request was received
        const requests = server.requests({
            method: 'GET',
            path: '/resource'
        });
        expect(requests.length).toBe(1);
    });
});

view raw JSON →