mock-http is a Node.js library that provides robust mock implementations of the core `http.IncomingMessage` and `http.ServerResponse` classes. This enables developers to conduct isolated unit testing of HTTP server-side logic, such as Connect, Express, or Koa middleware, without the overhead of creating a real HTTP server or managing network sockets. The library ensures full API compatibility with Node.js's native `http` module interfaces, allowing middleware to be tested in an environment closely mirroring production. Currently stable at version 1.1.1, its release cadence is generally aligned with Node.js LTS cycles for compatibility updates, rather than frequent feature additions, indicating a mature and maintenance-focused project. Its key differentiator is the faithful emulation of the standard HTTP objects, providing a reliable and predictable testing surface for complex server-side components.
npm install mock-httpVerified import paths — ran on the pinned version, not inferred.
Demonstrates mocking HTTP requests and responses to test a simple Connect-style middleware function, verifying headers, body, status, and middleware chaining behavior.
Design tests to focus on HTTP protocol-level interactions (headers, body, status codes) rather than direct socket manipulation or properties that depend on a live network connection.
For `mock.Response`, use the `onEnd` callback to trigger test assertions. For `mock.Request`, ensure all 'data' and 'end' event listeners have processed their input before concluding the test.
Prefer using public methods like `res.statusCode`, `res.getHeader()`, and `res.hasEnded()` where possible. If `_internal` is necessary, be prepared for potential adjustments during major version upgrades.
Ensure you are importing the library correctly using named imports (`import { Request, Response } from 'mock-http';`) or a namespace import (`import * as mock from 'mock-http';`) and then referencing `mock.Request` or `mock.Response`.Verify the middleware logic correctly handles all execution paths, ensuring `res.end()` or `next()` is called under expected test conditions, especially for asynchronous operations.
Review the middleware logic to prevent multiple calls to `res.end()` or any write operations to the response stream after the response has been finalized.
No dependency data recorded yet.