New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

axios-mock-plugin

Package Overview
Dependencies
Maintainers
0
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

axios-mock-plugin

Promise based mock adapter for axios.

  • 0.2.1
  • npm
  • Socket score

Version published
Weekly downloads
288
increased by372.13%
Maintainers
0
Weekly downloads
 
Created
Source

Axios Mock Plugin

npm version codecov License

Promise based mock adapter for axios.

Table of Contents

Motivation

Axios Mock Plugin was created to simplify API mocking in frontend development and testing. While there are other mocking solutions available, this plugin aims to provide:

  • A simple, Express-like syntax for defining mock endpoints
  • Seamless integration with existing Axios instances
  • Type-safe mocking with full TypeScript support
  • Flexible configuration for simulating real-world scenarios

Whether you're developing a new feature without a ready backend, running automated tests, or demonstrating your application offline, Axios Mock Plugin helps you mock API responses with minimal effort.

Features

  • Express-style endpoint patterns (GET /users/:id)
  • Dynamic URL parameters and query strings support
  • Request body and headers handling
  • Configurable response delays and random errors
  • Request/Response hooks for custom behaviors
  • TypeScript support out of the box

Installing

Using npm:

$ npm install axios-mock-plugin

Using yarn:

$ yarn add axios-mock-plugin

Using pnpm:

$ pnpm add axios-mock-plugin

Example

Basic Usage

import axios from 'axios'
import { attachMockInterceptor } from 'axios-mock-plugin'

const apiClient = axios.create()

// Define mock endpoints
const endpoints = {
  'GET /users/:id': (req) => ({
    id: req.params.id,
    name: 'John Doe'
  })
}

// Attach mock interceptor
const { mocker } = attachMockInterceptor(apiClient, { endpoints })

// Make a mocked request
apiClient.get('/users/123', { mock: true })
  .then(response => console.log(response.data))
  // Output: { id: '123', name: 'John Doe' }

URL Parameters and Query Strings

const endpoints = {
  'GET /users/:userId/posts/:postId': (req, config) => ({
    userId: req.params.userId,
    postId: req.params.postId,
    sortBy: req.query.sortBy,
    page: req.query.page
  })
}

apiClient.get('/users/123/posts/456?sortBy=date&page=1', { mock: true })
  .then(response => console.log(response.data))
  // Output: {
  //   userId: '123',
  //   postId: '456',
  //   sortBy: 'date',
  //   page: '1'
  // }

Request Body and Headers

const endpoints = {
  'POST /users': (req, config) => ({
    success: true,
    receivedData: req.body,
    contentType: config.headers['content-type']
  })
}

apiClient.post('/users',
  { name: 'John', email: 'john@example.com' },
  {
    headers: { 'content-type': 'application/json' },
    mock: true
  }
).then(response => console.log(response.data))
// Output: {
//   success: true,
//   receivedData: { name: 'John', email: 'john@example.com' },
//   contentType: 'application/json'
// }

API

attachMockInterceptor(axiosInstance, options)

Attaches a mock interceptor to an Axios instance.

import { AxiosInstance } from 'axios'
import { AxiosMocker, AxiosMockerConfig } from 'axios-mock-plugin'

function attachMockInterceptor(
  axiosInstance: AxiosInstance,
  config?: AxiosMockerConfig
): {
  mocker: AxiosMocker
  interceptorId: number
}

detachMockInterceptor(axiosInstance, interceptorId)

Removes the mock interceptor from an Axios instance.

function detachMockInterceptor(
  axiosInstance: AxiosInstance,
  interceptorId: number
): void

Request Config

The mock configuration extends Axios request config:

interface AxiosRequestConfigWithMock extends InternalAxiosRequestConfig<any> {
  mock?: boolean | Partial<MockOptions>
}

interface MockOptions {
  enabled?: boolean
  delay?: number
  errorRate?: number
  headers?: Record<string, string>
  error?: {
    status?: number
    message?: string
    details?: unknown[]
  }
  getDelay?: (config: AxiosRequestConfigWithMock, endpoint: string) => number
  enableLogging?: boolean
}

Types

MockRequest

Request object passed to endpoint handlers:

interface MockRequest<
  Params = Record<string, unknown>,
  Query = Record<string, unknown>,
  Body = unknown
> {
  params: Params
  query: Query
  body: Body
}

MockEndpoint

Endpoint handler function type:

type MockEndpoint<
  Params = Record<string, unknown>,
  Query = Record<string, unknown>,
  Body = unknown
> = (
  request: MockRequest<Params, Query, Body>,
  axiosConfig: AxiosRequestConfigWithMock
) => unknown | Promise<unknown>

Hooks

Request/Response hook types:

type RequestHook = (
  request: MockRequest,
  config: AxiosRequestConfigWithMock
) => void | Promise<void>

type ResponseHook = (
  response: AxiosResponse,
  config: AxiosRequestConfigWithMock
) => void | Promise<void>

Configuration

Default Config

const defaultConfig: InternalMockOptions = {
  enabled: true,      // Mock interceptor is enabled by default
  delay: 0,          // No delay
  errorRate: 0,      // No random errors
  headers: {},       // No additional headers
  error: undefined,  // No forced errors
  getDelay: undefined, // No dynamic delay
  enableLogging: false // Logging is disabled
}

Global Config

You can set global configuration when attaching the interceptor:

const { mocker } = attachMockInterceptor(axios, {
  endpoints: {
    'GET /users': () => [{ id: 1, name: 'John' }]
  },
  config: {
    delay: 1000,           // Add 1s delay to all requests
    errorRate: 0.1,        // 10% chance of random error
    enableLogging: true,   // Enable request/response logging
    headers: {             // Add global headers
      'x-custom-header': 'custom-value'
    },
    getDelay: (config, endpoint) => {
      // Custom delay logic
      return endpoint.includes('users') ? 2000 : 1000
    }
  }
})

Request Config

Override configuration for individual requests:

axios.get('/users/123', {
  mock: {
    delay: 2000,     // Override delay for this request only
    errorRate: 0     // Disable random errors for this request
  }
})

Configuration precedence: Request Config > Global Config > Default Config

Error Handling

apiClient.get('/users/123', { mock: true })
  .catch(error => {
    if (error.response) {
      // Mock responded with error status
      console.log(error.response.status)
      console.log(error.response.data)
    } else {
      // Mock setup error or network error
      console.log(error.message)
    }
  })

License

MIT License

Copyright (c) 2025 Ahmet Tinastepe

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Keywords

FAQs

Package last updated on 15 Feb 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc