Mock HTTP objects for testing Express, Next.js, and Koa routing functions
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Complete HTTP request object simulation with all standard properties and methods, designed for testing route handlers, middleware, and request processing logic.
Creates a mock HTTP request object with configurable properties and methods.
/**
* Creates a new mock HTTP request instance
* @param options - Configuration options for the mock request
* @returns Mock request object with all HTTP request properties and methods
*/
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;
}
type MockRequest<T extends RequestType> = T & {
// Mock configuration methods
_setParameter: (key: string, value?: string) => void;
_setSessionVariable: (variable: string, value?: string) => void;
_setCookiesVariable: (variable: string, value?: string) => void;
_setSignedCookiesVariable: (variable: string, value?: string) => void;
_setHeadersVariable: (variable: string, value: string) => void;
_setFilesVariable: (variable: string, value?: string) => void;
_setMethod: (method?: string) => void;
_setURL: (value?: string) => void;
_setOriginalUrl: (value?: string) => void;
_setBaseUrl: (value?: string) => void;
_setBody: (body?: Body) => void;
_addBody: (key: string, value?: any) => void;
// Enhanced headers with Web API methods
headers: HeaderWebAPI;
// Express-style computed properties
protocol: string;
secure: boolean;
ip: string;
ips: string[];
hostname: string;
host: string;
subdomains: string[];
path: string;
fresh: boolean;
stale: boolean;
xhr: boolean;
// Support custom properties
[key: string]: any;
};
interface HeaderWebAPI {
[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]>;
}Usage Examples:
const httpMocks = require('node-mocks-http');
// Basic request
const request = httpMocks.createRequest({
method: 'GET',
url: '/users/123',
params: { id: '123' }
});
// Request with headers and body
const postRequest = httpMocks.createRequest({
method: 'POST',
url: '/api/users',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123'
},
body: {
name: 'John Doe',
email: 'john@example.com'
}
});
// Request with query parameters
const searchRequest = httpMocks.createRequest({
method: 'GET',
url: '/search?q=node&limit=10',
query: {
q: 'node',
limit: '10'
}
});Methods for accessing and manipulating HTTP headers.
/**
* Get header value by name (case-insensitive)
* @param name - Header name
* @returns Header value or undefined
*/
getHeader(name: string): string | undefined;
/**
* Alias for getHeader
*/
header(name: string): string | undefined;
/**
* Alias for getHeader
*/
get(name: string): string | undefined;Usage Examples:
const request = httpMocks.createRequest({
headers: {
'Content-Type': 'application/json',
'User-Agent': 'test-agent'
}
});
console.log(request.get('Content-Type')); // 'application/json'
console.log(request.header('user-agent')); // 'test-agent' (case-insensitive)
console.log(request.getHeader('Authorization')); // undefinedMethods for checking and validating content types.
/**
* Check if request matches given content type(s)
* @param types - Content type or array of types to check
* @returns Matching type string or false
*/
is(...types: string[]): string | false | null;Usage Examples:
const request = httpMocks.createRequest({
headers: { 'Content-Type': 'application/json' },
body: { name: 'test' }
});
console.log(request.is('json')); // 'json'
console.log(request.is('html')); // false
console.log(request.is(['xml', 'json'])); // 'json'Methods for handling Accept headers and content negotiation.
/**
* Check what content types the client accepts
* @param types - Content types to check
* @returns Best matching type or false
*/
accepts(types: string | string[]): string | false;
/**
* Check what encodings the client accepts
* @param encodings - Encodings to check
* @returns Best matching encoding or false
*/
acceptsEncodings(...encodings: string[]): string | false;
/**
* Check what charsets the client accepts
* @param charsets - Charsets to check
* @returns Best matching charset or false
*/
acceptsCharsets(...charsets: string[]): string | false;
/**
* Check what languages the client accepts
* @param languages - Languages to check
* @returns Best matching language or false
*/
acceptsLanguages(...languages: string[]): string | false;Support for HTTP Range requests.
/**
* Parse Range header field
* @param size - Resource size
* @param opts - Range parsing options
* @returns Range result or undefined
*/
range(size: number, opts?: object): false | number | array | undefined;Methods for accessing request parameters from various sources.
/**
* Get parameter value from params, body, or query (in that order)
* @param name - Parameter name
* @param defaultValue - Default value if parameter not found
* @returns Parameter value or default
*/
param(name: string, defaultValue?: any): any;Usage Examples:
const request = httpMocks.createRequest({
params: { id: '123' },
body: { name: 'John' },
query: { sort: 'asc' }
});
console.log(request.param('id')); // '123' (from params)
console.log(request.param('name')); // 'John' (from body)
console.log(request.param('sort')); // 'asc' (from query)
console.log(request.param('missing', 'default')); // 'default'Methods for handling request as a stream.
/**
* Send data to the request stream
* @param data - Data to send (string, object, number, or Buffer)
*/
send(data: string | object | number | Buffer): void;
/**
* Destroy the request stream
*/
destroy(): void;
/**
* Async iterator for processing request data
*/
[Symbol.asyncIterator](): AsyncIterableIterator<Buffer>;Methods for dynamically modifying the mock request (prefixed with _).
/**
* Set a route parameter
* @param key - Parameter key
* @param value - Parameter value
*/
_setParameter(key: string, value?: string): void;
/**
* Set a session variable
* @param variable - Variable name
* @param value - Variable value
*/
_setSessionVariable(variable: string, value?: string): void;
/**
* Set a cookie variable
* @param variable - Cookie name
* @param value - Cookie value
*/
_setCookiesVariable(variable: string, value?: string): void;
/**
* Set a signed cookie variable
* @param variable - Cookie name
* @param value - Cookie value
*/
_setSignedCookiesVariable(variable: string, value?: string): void;
/**
* Set a header value
* @param variable - Header name
* @param value - Header value
*/
_setHeadersVariable(variable: string, value: string): void;
/**
* Set a file variable
* @param variable - File field name
* @param value - File value
*/
_setFilesVariable(variable: string, value?: string): void;
/**
* Set the HTTP method
* @param method - HTTP method
*/
_setMethod(method?: string): void;
/**
* Set the request URL
* @param value - URL path
*/
_setURL(value?: string): void;
/**
* Set the original URL
* @param value - Original URL
*/
_setOriginalUrl(value?: string): void;
/**
* Set the base URL
* @param value - Base URL path
*/
_setBaseUrl(value?: string): void;
/**
* Set the request body
* @param body - Request body object
*/
_setBody(body?: Body): void;
/**
* Add a property to the request body
* @param key - Body property key
* @param value - Body property value
*/
_addBody(key: string, value?: any): void;Request objects include Express-compatible computed properties that derive values from headers and configuration.
/**
* Request protocol (http or https)
*/
protocol: string;
/**
* Whether the connection is secure (https)
*/
secure: boolean;
/**
* Client IP address
*/
ip: string;
/**
* Array of IP addresses (when behind proxies)
*/
ips: string[];
/**
* Request hostname (without port)
*/
hostname: string;
/**
* Request host (with port if specified)
*/
host: string;
/**
* Array of subdomain parts
*/
subdomains: string[];
/**
* Request pathname (derived from URL)
*/
path: string;
/**
* Whether request is fresh (conditional GET)
*/
fresh: boolean;
/**
* Whether request is stale (opposite of fresh)
*/
stale: boolean;
/**
* Whether request is XMLHttpRequest
*/
xhr: boolean;Usage Examples:
const request = httpMocks.createRequest({
headers: {
'Host': 'api.example.com:8080',
'X-Forwarded-Proto': 'https',
'X-Requested-With': 'XMLHttpRequest'
},
url: '/users/123'
});
console.log(request.protocol); // 'https'
console.log(request.secure); // true
console.log(request.hostname); // 'api.example.com'
console.log(request.host); // 'api.example.com:8080'
console.log(request.path); // '/users/123'
console.log(request.xhr); // trueThe mock request includes all standard HTTP request properties: