Mock HTTP objects for testing Express, Next.js, and Koa routing functions
npx @tessl/cli install tessl/npm-node-mocks-http@1.17.0node-mocks-http provides comprehensive mock implementations of Node.js HTTP request and response objects specifically designed for testing web server applications built with Express, Next.js, and Koa frameworks. It offers full-featured mock objects that simulate real HTTP requests and responses, including support for headers, cookies, parameters, query strings, request bodies, and all standard HTTP methods.
npm install node-mocks-http --save-devconst httpMocks = require('node-mocks-http');For ESM:
import httpMocks from 'node-mocks-http';TypeScript:
import * as httpMocks from 'node-mocks-http';
import { createRequest, createResponse, createMocks } from 'node-mocks-http';const httpMocks = require('node-mocks-http');
// Create individual mocks
const request = httpMocks.createRequest({
method: 'GET',
url: '/user/42',
params: { id: 42 },
headers: { 'Content-Type': 'application/json' }
});
const response = httpMocks.createResponse();
// Or create linked request/response pair
const { req, res } = httpMocks.createMocks({
method: 'POST',
url: '/api/users',
body: { name: 'John', email: 'john@example.com' }
});
// Use in your tests
yourRouteHandler(req, res);
// Verify results
console.log(res.statusCode); // 200
console.log(res._getData()); // Response data
console.log(res._isJSON()); // true if JSON responsenode-mocks-http is built around several key components:
_ for verifying mock behaviorComplete HTTP request object simulation with all standard properties and methods. Perfect for testing route handlers, middleware, and request processing logic.
function createRequest<T extends RequestType = Request>(options?: RequestOptions): MockRequest<T>;
interface RequestOptions {
method?: RequestMethod;
url?: string;
originalUrl?: string;
baseUrl?: string;
path?: string;
params?: Params;
session?: Session;
cookies?: Cookies;
signedCookies?: Cookies;
headers?: Headers;
body?: Body;
query?: Query;
files?: Files;
ip?: string;
[key: string]: any;
}Full HTTP response object simulation with status codes, headers, cookies, and all response methods. Includes introspection methods for test verification.
function createResponse<T extends ResponseType = Response>(options?: ResponseOptions): MockResponse<T>;
interface ResponseOptions {
eventEmitter?: any;
writableStream?: any;
req?: any;
locals?: any;
}Convenient functions for creating individual mocks or linked request/response pairs that can interact with each other.
function createMocks<T1 extends RequestType = Request, T2 extends ResponseType = Response>(
reqOptions?: RequestOptions,
resOptions?: ResponseOptions
): Mocks<T1, T2>;
interface Mocks<T1 extends RequestType, T2 extends ResponseType> {
req: MockRequest<T1>;
res: MockResponse<T2>;
}Enhanced mocks with Express-specific functionality including application mocking, Express request/response extensions, and routing utilities.
const express = httpMocks.express;
function createApplication(): ExpressApplication;type RequestMethod = 'CONNECT' | 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'POST' | 'PUT' | 'TRACE';
type RequestType = IncomingMessage | globalThis.Request;
type ResponseType = OutgoingMessage | globalThis.Response;
interface Params {
[key: string]: any;
}
interface Session {
[key: string]: any;
}
interface Cookies {
[key: string]: string;
}
interface Headers {
// Standard HTTP headers
accept?: string;
'accept-language'?: string;
'accept-patch'?: string;
'accept-ranges'?: string;
'access-control-allow-credentials'?: string;
'access-control-allow-headers'?: string;
'access-control-allow-methods'?: string;
'access-control-allow-origin'?: string;
'access-control-expose-headers'?: string;
'access-control-max-age'?: string;
age?: string;
allow?: string;
'alt-svc'?: string;
authorization?: string;
'cache-control'?: string;
connection?: string;
'content-disposition'?: string;
'content-encoding'?: string;
'content-language'?: string;
'content-length'?: string;
'content-location'?: string;
'content-range'?: string;
'content-type'?: string;
cookie?: string;
date?: string;
expect?: string;
expires?: string;
forwarded?: string;
from?: string;
host?: string;
'if-match'?: string;
'if-modified-since'?: string;
'if-none-match'?: string;
'if-unmodified-since'?: string;
'last-modified'?: string;
location?: string;
pragma?: string;
'proxy-authenticate'?: string;
'proxy-authorization'?: string;
'public-key-pins'?: string;
range?: string;
referer?: string;
'retry-after'?: string;
'set-cookie'?: string[];
'strict-transport-security'?: string;
tk?: string;
trailer?: string;
'transfer-encoding'?: string;
upgrade?: string;
'user-agent'?: string;
vary?: string;
via?: string;
warning?: string;
'www-authenticate'?: string;
// Support for arbitrary headers
[header: string]: string | string[] | undefined;
}
interface HeaderWebAPI {
// Include all header properties
[header: string]: any;
// Web API Headers methods
append(name: string, value: string): void;
delete(name: string): void;
get(name: string): string | null;
has(name: string): boolean;
set(name: string, value: string): void;
forEach(callbackfn: (value: string, key: string, parent: HeaderWebAPI) => void, thisArg?: any): void;
// Iterator methods
entries(): IterableIterator<[string, string]>;
keys(): IterableIterator<string>;
values(): IterableIterator<string>;
[Symbol.iterator](): IterableIterator<[string, string]>;
}
interface Query {
[key: string]: any;
}
interface Files {
[key: string]: string;
}
interface Body {
[key: string]: any;
}
interface ResponseCookie {
value: any;
options: CookieOptions;
}