Registry / testing / node-mocks-http

node-mocks-http

JSON →
library1.17.2jsnpmunverified

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.

npm install node-mocks-http
INSTALL
IMPORT
SIG · NODE-MOCKS-HTTP
N
node-mocks-http
testingjavascriptv1.17.2
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

httpMocks
import httpMocks from 'node-mocks-http';
const httpMocks = require('node-mocks-http');
For modern Node.js projects using ES Modules (`"type": "module"` in `package.json` or `.mjs` files). CommonJS `require` is still supported but less idiomatic for new projects.
httpMocks
const httpMocks = require('node-mocks-http');
Standard CommonJS import pattern. This is shown in the README, indicating its continued support.
createRequest / createResponse
import httpMocks from 'node-mocks-http'; const request = httpMocks.createRequest();
import { createRequest } from 'node-mocks-http';
These methods are properties of the default `httpMocks` export, not named exports from the package root. Direct destructuring from the package path will fail.
NextApiRequest / NextApiResponse
import type { NextApiRequest, NextApiResponse } from 'next'; import httpMocks from 'node-mocks-http'; const mockRequest = httpMocks.createRequest<NextApiRequest>({});
import { NextApiRequest } from 'node-mocks-http';
Next.js specific types must be imported from the `next` package, not `node-mocks-http`. `node-mocks-http` uses these as generic type parameters for its mock objects.

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)}`); } });
Debug
Known issues
gotchaWhen using TypeScript, remember to install the necessary `@types` packages (e.g., `@types/express`, `@types/node`). Although `node-mocks-http` ships with its own types, these peer dependencies are crucial for correctly typing the underlying framework interfaces your code expects.
fix
Install peer dependencies: `npm install --save-dev @types/node @types/express` or `yarn add --dev @types/node @types/express`.
affects: >=1.0.0
gotchaThe mock `response` object's built-in event emitter is not fully functional and does not emit events by default. If your code under test relies on `response.on('event', ...)` for testing event handlers, you must provide your own event emitter instance to the mock response.
fix
Pass a functional event emitter in `createResponse` options: `httpMocks.createResponse({ eventEmitter: require('events').EventEmitter })`.
affects: >=1.0.0
gotchaWhen testing Next.js API routes or App Router handlers with TypeScript, ensure you import the specific `NextApiRequest`, `NextApiResponse`, `NextRequest`, or `NextResponse` types from the `next` package and use them as generics with `createRequest` and `createResponse`. By default, `node-mocks-http` mocks are Express-based.
fix
Specify the generic types: `httpMocks.createRequest<NextApiRequest>({...})` and `httpMocks.createResponse<NextApiResponse>()`. Remember to import `NextApiRequest` and `NextApiResponse` from `next`.
affects: >=1.14.0
gotchaNode.js ESM (ECMAScript Modules) support in testing frameworks and mocking libraries can be complex. While `node-mocks-http` supports ESM imports for itself, mocking dependencies within ESM test files might require specific configurations or alternative tools like `testdouble` for module-level mocking.
fix
If encountering issues with ESM and mocking, check your test runner's ESM configuration (e.g., `"type": "module"` in `package.json`). For advanced module-level mocking in ESM, consider libraries like `testdouble` or alternative test runners like `vitest` which have better ESM support.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: httpMocks.createRequest is not a function
Attempting to destructure `createRequest` or `createResponse` directly from the package, or using CommonJS `require` in an ESM context (or vice-versa) incorrectly.
fix
Ensure you import `httpMocks` as a default export (`import httpMocks from 'node-mocks-http';` for ESM or `const httpMocks = require('node-mocks-http');` for CJS) and then call its methods: `httpMocks.createRequest()`.
TS2345: Argument of type '{}' is not assignable to parameter of type 'Request'. Property 'body' is missing in type '{}' but required in type 'Request'.
TypeScript error due to `createRequest` or `createResponse` being used without specifying the correct generic type, causing the mock object to default to `http.IncomingMessage` or `http.ServerResponse` which might not match the specific framework types (e.g., Express `Request`).
fix
Add the correct generic type parameter to `createRequest` and `createResponse`, for example: `httpMocks.createRequest<express.Request>({...})` or `httpMocks.createResponse<express.Response>()`. Remember to import the `Request` and `Response` types from your framework (e.g., `import type { Request, Response } from 'express';`).
response._getJSONData is not a function
The `_getJSONData()` (and similar `_getData()`, `_getHeaders()` etc.) methods are non-standard helper methods added by `node-mocks-http` for testing purposes, which might be called before the response stream has ended or if the response content is not JSON.
fix
Ensure that your route handler has called a method like `response.send()` or `response.end()` to complete the response before attempting to retrieve data. Also, `_getJSONData()` specifically expects JSON content.
Upgrade
Version history
1.17.2latest on npm
Audit
Dependencies
@types/expressoptionalPeer dependency for TypeScript users testing Express.js applications, providing accurate type definitions for mock objects.
@types/nodeoptionalPeer dependency for TypeScript users, providing core Node.js type definitions, including those for http.IncomingMessage and http.ServerResponse.
Agent activity
4 hits · last 30 days
node
4
Resources