CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-xhr-mock

A comprehensive XMLHttpRequest mocking utility for testing and prototyping web applications.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

xhr-mock

xhr-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.

Package Information

  • Package Name: xhr-mock
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install --save-dev xhr-mock

Core Imports

import 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 -->

Basic Usage

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
  });
});

Architecture

xhr-mock is built around several key components:

  • Mock Controller: Central XHRMock class for setting up and managing mocks
  • Request/Response Objects: MockRequest and MockResponse classes for inspecting and building HTTP interactions
  • Mock Patterns: URL and HTTP method pattern matching for request routing
  • Utility Functions: Helper functions for common scenarios like delays, one-time responses, and sequences
  • XMLHttpRequest Replacement: Complete mock implementation that follows the XMLHttpRequest specification

Capabilities

Mock Controller

Core 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;
}

Mock Controller

Request and Response Objects

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;
}

Request and Response Objects

Utility Functions

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>;

Utility Functions

Core Types

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;
}
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/xhr-mock@2.5.x
Publish Source
CLI
Badge
tessl/npm-xhr-mock badge