Registry / testing / axios-mock-server

axios-mock-server

JSON →
library0.19.1jsnpmunverified

axios-mock-server is a development dependency designed to provide a RESTful mock server that integrates directly with Axios, removing the need for a separate backend server during client-side development and testing. It enables developers to define API endpoints as JavaScript or TypeScript files, utilizing an auto-routing mechanism that mirrors Nuxt.js's file-system-based routing. This library facilitates mocking HTTP requests made via Axios in both browser (SPA) and Node.js environments. The current stable version is 0.19.1, with a consistent cadence of patch and minor releases focusing on bug fixes, dependency updates, and feature enhancements. Its key differentiators include its serverless nature, intuitive file-based routing for mock definitions, and robust TypeScript support, making it an efficient tool for API mocking.

npm install axios-mock-server
INSTALL
IMPORT
SIG · AXIOS-MOCK-SERVER
A
axios-mock-server
testingjavascriptv0.19.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

factory
import { factory } from 'axios-mock-server';
const { factory } = require('axios-mock-server');
Used to create a mock instance and connect it to a specific Axios instance.
connectToAxios
import { connectToAxios } from 'axios-mock-server';
import connectToAxios from 'axios-mock-server';
Main entry point for connecting a compiled API definition to an Axios instance, as demonstrated in the official tutorial. This is a named export.
setupWorker
import { setupWorker } from 'axios-mock-server/node';
import { setupWorker } from 'axios-mock-server';
Used for global request interception in Node.js environments. A separate '/browser' entry point exists for browser-specific usage. This is similar to Mock Service Worker (MSW) setup for global intercepts. Ensure you import from the correct environment subpath.

This quickstart demonstrates how to define a mock API endpoint, build it using the CLI, and then connect it to an Axios instance in your application to intercept and respond to HTTP requests.

// 1. Install dependencies (in your project root) // npm install axios axios-mock-server --save-dev // 2. Create a mock directory and define your API endpoint // file: mocks/users/_userId.js const users = [{ id: 0, name: 'foo' }, { id: 1, name: 'bar' }]; module.exports = { get({ values }) { // values.userId is dynamically parsed from the URL, e.g., /users/0 const userId = Number(values.userId); const user = users.find(u => u.id === userId); if (user) { return [200, user]; } return [404, { message: 'User not found' }]; }, post({ data }) { // Simulate adding a new user if (!data || !data.name) return [400, { message: 'Name is required' }]; const newUser = { id: users.length, name: data.name }; users.push(newUser); return [201, newUser]; } }; // 3. Build the mock API (run this command in your terminal) // npx axios-mock-server build --input mocks --output dist/mock.js // 4. In your application file (e.g., src/main.js), import and use the mock import axios from 'axios'; import { connectToAxios } from 'axios-mock-server'; import api from '../dist/mock'; // Adjust path based on your project structure // Create an Axios instance const client = axios.create({ baseURL: 'http://localhost:8080' }); // Example base URL // Connect the mock API to the Axios instance connectToAxios(api, client); async function fetchData() { console.log('Attempting to fetch user 0...'); try { const response = await client.get('/users/0'); console.log('GET /users/0 response:', response.data); // Expected: { id: 0, name: 'foo' } } catch (error) { console.error('Error fetching user 0:', error.response?.data || error.message); } console.log('\nAttempting to post a new user...'); try { const response = await client.post('/users', { name: 'baz' }); console.log('POST /users response:', response.data); // Expected: { id: 2, name: 'baz' } } catch (error) { console.error('Error posting new user:', error.response?.data || error.message); } console.log('\nAttempting to fetch a non-existent user 99...'); try { const response = await client.get('/users/99'); console.log('GET /users/99 response:', response.data); } catch (error) { console.error('Error fetching user 99 (expected 404):', error.response?.data || error.message); } } fetchData();
Debug
Known issues
gotchaWhen defining mock API endpoints, ensure you return responses as `[statusCode, data]` arrays. Directly returning `data` or other formats without the status code will lead to unexpected behavior. For TypeScript, explicitly asserting the `MockResponse` type for asynchronous responses is often necessary.
fix
Always return `[statusCode, data]` from your mock methods. For TypeScript, use `return [200, data] as MockResponse;`
affects: >=0.1.0
breakingThe `axios` package itself experienced a critical supply chain attack on March 31, 2026, where malicious versions `axios@1.14.1` and `axios@0.30.4` were published. These versions contained a Remote Access Trojan. While `axios-mock-server` is a distinct package, any project using affected `axios` versions is at risk.
fix
Immediately audit your `node_modules` and lock files for `axios@1.14.1` or `axios@0.30.4` and the `plain-crypto-js` dependency. Pin `axios` to safe versions (`axios@1.14.0` or `axios@0.30.3`), update all credentials, and rebuild from a known-good state. Use `npm ci --ignore-scripts` in CI/CD.
affects: axios@1.14.1, axios@0.30.4
gotchaThe mock definition files (e.g., `mocks/users/_userId.js`) typically use CommonJS `module.exports`, while client-side application code usually uses ESM `import` statements. This requires a build step for the mock definitions (e.g., `npx axios-mock-server build`) to generate a compatible module that can be imported by your application.
fix
Follow the tutorial's `build` step: `npx axios-mock-server build --input mocks --output dist/mock.js` and then `import api from '../dist/mock';` in your application.
affects: >=0.1.0
deprecatedSecurity vulnerability detected in `ini` dependency (from 1.3.5 to 1.3.7) and `acorn` (from 6.4.0 to 6.4.1) in older versions of `axios-mock-server`. While these are dev dependencies for the mock server itself, keeping dependencies up-to-date is crucial for overall project security.
fix
Upgrade `axios-mock-server` to version `0.19.1` or newer to ensure these transitive dependencies are patched.
affects: <0.19.1
Errors
Common errors & fixes
The expected type comes from property 'get' which is declared here on type 'MockMethods' error in TypeScript
In TypeScript, when returning asynchronous responses from mock methods, the inferred type may not match the `MockMethods` expectation if you return an array directly.
fix
Assert the response as `MockResponse` or ensure the response is an object. Example: `return [200, data] as MockResponse;` or if returning an object, ensure it's compatible with `MockResponse`.
Upgrade
Version history
0.19.1latest on npm
Audit
Dependencies
axiosrequiredThis library mocks requests made by axios; it's a peer dependency for the consuming application.
Agent activity
22 hits · last 30 days
node
18
OpenAI (training)
1
Resources
axios-mock-server — npm install axios-mock-server · libregistry