Gathering detailed insights and metrics for axios-mock-adapter
Gathering detailed insights and metrics for axios-mock-adapter
Gathering detailed insights and metrics for axios-mock-adapter
Gathering detailed insights and metrics for axios-mock-adapter
Axios adapter that allows to easily mock requests
npm install axios-mock-adapter
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
3,472 Stars
361 Commits
245 Forks
27 Watching
2 Branches
70 Contributors
Updated on 27 Nov 2024
Minified
Minified + Gzipped
JavaScript (96.23%)
TypeScript (3.77%)
Cumulative downloads
Total Downloads
Last day
-16.3%
323,181
Compared to previous day
Last week
-0%
1,713,677
Compared to previous week
Last month
15.8%
7,267,185
Compared to previous month
Last year
32.4%
67,035,320
Compared to previous year
2
1
8
Axios adapter that allows to easily mock requests
Using npm:
$ npm install axios-mock-adapter --save-dev
It's also available as a UMD build:
axios-mock-adapter works on Node as well as in a browser, it works with axios v0.17.0 and above.
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 );
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 binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
1 existing vulnerabilities detected
Details
Reason
9 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 7
Reason
Found 3/15 approved changesets -- score normalized to 2
Reason
dependency not pinned by hash detected -- score normalized to 2
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
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 More