Axios adapter that allows to easily mock requests
Installations
npm install axios-mock-adapter
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
20.15.0
NPM Version
10.7.0
Score
92.4
Supply Chain
99.5
Quality
79.6
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (96.23%)
TypeScript (3.77%)
Love this project? Help keep it running — sponsor us today! 🚀
Developer
ctimmerm
Download Statistics
Total Downloads
243,582,653
Last Day
351,036
Last Week
1,667,650
Last Month
7,120,275
Last Year
71,657,692
GitHub Statistics
MIT License
3,486 Stars
361 Commits
250 Forks
27 Watchers
2 Branches
67 Contributors
Updated on Feb 12, 2025
Bundle Size
7.85 kB
Minified
2.87 kB
Minified + Gzipped
Package Meta Information
Latest Version
2.1.0
Package Id
axios-mock-adapter@2.1.0
Unpacked Size
66.27 kB
Size
16.12 kB
File Count
13
NPM Version
10.7.0
Node Version
20.15.0
Published on
Oct 09, 2024
Total Downloads
Cumulative downloads
Total Downloads
243,582,653
Last Day
6.5%
351,036
Compared to previous day
Last Week
1%
1,667,650
Compared to previous week
Last Month
52.2%
7,120,275
Compared to previous month
Last Year
35.6%
71,657,692
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
2
Peer Dependencies
1
Dev Dependencies
8
axios-mock-adapter
Axios adapter that allows to easily mock requests
Installation
Using npm:
$ npm install axios-mock-adapter --save-dev
It's also available as a UMD build:
- https://unpkg.com/axios-mock-adapter/dist/axios-mock-adapter.js
- https://unpkg.com/axios-mock-adapter/dist/axios-mock-adapter.min.js
axios-mock-adapter works on Node as well as in a browser, it works with axios v0.17.0 and above.
Example
Mocking a GET
request
1const axios = require("axios"); 2const AxiosMockAdapter = require("axios-mock-adapter"); 3 4// This sets the mock adapter on the default instance 5const mock = new AxiosMockAdapter(axios); 6 7// Mock any GET request to /users 8// arguments for reply are (status, data, headers) 9mock.onGet("/users").reply(200, { 10 users: [{ id: 1, name: "John Smith" }], 11}); 12 13axios.get("/users").then(function (response) { 14 console.log(response.data); 15});
Mocking a GET
request with specific parameters
1const axios = require("axios"); 2const AxiosMockAdapter = require("axios-mock-adapter"); 3 4// This sets the mock adapter on the default instance 5const mock = new AxiosMockAdapter(axios); 6 7// Mock GET request to /users when param `searchText` is 'John' 8// arguments for reply are (status, data, headers) 9mock.onGet("/users", { params: { searchText: "John" } }).reply(200, { 10 users: [{ id: 1, name: "John Smith" }], 11}); 12 13axios 14 .get("/users", { params: { searchText: "John" } }) 15 .then(function (response) { 16 console.log(response.data); 17 });
When using params
, you must match all key/value pairs passed to that option.
To add a delay to responses, specify a delay amount (in milliseconds) when instantiating the adapter
1// All requests using this instance will have a 2 seconds delay: 2const mock = new AxiosMockAdapter(axiosInstance, { delayResponse: 2000 });
You can restore the original adapter (which will remove the mocking behavior)
1mock.restore();
You can also reset the registered mock handlers with resetHandlers
1mock.resetHandlers();
You can reset both registered mock handlers and history items with reset
1mock.reset();
reset
is different from restore
in that restore
removes the mocking from the axios instance completely,
whereas reset
only removes all mock handlers that were added with onGet, onPost, etc. but leaves the mocking in place.
Mock a low level network error
1// Returns a failed promise with Error('Network Error'); 2mock.onGet("/users").networkError(); 3 4// networkErrorOnce can be used to mock a network error only once 5mock.onGet("/users").networkErrorOnce();
Mock a network timeout
1// Returns a failed promise with Error with code set to 'ECONNABORTED' 2mock.onGet("/users").timeout(); 3 4// timeoutOnce can be used to mock a timeout only once 5mock.onGet("/users").timeoutOnce();
Passing a function to reply
1mock.onGet("/users").reply(function (config) { 2 // `config` is the axios config and contains things like the url 3 4 // return an array in the form of [status, data, headers] 5 return [ 6 200, 7 { 8 users: [{ id: 1, name: "John Smith" }], 9 }, 10 ]; 11});
Passing a function to reply
that returns an axios request, essentially mocking a redirect
1mock.onPost("/foo").reply(function (config) { 2 return axios.get("/bar"); 3});
Using a regex
1mock.onGet(/\/users\/\d+/).reply(function (config) { 2 // the actual id can be grabbed from config.url 3 4 return [200, {}]; 5});
Using variables in regex
1const usersUri = "/users"; 2const url = new RegExp(`${usersUri}/*`); 3 4mock.onGet(url).reply(200, users);
Specify no path to match by verb alone
1// Reject all POST requests with HTTP 500 2mock.onPost().reply(500);
Chaining is also supported
1mock.onGet("/users").reply(200, users).onGet("/posts").reply(200, posts);
.replyOnce()
can be used to let the mock only reply once
1mock 2 .onGet("/users") 3 .replyOnce(200, users) // After the first request to /users, this handler is removed 4 .onGet("/users") 5 .replyOnce(500); // The second request to /users will have status code 500 6// Any following request would return a 404 since there are 7// no matching handlers left
Mocking any request to a given url
1// mocks GET, POST, ... requests to /foo 2mock.onAny("/foo").reply(200);
.onAny
can be useful when you want to test for a specific order of requests
1// Expected order of requests: 2const responses = [ 3 ["GET", "/foo", 200, { foo: "bar" }], 4 ["POST", "/bar", 200], 5 ["PUT", "/baz", 200], 6]; 7 8// Match ALL requests 9mock.onAny().reply((config) => { 10 const [method, url, ...response] = responses.shift(); 11 if (config.url === url && config.method.toUpperCase() === method) 12 return response; 13 // Unexpected request, error out 14 return [500, {}]; 15});
Requests that do not map to a mock handler are rejected with a HTTP 404 response. Since
handlers are matched in order, a final onAny()
can be used to change the default
behaviour
1// Mock GET requests to /foo, reject all others with HTTP 500 2mock.onGet("/foo").reply(200).onAny().reply(500);
Mocking a request with a specific request body/data
1mock.onPut("/product", { id: 4, name: "foo" }).reply(204);
Using an asymmetric matcher, for example Jest matchers
1mock 2 .onPost( 3 "/product", 4 { id: 1 }, 5 { 6 headers: expect.objectContaining({ 7 Authorization: expect.stringMatching(/^Basic /), 8 }) 9 } 10 ) 11 .reply(204);
Using a custom asymmetric matcher (any object that has a asymmetricMatch
property)
1mock 2 .onPost("/product", { 3 asymmetricMatch: function (actual) { 4 return ["computer", "phone"].includes(actual["type"]); 5 }, 6 }) 7 .reply(204);
.passThrough()
forwards the matched request over network
1// Mock POST requests to /api with HTTP 201, but forward 2// GET requests to server 3mock 4 .onPost(/^\/api/) 5 .reply(201) 6 .onGet(/^\/api/) 7 .passThrough();
Recall that the order of handlers is significant
1// Mock specific requests, but let unmatched ones through 2mock 3 .onGet("/foo") 4 .reply(200) 5 .onPut("/bar", { xyz: "abc" }) 6 .reply(204) 7 .onAny() 8 .passThrough();
Note that passThrough
requests are not subject to delaying by delayResponse
.
If you set onNoMatch
option to passthrough
all requests would be forwarded over network by default
1// Mock all requests to /foo with HTTP 200, but forward
2// any others requests to server
3const mock = new AxiosMockAdapter(axiosInstance, { onNoMatch: "passthrough" });
4
5mock.onAny("/foo").reply(200);
Using onNoMatch
option with throwException
to throw an exception when a request is made without match any handler. It's helpful to debug your test mocks.
1const mock = new AxiosMockAdapter(axiosInstance, { onNoMatch: "throwException" }); 2 3mock.onAny("/foo").reply(200); 4 5axios.get("/unexistent-path"); 6 7// Exception message on console: 8// 9// Could not find mock for: 10// { 11// "method": "get", 12// "url": "http://localhost/unexistent-path" 13// }
As of 1.7.0, reply
function may return a Promise:
1mock.onGet("/product").reply(function (config) { 2 return new Promise(function (resolve, reject) { 3 setTimeout(function () { 4 if (Math.random() > 0.1) { 5 resolve([200, { id: 4, name: "foo" }]); 6 } else { 7 // reject() reason will be passed as-is. 8 // Use HTTP error status code to simulate server failure. 9 resolve([500, { success: false }]); 10 } 11 }, 1000); 12 }); 13});
Composing from multiple sources with Promises:
1const normalAxios = axios.create(); 2const mockAxios = axios.create(); 3const mock = new AxiosMockAdapter(mockAxios); 4 5mock 6 .onGet("/orders") 7 .reply(() => 8 Promise.all([ 9 normalAxios.get("/api/v1/orders").then((resp) => resp.data), 10 normalAxios.get("/api/v2/orders").then((resp) => resp.data), 11 { id: "-1", content: "extra row 1" }, 12 { id: "-2", content: "extra row 2" }, 13 ]).then((sources) => [ 14 200, 15 sources.reduce((agg, source) => agg.concat(source)), 16 ]) 17 );
History
The history
property allows you to enumerate existing axios request objects. The property is an object of verb keys referencing arrays of request objects.
This is useful for testing.
1describe("Feature", () => { 2 it("requests an endpoint", (done) => { 3 const mock = new AxiosMockAdapter(axios); 4 mock.onPost("/endpoint").replyOnce(200); 5 6 feature 7 .request() 8 .then(() => { 9 expect(mock.history.post.length).toBe(1); 10 expect(mock.history.post[0].data).toBe(JSON.stringify({ foo: "bar" })); 11 }) 12 .then(done) 13 .catch(done.fail); 14 }); 15});
You can clear the history with resetHistory
1mock.resetHistory();

No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
1 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
Reason
Found 3/15 approved changesets -- score normalized to 2
Reason
dependency not pinned by hash detected -- score normalized to 2
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:24: update your workflow using https://app.stepsecurity.io/secureworkflow/ctimmerm/axios-mock-adapter/node.js.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:26: update your workflow using https://app.stepsecurity.io/secureworkflow/ctimmerm/axios-mock-adapter/node.js.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:39: update your workflow using https://app.stepsecurity.io/secureworkflow/ctimmerm/axios-mock-adapter/node.js.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/node.js.yml:41: update your workflow using https://app.stepsecurity.io/secureworkflow/ctimmerm/axios-mock-adapter/node.js.yml/master?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/node.js.yml:32
- Info: 0 out of 4 GitHub-owned GitHubAction dependencies pinned
- Info: 2 out of 3 npmCommand dependencies pinned
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/node.js.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 23 are checked with a SAST tool
Score
3.7
/10
Last Scanned on 2025-02-10
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to axios-mock-adapter
@types/axios-mock-adapter
Stub TypeScript definitions entry for axios-mock-adapter, which provides its own types definitions
axios-mock-shim
A plugin build for easily using axios-mock-adapter with axios
openapi-axios-mock-adapter
for axios-mock-adapter
@maprox/axios-mock-adapter
Axios adapter that allows to easily mock requests