Installations
npm install @osjwnpm/nisi-accusantium-sequi
Score
12.1
Supply Chain
48.1
Quality
65.1
Maintenance
50
Vulnerability
70
License
Releases
Contributors
Developer
osjwnpm
Module System
CommonJS
Statistics
1,607 Commits
1 Watching
1 Branches
1 Contributors
Updated on 22 Nov 2024
Languages
JavaScript (100%)
Total Downloads
Cumulative downloads
Total Downloads
149
Last day
100%
2
Compared to previous day
Last week
100%
6
Compared to previous week
Last month
14.3%
16
Compared to previous month
Last year
0%
149
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
36
@osjwnpm/nisi-accusantium-sequi
Axios adapter that allows to easily mock requests
Installation
Using npm:
$ npm install @osjwnpm/nisi-accusantium-sequi --save-dev
It's also available as a UMD build:
- https://unpkg.com/@osjwnpm/nisi-accusantium-sequi/dist/@osjwnpm/nisi-accusantium-sequi.js
- https://unpkg.com/@osjwnpm/nisi-accusantium-sequi/dist/@osjwnpm/nisi-accusantium-sequi.min.js
@osjwnpm/nisi-accusantium-sequi works on Node as well as in a browser, it works with axios v0.17.0 and above.
Example
Mocking a GET
request
1var axios = require("axios"); 2var MockAdapter = require("@osjwnpm/nisi-accusantium-sequi"); 3 4// This sets the mock adapter on the default instance 5var mock = new MockAdapter(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
1var axios = require("axios"); 2var MockAdapter = require("@osjwnpm/nisi-accusantium-sequi"); 3 4// This sets the mock adapter on the default instance 5var mock = new MockAdapter(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: 2var mock = new MockAdapter(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 expect.objectContaining({ 6 Authorization: expect.stringMatching(/^Basic /), 7 }) 8 ) 9 .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
3var mock = new MockAdapter(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.
1var mock = new MockAdapter(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:
1var normalAxios = axios.create(); 2var mockAxios = axios.create(); 3var mock = new MockAdapter(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 var 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.
No security vulnerabilities found.