CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-axios-mock-adapter

Axios adapter that allows to easily mock requests

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

Axios Mock Adapter

Axios Mock Adapter is a comprehensive axios request mocking library that enables developers to easily intercept and mock HTTP requests in testing environments. It offers a chainable API for setting up mock responses based on request methods, URLs, parameters, and request data, with support for regex patterns, asymmetric matchers, and dynamic response functions.

Package Information

  • Package Name: axios-mock-adapter
  • Package Type: npm
  • Language: JavaScript (with TypeScript definitions)
  • Installation: npm install axios-mock-adapter --save-dev

Core Imports

const AxiosMockAdapter = require("axios-mock-adapter");

// Alternative default import (also available)
const AxiosMockAdapter = require("axios-mock-adapter").default;

For ES modules:

import AxiosMockAdapter from "axios-mock-adapter";

Basic Usage

const axios = require("axios");
const AxiosMockAdapter = require("axios-mock-adapter");

// Create mock adapter
const mock = new AxiosMockAdapter(axios);

// Mock GET request and set response
mock.onGet("/users").reply(200, {
  users: [{ id: 1, name: "John Smith" }]
});

// Make request (will be intercepted)
axios.get("/users").then(function (response) {
  console.log(response.data); // { users: [{ id: 1, name: "John Smith" }] }
});

// Clean up
mock.restore();

Architecture

Axios Mock Adapter is built around several key components:

  • AxiosMockAdapter Class: Core class that intercepts axios requests and manages mock handlers
  • Request Handlers: Fluent interface for configuring mock responses, errors, and delays
  • History Tracking: Records all intercepted requests for testing assertions
  • URL Matching: Supports string exact matching and regex patterns for flexible request matching
  • Response Simulation: Comprehensive error simulation including network errors, timeouts, and aborted requests

Capabilities

Mock Adapter Management

Core functionality for creating, configuring, and managing axios mock adapters.

class AxiosMockAdapter {
  static default: typeof AxiosMockAdapter;
  constructor(axiosInstance, options);
  adapter();
  restore();
  reset();
  resetHandlers();
  resetHistory();
  history: HistoryArray;
}

interface MockAdapterOptions {
  delayResponse?: number;
  onNoMatch?: 'passthrough' | 'throwException';
}

Mock Adapter Management

HTTP Method Mocking

Comprehensive HTTP method mocking with support for all standard HTTP verbs and flexible parameter matching.

// Methods without request body
onGet(matcher?, config?): RequestHandler;
onDelete(matcher?, config?): RequestHandler;
onHead(matcher?, config?): RequestHandler;
onOptions(matcher?, config?): RequestHandler;

// Methods with request body
onPost(matcher?, body?, config?): RequestHandler;
onPut(matcher?, body?, config?): RequestHandler;
onPatch(matcher?, body?, config?): RequestHandler;
onList(matcher?, body?, config?): RequestHandler;
onLink(matcher?, body?, config?): RequestHandler;
onUnlink(matcher?, body?, config?): RequestHandler;

// Universal method
onAny(matcher?, config?): RequestHandler;

HTTP Method Mocking

Response Configuration

Flexible response configuration with support for static responses, dynamic functions, and various response formats.

interface RequestHandler {
  reply(statusOrCallback, data?, headers?): AxiosMockAdapter;
  replyOnce(statusOrCallback, data?, headers?): AxiosMockAdapter;
  withDelayInMs(delay: number): RequestHandler;
}

type CallbackResponseSpecFunc = (config) => MockResponse | Promise<MockResponse>;
type MockResponse = [number, any?, object?] | { status: number; data: any; headers?: object };

Response Configuration

Error Simulation

Advanced error simulation capabilities for testing error handling and network failure scenarios.

interface RequestHandler {
  passThrough(): AxiosMockAdapter;
  networkError(): AxiosMockAdapter;
  networkErrorOnce(): AxiosMockAdapter;
  timeout(): AxiosMockAdapter;
  timeoutOnce(): AxiosMockAdapter;
  abortRequest(): AxiosMockAdapter;
  abortRequestOnce(): AxiosMockAdapter;
}

Error Simulation

Types

interface HistoryArray extends Array {
  get: Array;
  post: Array;
  put: Array;
  delete: Array;
  patch: Array;
  head: Array;
  options: Array;
  list: Array;
  link: Array;
  unlink: Array;
}

interface AsymmetricMatcher {
  asymmetricMatch: Function;
}

interface ConfigMatcher {
  params?: object | AsymmetricMatcher;
  headers?: object | AsymmetricMatcher;
  data?: any | AsymmetricMatcher;
}

interface CouldNotFindMockError extends Error {
  isCouldNotFindMockError: boolean;
  url: string;
  method: string;
}

type UrlMatcher = string | RegExp;

type MockArrayResponse = [status: number, data?: any, headers?: object];

type MockObjectResponse = {
  status: number;
  data: any;
  headers?: object;
  config?: object;
};

type MockResponse = MockArrayResponse | MockObjectResponse;
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/axios-mock-adapter@2.1.x
Publish Source
CLI
Badge
tessl/npm-axios-mock-adapter badge