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
muslnode 18–226 runs
build_error
glibcnode 18–226 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)}`);
}
});
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.
fixEnsure 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`).
fixAdd 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.
fixEnsure 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.
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.