Axios Mock Plugin

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()
const endpoints = {
'GET /users/:id': (req) => ({
id: req.params.id,
name: 'John Doe'
})
}
const { mocker } = attachMockInterceptor(apiClient, { endpoints })
apiClient.get('/users/123', { mock: true })
.then(response => console.log(response.data))
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))
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))
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,
delay: 0,
errorRate: 0,
headers: {},
error: undefined,
getDelay: undefined,
enableLogging: false
}
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,
errorRate: 0.1,
enableLogging: true,
headers: {
'x-custom-header': 'custom-value'
},
getDelay: (config, endpoint) => {
return endpoint.includes('users') ? 2000 : 1000
}
}
})
Request Config
Override configuration for individual requests:
axios.get('/users/123', {
mock: {
delay: 2000,
errorRate: 0
}
})
Configuration precedence: Request Config > Global Config > Default Config
Error Handling
apiClient.get('/users/123', { mock: true })
.catch(error => {
if (error.response) {
console.log(error.response.status)
console.log(error.response.data)
} else {
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.