A comprehensive XMLHttpRequest mocking utility for testing and prototyping web applications.
The Mock Controller is the central component for managing XMLHttpRequest mocks. It provides methods to set up and tear down mocks, register request handlers, and control the mock lifecycle.
Controls the mock lifecycle by replacing and restoring the global XMLHttpRequest object.
/**
* Replace the global XMLHttpRequest object with the mock implementation
* @returns XHRMock instance for chaining
*/
setup(): XHRMock;
/**
* Restore the global XMLHttpRequest object to its original state
* @returns XHRMock instance for chaining
*/
teardown(): XHRMock;
/**
* Clear all registered request handlers
* @returns XHRMock instance for chaining
*/
reset(): XHRMock;Usage Example:
import mock from 'xhr-mock';
// Set up mocks before your tests
mock.setup();
// Your test code here...
// Clean up mocks after your tests
mock.teardown();Register a callback to handle errors that occur in mock handlers.
/**
* Set error callback for handler errors
* @param callback - Function to handle errors from mock handlers
* @returns XHRMock instance for chaining
*/
error(callback: (event: ErrorCallbackEvent) => void): XHRMock;
interface ErrorCallbackEvent {
req: MockRequest;
err: Error;
}Usage Example:
mock.error((event) => {
console.error('Mock handler error:', event.err);
console.log('Request that caused error:', event.req.method(), event.req.url());
});Register mock handlers for specific requests or all requests.
/**
* Register a mock function for all requests
* @param fn - Function that handles all requests
* @returns XHRMock instance for chaining
*/
use(fn: MockFunction): XHRMock;
/**
* Register a mock for specific HTTP method and URL pattern
* @param method - HTTP method (GET, POST, PUT, PATCH, DELETE)
* @param url - URL string or RegExp pattern to match
* @param mock - Mock object or function to handle the request
* @returns XHRMock instance for chaining
*/
use(method: string, url: string | RegExp, mock: Mock): XHRMock;Usage Examples:
// Handle all requests with a function
mock.use((req, res) => {
if (req.url().path === '/api/status') {
return res.status(200).body('OK');
}
// Return undefined to pass to next handler
});
// Handle specific method and URL
mock.use('GET', '/api/users', {
status: 200,
body: JSON.stringify([{ id: 1, name: 'John' }])
});
// Using RegExp for URL matching
mock.use('POST', /\/api\/users\/\d+/, (req, res) => {
return res.status(204);
});Convenient methods for registering handlers for specific HTTP methods.
/**
* Register a mock for GET requests to specific URL
* @param url - URL string or RegExp pattern to match
* @param mock - Mock object or function to handle the request
* @returns XHRMock instance for chaining
*/
get(url: string | RegExp, mock: Mock): XHRMock;
/**
* Register a mock for POST requests to specific URL
* @param url - URL string or RegExp pattern to match
* @param mock - Mock object or function to handle the request
* @returns XHRMock instance for chaining
*/
post(url: string | RegExp, mock: Mock): XHRMock;
/**
* Register a mock for PUT requests to specific URL
* @param url - URL string or RegExp pattern to match
* @param mock - Mock object or function to handle the request
* @returns XHRMock instance for chaining
*/
put(url: string | RegExp, mock: Mock): XHRMock;
/**
* Register a mock for PATCH requests to specific URL
* @param url - URL string or RegExp pattern to match
* @param mock - Mock object or function to handle the request
* @returns XHRMock instance for chaining
*/
patch(url: string | RegExp, mock: Mock): XHRMock;
/**
* Register a mock for DELETE requests to specific URL
* @param url - URL string or RegExp pattern to match
* @param mock - Mock object or function to handle the request
* @returns XHRMock instance for chaining
*/
delete(url: string | RegExp, mock: Mock): XHRMock;Usage Examples:
// Simple object responses
mock.get('/api/users', {
status: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify([{ id: 1, name: 'John' }])
});
mock.post('/api/users', {
status: 201,
body: JSON.stringify({ id: 2, name: 'Jane' })
});
// Function responses for dynamic behavior
mock.put('/api/users/:id', (req, res) => {
const userData = JSON.parse(req.body());
return res
.status(200)
.header('Content-Type', 'application/json')
.body(JSON.stringify({ ...userData, updated: true }));
});
// Using RegExp for complex URL patterns
mock.delete(/\/api\/users\/\d+/, (req, res) => {
return res.status(204);
});Note: The following methods are deprecated and should be replaced with use():
/**
* @deprecated Use use() instead
*/
mock(fn: MockFunction): XHRMock;
mock(method: string, url: string | RegExp, mock: Mock): XHRMock;type MockFunction = (
request: MockRequest,
response: MockResponse
) => undefined | MockResponse | Promise<undefined | MockResponse>;
interface MockObject {
status?: number;
reason?: string;
headers?: MockHeaders;
body?: any;
}
type Mock = MockObject | MockFunction;
type MockHeaders = {[name: string]: string};Install with Tessl CLI
npx tessl i tessl/npm-xhr-mock