A comprehensive XMLHttpRequest mocking utility for testing and prototyping web applications.
The MockRequest and MockResponse classes provide complete control over HTTP request inspection and response construction. These objects follow a fluent API pattern where methods can be chained together.
Represents an incoming HTTP request with methods to inspect and modify request properties.
class MockRequest {
/**
* Get the HTTP method
* @returns The HTTP method (e.g., 'GET', 'POST')
*/
method(): string;
/**
* Set the HTTP method
* @param method - HTTP method to set
* @returns MockRequest instance for chaining
*/
method(method: string): MockRequest;
/**
* Get the request URL as a parsed object
* @returns MockURL object with parsed URL components
*/
url(): MockURL;
/**
* Set the request URL
* @param url - URL string to parse and set
* @returns MockRequest instance for chaining
*/
url(url: string): MockRequest;
/**
* Get a specific request header value
* @param name - Header name (case-insensitive)
* @returns Header value or null if not found
*/
header(name: string): null | string;
/**
* Set a request header
* @param name - Header name
* @param value - Header value
* @returns MockRequest instance for chaining
*/
header(name: string, value: string): MockRequest;
/**
* Get all request headers
* @returns Object containing all headers
*/
headers(): MockHeaders;
/**
* Set multiple request headers
* @param headers - Object containing header name-value pairs
* @returns MockRequest instance for chaining
*/
headers(headers: MockHeaders): MockRequest;
/**
* Get the request body
* @returns Request body (any type)
*/
body(): any;
/**
* Set the request body
* @param body - Request body content
* @returns MockRequest instance for chaining
*/
body(body: any): MockRequest;
}Usage Examples:
mock.post('/api/users', (req, res) => {
// Inspect request method
console.log(req.method()); // 'POST'
// Check request headers
const contentType = req.header('Content-Type');
if (contentType === 'application/json') {
// Parse JSON body
const userData = JSON.parse(req.body());
console.log('User data:', userData);
}
// Check URL components
const url = req.url();
console.log('Path:', url.path);
console.log('Query params:', url.query);
// Return response
return res.status(201).body(JSON.stringify({ id: 123, ...userData }));
});Represents an HTTP response with methods to set status, headers, and body content.
class MockResponse {
/**
* Get the response status code
* @returns HTTP status code
*/
status(): number;
/**
* Set the response status code
* @param status - HTTP status code (e.g., 200, 404, 500)
* @returns MockResponse instance for chaining
*/
status(status: number): MockResponse;
/**
* Get the response reason phrase
* @returns HTTP reason phrase (e.g., 'OK', 'Not Found')
*/
reason(): string;
/**
* Set the response reason phrase
* @param reason - HTTP reason phrase
* @returns MockResponse instance for chaining
*/
reason(reason: string): MockResponse;
/**
* Get a specific response header value
* @param name - Header name (case-insensitive)
* @returns Header value or null if not found
*/
header(name: string): null | string;
/**
* Set a response header
* @param name - Header name
* @param value - Header value
* @returns MockResponse instance for chaining
*/
header(name: string, value: string): MockResponse;
/**
* Get all response headers
* @returns Object containing all headers
*/
headers(): MockHeaders;
/**
* Set multiple response headers
* @param headers - Object containing header name-value pairs
* @returns MockResponse instance for chaining
*/
headers(headers: MockHeaders): MockResponse;
/**
* Get the response body
* @returns Response body (any type)
*/
body(): any;
/**
* Set the response body
* @param body - Response body content
* @returns MockResponse instance for chaining
*/
body(body: any): MockResponse;
}Usage Examples:
// Basic response construction
mock.get('/api/status', (req, res) => {
return res
.status(200)
.reason('OK')
.header('Content-Type', 'application/json')
.body(JSON.stringify({ status: 'healthy' }));
});
// Error response
mock.get('/api/forbidden', (req, res) => {
return res
.status(403)
.reason('Forbidden')
.header('Content-Type', 'application/json')
.body(JSON.stringify({ error: 'Access denied' }));
});
// Multiple headers at once
mock.get('/api/data', (req, res) => {
return res
.status(200)
.headers({
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'X-API-Version': '1.0'
})
.body(JSON.stringify({ data: [1, 2, 3] }));
});
// Dynamic response based on request
mock.post('/api/echo', (req, res) => {
const requestBody = req.body();
const contentType = req.header('Content-Type') || 'text/plain';
return res
.status(200)
.header('Content-Type', contentType)
.body(requestBody);
});The following MockResponse methods are deprecated:
/**
* @deprecated Use reason() instead
*/
statusText(): null | string;
statusText(reason: string): MockResponse;type MockHeaders = {[name: string]: string};
interface MockURL {
protocol?: string;
username?: string;
password?: string;
host?: string;
port?: number;
path?: string;
query?: {[name: string]: string};
hash?: string;
toString(): string;
}xhr-mock automatically simulates progress events for both upload and download when appropriate headers and body content are provided:
Upload Progress:
// Set Content-Length header when sending body to trigger upload progress events
mock.post('/upload', (req, res) => {
// req will have Content-Length header if set by client
return res.status(200);
});
// Client code:
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = (event) => {
console.log(`Upload: ${event.loaded}/${event.total} bytes`);
};
xhr.open('POST', '/upload');
xhr.setRequestHeader('Content-Length', '12');
xhr.send('Hello World!');Download Progress:
// Set Content-Length header in response to trigger download progress events
mock.get('/download', (req, res) => {
const data = 'Large file content...';
return res
.status(200)
.header('Content-Length', data.length.toString())
.body(data);
});
// Client code:
const xhr = new XMLHttpRequest();
xhr.onprogress = (event) => {
console.log(`Download: ${event.loaded}/${event.total} bytes`);
};
xhr.open('GET', '/download');
xhr.send();Install with Tessl CLI
npx tessl i tessl/npm-xhr-mock