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
Full HTTP response object simulation with status codes, headers, cookies, and all response methods. Includes comprehensive introspection methods for test verification.
Creates a mock HTTP response object with configurable properties and methods.
/**
* Creates a new mock HTTP response instance
* @param options - Configuration options for the mock response
* @returns Mock response object with all HTTP response properties and methods
*/
function createResponse<T extends ResponseType = Response>(options?: ResponseOptions): MockResponse<T>;
interface ResponseOptions {
eventEmitter?: any;
writableStream?: any;
req?: any;
locals?: any;
}
type MockResponse<T extends ResponseType> = T & {
// Introspection methods for testing
_isEndCalled: () => boolean;
_getHeaders: () => HeaderWebAPI;
_getData: () => any;
_getJSONData: () => any;
_getBuffer: () => Buffer;
_getChunks: () => any[];
_getLocals: () => any;
_getStatusCode: () => number;
_getStatusMessage: () => string;
_isJSON: () => boolean;
_isUTF8: () => boolean;
_isDataLengthValid: () => boolean;
_getRedirectUrl: () => string;
_getRenderData: () => any;
_getRenderView: () => string;
// Response cookies
cookies: { [name: string]: ResponseCookie };
};
interface ResponseCookie {
value: any;
options: CookieOptions;
}Usage Examples:
const httpMocks = require('node-mocks-http');
// Basic response
const response = httpMocks.createResponse();
// Response with custom locals
const responseWithLocals = httpMocks.createResponse({
locals: {
user: { id: 1, name: 'John' },
theme: 'dark'
}
});
// Response linked to a request (for format() method)
const { req, res } = httpMocks.createMocks();Methods for setting and managing response status codes.
/**
* Set response status code (chainable)
* @param code - HTTP status code
* @returns Response instance for chaining
*/
status(code: number): MockResponse;
/**
* Send given HTTP status code with standard message
* @param statusCode - HTTP status code
* @returns Response instance
*/
sendStatus(statusCode: number): MockResponse;Usage Examples:
const response = httpMocks.createResponse();
// Set status code
response.status(404);
console.log(response.statusCode); // 404
// Send status with message
response.sendStatus(201); // Sets status to 201 and sends "Created"Comprehensive header management methods.
/**
* Write response headers (should be called once)
* @param statusCode - HTTP status code
* @param statusMessage - Optional status message
* @param headers - Optional headers object
* @returns Response instance
*/
writeHead(statusCode: number, statusMessage?: string | object, headers?: object): MockResponse;
/**
* Set header field to value, or pass an object of header fields
* @param field - Header name or headers object
* @param val - Header value (if field is string)
* @returns Response instance
*/
set(field: string | object, val?: string | string[]): MockResponse;
/**
* Alias for set()
*/
header(field: string | object, val?: string | string[]): MockResponse;
/**
* Get header value by name
* @param name - Header name
* @returns Header value
*/
get(name: string): string | string[] | undefined;
/**
* Alias for get()
*/
getHeader(name: string): string | string[] | undefined;
/**
* Get all headers as object
* @returns Headers object
*/
getHeaders(): object;
/**
* Get array of header names
* @returns Array of header names
*/
getHeaderNames(): string[];
/**
* Check if header exists
* @param name - Header name
* @returns True if header exists
*/
hasHeader(name: string): boolean;
/**
* Set individual header
* @param name - Header name
* @param value - Header value
* @returns Response instance
*/
setHeader(name: string, value: string | string[]): MockResponse;
/**
* Append value to header
* @param name - Header name
* @param value - Value to append
* @returns Response instance
*/
appendHeader(name: string, value: string | string[]): MockResponse;
/**
* Append additional header field with value
* @param field - Header field name
* @param val - Header value
* @returns Response instance
*/
append(field: string, val: string | string[]): MockResponse;
/**
* Remove header by name
* @param name - Header name
*/
removeHeader(name: string): void;Methods for low-level HTTP response control.
/**
* Write response headers (should be called once)
* @param statusCode - HTTP status code
* @param statusMessage - Optional status message
* @param headers - Optional headers object
* @returns Response instance
*/
writeHead(statusCode: number, statusMessage?: string | object, headers?: object): MockResponse;Methods for sending response content.
/**
* Write data to response (can be called multiple times)
* @param data - Data to write
* @param encoding - Optional encoding
*/
write(data: string | Buffer | TypedArray, encoding?: string): void;
/**
* End the response with optional data
* @param data - Optional data to send
* @param encoding - Optional encoding
* @param callback - Optional callback
*/
end(data?: string | Buffer | TypedArray, encoding?: string, callback?: Function): void;
/**
* Send response data (Express-style)
* @param data - Data to send
* @returns Response instance
*/
send(data?: any): MockResponse;
/**
* Send JSON response
* @param data - Data to send as JSON
* @returns Response instance
*/
json(data?: any): MockResponse;
/**
* Send JSONP response
* @param data - Data to send as JSONP
* @returns Response instance
*/
jsonp(data?: any): MockResponse;Usage Examples:
const response = httpMocks.createResponse();
// Send simple response
response.send('Hello World');
// Send JSON response
response.json({ message: 'Success', data: [1, 2, 3] });
// Send status with data
response.status(201).json({ id: 123, created: true });
// Write data incrementally
response.write('Chunk 1');
response.write('Chunk 2');
response.end('Final chunk');Methods for setting content types and handling attachments.
/**
* Set Content-Type header based on file extension or mime type
* @param type - File extension or mime type
* @returns Response instance
*/
type(type: string): MockResponse;
/**
* Alias for type()
*/
contentType(type: string): MockResponse;
/**
* Set Content-Disposition header to attachment
* @param filename - Optional filename
* @returns Response instance
*/
attachment(filename?: string): MockResponse;Usage Examples:
const response = httpMocks.createResponse();
// Set content type by extension
response.type('json'); // Sets 'application/json'
response.type('html'); // Sets 'text/html'
// Set content type by mime type
response.type('application/pdf');
// Set as attachment
response.attachment('report.pdf');Methods for managing response cookies.
/**
* Set cookie
* @param name - Cookie name
* @param value - Cookie value
* @param options - Cookie options
* @returns Response instance
*/
cookie(name: string, value: any, options?: CookieOptions): MockResponse;
/**
* Clear cookie
* @param name - Cookie name
* @param options - Cookie options
* @returns Response instance
*/
clearCookie(name: string, options?: CookieOptions): MockResponse;Usage Examples:
const response = httpMocks.createResponse();
// Set simple cookie
response.cookie('sessionId', 'abc123');
// Set cookie with options
response.cookie('preferences', 'dark-theme', {
maxAge: 86400000, // 24 hours
httpOnly: true,
secure: true
});
// Clear cookie
response.clearCookie('sessionId');Methods for redirects and template rendering.
/**
* Redirect to URL with optional status code
* @param statusCode - Optional HTTP status code (default: 302)
* @param url - URL to redirect to
*/
redirect(url: string): void;
redirect(statusCode: number, url: string): void;
/**
* Render template with data
* @param view - Template name
* @param data - Template data
* @param callback - Optional callback
*/
render(view: string, data?: object, callback?: Function): void;
render(view: string, callback?: Function): void;Additional response utility methods.
/**
* Set Location header
* @param location - Location URL
* @returns Response instance
*/
location(location: string): MockResponse;
/**
* Add field(s) to Vary response header
* @param fields - Field name or array of field names
* @returns Response instance
*/
vary(fields: string | string[]): MockResponse;
/**
* Perform content negotiation
* @param supported - Object mapping content types to handler functions
* @returns Result of handler function
*/
format(supported: { [type: string]: Function }): any;
/**
* Set encoding for response data
* @param encoding - Character encoding
*/
setEncoding(encoding: string): void;
/**
* Get current encoding
* @returns Current encoding
*/
getEncoding(): string;
/**
* Destroy the response stream
* @param args - Optional arguments passed to destroy
*/
destroy(...args: any[]): void;
/**
* Destroy the response stream soon
* @param args - Optional arguments passed to destroySoon
*/
destroySoon(...args: any[]): void;Testing utility methods for verifying response behavior (prefixed with _).
/**
* Check if end() has been called
* @returns True if end() was called
*/
_isEndCalled(): boolean;
/**
* Get all response headers
* @returns Headers object
*/
_getHeaders(): object;
/**
* Get response data as string
* @returns Response data
*/
_getData(): string;
/**
* Get response data as parsed JSON
* @returns Parsed JSON data
*/
_getJSONData(): any;
/**
* Get response data as Buffer
* @returns Response buffer
*/
_getBuffer(): Buffer;
/**
* Get array of written chunks
* @returns Array of data chunks written to response
*/
_getChunks(): any[];
/**
* Get response locals
* @returns Locals object
*/
_getLocals(): object;
/**
* Get response status code
* @returns Status code
*/
_getStatusCode(): number;
/**
* Get response status message
* @returns Status message
*/
_getStatusMessage(): string;
/**
* Check if response is JSON
* @returns True if Content-Type is application/json
*/
_isJSON(): boolean;
/**
* Check if response encoding is UTF-8
* @returns True if encoding is utf8
*/
_isUTF8(): boolean;
/**
* Validate Content-Length header against actual data length
* @returns True if Content-Length matches data length
*/
_isDataLengthValid(): boolean;
/**
* Get redirect URL (if redirect was called)
* @returns Redirect URL
*/
_getRedirectUrl(): string;
/**
* Get render view name (if render was called)
* @returns View name
*/
_getRenderView(): string;
/**
* Get render data (if render was called)
* @returns Render data
*/
_getRenderData(): object;Usage Examples:
const response = httpMocks.createResponse();
// Use the response in your handler
yourRouteHandler(request, response);
// Verify the response in tests
console.log(response._isEndCalled()); // true if end() was called
console.log(response._getStatusCode()); // e.g., 200
console.log(response._getData()); // response body as string
console.log(response._getJSONData()); // parsed JSON if JSON response
console.log(response._isJSON()); // true if JSON response
console.log(response._getHeaders()); // all response headers
// Check redirects
if (response.statusCode === 302) {
console.log(response._getRedirectUrl()); // redirect URL
}
// Check renders
console.log(response._getRenderView()); // template name
console.log(response._getRenderData()); // template dataThe mock response includes all standard HTTP response properties: