A comprehensive XMLHttpRequest mocking utility for testing and prototyping web applications.
npx @tessl/cli install tessl/npm-xhr-mock@2.5.0xhr-mock is a comprehensive XMLHttpRequest mocking utility designed for testing and prototyping web applications. It enables developers to replace the global XMLHttpRequest object with a mock implementation that can simulate HTTP responses, errors, timeouts, and progress events.
npm install --save-dev xhr-mockimport mock from 'xhr-mock';
import { MockRequest, MockResponse, proxy, once, delay, sequence } from 'xhr-mock';For CommonJS:
const mock = require('xhr-mock');
const { MockRequest, MockResponse, proxy, once, delay, sequence } = require('xhr-mock');For browser without bundler:
<script src="https://unpkg.com/xhr-mock/dist/xhr-mock.js"></script>
<!-- Global XHRMock variable is now available -->import mock from 'xhr-mock';
describe('API Tests', () => {
// Setup mock before each test
beforeEach(() => mock.setup());
// Teardown mock after each test
afterEach(() => mock.teardown());
it('should mock GET requests', async () => {
// Mock a GET request
mock.get('/api/users', {
status: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify([{ id: 1, name: 'John' }])
});
// Make actual request (using any HTTP library)
const response = await fetch('/api/users');
const users = await response.json();
expect(users).toEqual([{ id: 1, name: 'John' }]);
});
it('should mock with custom function', async () => {
mock.post('/api/users', (req, res) => {
const userData = JSON.parse(req.body());
return res.status(201).body(JSON.stringify({
id: 123,
...userData
}));
});
// Test your code that makes POST requests
});
});xhr-mock is built around several key components:
XHRMock class for setting up and managing mocksMockRequest and MockResponse classes for inspecting and building HTTP interactionsCore mock management functionality for setting up XMLHttpRequest mocks, registering handlers, and controlling the mock lifecycle.
class XHRMock {
setup(): XHRMock;
teardown(): XHRMock;
reset(): XHRMock;
error(callback: (event: ErrorCallbackEvent) => void): XHRMock;
use(fn: MockFunction): XHRMock;
use(method: string, url: string | RegExp, mock: Mock): XHRMock;
get(url: string | RegExp, mock: Mock): XHRMock;
post(url: string | RegExp, mock: Mock): XHRMock;
put(url: string | RegExp, mock: Mock): XHRMock;
patch(url: string | RegExp, mock: Mock): XHRMock;
delete(url: string | RegExp, mock: Mock): XHRMock;
}Classes for inspecting incoming requests and building mock responses with full control over headers, body, and status codes.
class MockRequest {
method(): string;
method(method: string): MockRequest;
url(): MockURL;
url(url: string): MockRequest;
header(name: string): null | string;
header(name: string, value: string): MockRequest;
headers(): MockHeaders;
headers(headers: MockHeaders): MockRequest;
body(): any;
body(body: any): MockRequest;
}
class MockResponse {
status(): number;
status(status: number): MockResponse;
reason(): string;
reason(reason: string): MockResponse;
header(name: string): null | string;
header(name: string, value: string): MockResponse;
headers(): MockHeaders;
headers(headers: MockHeaders): MockResponse;
body(): any;
body(body: any): MockResponse;
}Helper functions for advanced mocking scenarios including delays, one-time responses, response sequences, and request proxying.
function once(mock: MockFunction | MockObject): MockFunction;
function delay(mock: MockFunction | MockObject, ms?: number): MockFunction;
function sequence(mocks: (MockFunction | MockObject)[]): MockFunction;
function proxy(req: MockRequest, res: MockResponse): Promise<MockResponse>;type MockHeaders = {[name: string]: string};
interface MockObject {
status?: number;
reason?: string;
headers?: MockHeaders;
body?: any;
}
type MockFunction = (
request: MockRequest,
response: MockResponse
) => undefined | MockResponse | Promise<undefined | MockResponse>;
type Mock = MockObject | MockFunction;
interface ErrorCallbackEvent {
req: MockRequest;
err: Error;
}