Gathering detailed insights and metrics for axios-mock-shim
Gathering detailed insights and metrics for axios-mock-shim
npm install axios-mock-shim
Typescript
Module System
Node Version
NPM Version
68.2
Supply Chain
97.8
Quality
75.7
Maintenance
50
Vulnerability
100
License
TypeScript (85.74%)
JavaScript (14.26%)
Verify real, reachable, and deliverable emails with instant MX records, SMTP checks, and disposable email detection.
Total Downloads
5,071
Last Day
1
Last Week
3
Last Month
9
Last Year
379
MIT License
47 Commits
1 Watchers
14 Branches
1 Contributors
Updated on Sep 11, 2020
Minified
Minified + Gzipped
Latest Version
1.2.4
Package Id
axios-mock-shim@1.2.4
Unpacked Size
48.42 kB
Size
14.85 kB
File Count
7
NPM Version
6.14.8
Node Version
12.12.0
Cumulative downloads
Total Downloads
Last Day
0%
1
Compared to previous day
Last Week
50%
3
Compared to previous week
Last Month
-85.5%
9
Compared to previous month
Last Year
-50.9%
379
Compared to previous year
2
A plugin build for easily using axios-mock-adapter with axios.
Be sure to install axios
& axios-mock-adapter
before using this plugin.
1npm i axios-mock-shim 2// or 3yarn add axios-mock-shim
Import the plugin with two methods createAxios
, createAPIHandler
1import { createAxios, createAPIHandler } from 'axios-mock-shim';
Create Axios instance by given config.(default config or your custom config)
1const instance = createAxios(); 2 3// eg. 4instance.interceptors.response.use( 5 //... 6);
Create an AxiosRequest
object, which you can then use to define & call the api with specific mock data.
Note: Here must provide the
shimOptions
with at leastuseMock
property to tell the plugin whether using the mock-adapter.
1// Create an AxiosRequest with mock-adapter feature
2const api = createAPIHandler(instance, { useMock: true });
3
4// If you would like to use pure axios for production
5// You can set the option as below
6const api = createAPIHandler(instance, {
7 useMock: process.env.NODE_ENV !== 'production'
8});
Define your api logic & mock data with your AxiosRequest
object
method list: use
, with
, run
Define the api setting
method: http method
required
- type: string
svc: url path
required
- type: string
(note => without baseURL in axios instance)
data: params or data
optional
- type: object
Define the mock reply data.
If set
useMock
tofalse
, then no need to call this method.
Even call this method with
useMock
set byfalse
, it will still skip the mock feature automatically.
reply
method
required
- type: function(resolve, reject, config)
| array[statusCode: number, data]
> function will get three arguments, when using function type reply, please wrap your data into the first resolve
method in order to tell the plugin fullfill the Promise.Trigger the mock feature without calling run, by default, calling run
will trigger mock automatically, but sometimes we just want to define specific response with some params.
Just like
with
, ifuseMock
is set tofalse
, this method will skip the mock. avoiding you from callingmock
accidently in production mode.
1// Define some special situation response in dev 2if (process.env.NODE_ENV === 'development') { 3 const getInfos = [{ id: 3000 }, { test: 'This is test data', }]; 4 // trigger as folloing will let Shim plugin cache result for the params without calling a request 5 api.use('post', 'buy', getInfos[0]).with([400, getInfos[1]]).mock(); 6}
calling the mock with replyOnce
, with only mock request once.
Execute the AxiosRequest
, will execute real request by axios with auto checking for mock cache, if there's no cache yet, will mock & cache the result.
1export default { 2 3 // array type reply 4 getProfile() { 5 return api.use('get', 'solo/config', { params: { token: 1 } }).with([200, { 6 data: { 7 number: 10, 8 } 9 }]).run(); 10 }, 11 12 // function type reply 13 getSoloConfig() { 14 return api.use('post', 'profile', { id: 100 }) 15 .with((resolve, reject, config) => { 16 console.log(config); // mock-adapter's config 17 res([ 18 200, 19 { 20 data: { 21 name: 'Johnny', 22 money: 1000, 23 }, 24 } 25 ]); 26 }).run(); 27 }, 28 29 // If no need for mock 30 getNoMock() { 31 return api.use('get', 'nomock').run(); 32 }, 33};
Same behavior to run
, but would just mock once. same action as mockOnce
+ run
.
boolean
Required to set whether using mock-adapter. no default value.
boolean
Whether snakify keys in params or data in request. SnakifyKeys will run before the beforeRequest
, those config added by beforeRequest
will not auto apply the snakifyKeys
method.
Function
provide a way to dynamically inject some axios config each request, such as getting localStorage data into header
.
it will give you the default params to send to request.
if this property is not set, it will use the default params to call
The axios instance will call such as
axios.post()
but notaxios()
to send the request in order to match the mock-adapter's setting, usingaxios()
with sending data will cause 404 error!! See: Mock failed with 404 Error
1const api = createAPIHandler(instance, { 2 beforeRequest(config) { 3 const TOKEN = localStorage.getItem('TOKEN'); 4 return Object.assign(config, { 5 headers: { 6 'Content-Type': 'application/json', 7 'My-Token': TOKEN, 8 }, 9 }); 10 }, 11});
Function
You can specify what to do before getting the response, eg.
1const api = createAPIHandler(instance, {
2 useMock: true,
3 beforeResponse(response) {
4 return camelizeKeys(response.data);
5 },
6});
If you need to mock every request which without using with
to set its mock data, this property could that you define a fallback reply which will be used for all unhandled request.
This could only used with
useMock
set bytrue
;
1const api = createAPIHandler(instance, {
2 useMock: process.env.NODE_ENV !== 'production',
3 anyReply: [200, {
4 error: 'Unhandled request',
5 }],
6 // or
7 anyReply(resolve, reject, config) {
8 if (Math.random() > 0.1) return reject([404]);
9 return resolve([200, {
10 error: 'Unhandled request'
11 }]);
12 },
13});
1const mockDefaultConfig = { 2 delayResponse: 500, 3 onNoMatch: "passthrough", 4}
1const axiosDefaultConfig = { 2 baseURL: '/api/', 3 headers: { 4 'Content-Type': 'application/json', 5 }, 6 timeout: 5000, 7 withCredentials: true, 8}
1import { createAxios, createAPIHandler } from 'axios-mock-shim'; 2 3const instance = createAxios({ 4 xsrfCookieName: 'myToken', 5 xsrfHeaderName: 'MY-TOKEN', 6}); 7 8const api = createAPIHandler(instance, { 9 useMock: process.env.NODE_ENV === 'development', 10 snakifyData: true, 11 beforeRequest(params) { 12 const TOKEN = localStorage.getItem('MY-TOKEN'); 13 // console.log(params); 14 return Object.assign(params, { 15 headers: { 16 'MY-Token': TOKEN, 17 }, 18 }); 19 }, 20 beforeResponse(res) { 21 return utils.camelizeKeys(res.data); 22 }, 23}); 24 25// custom situation request 26// will not be bundled in production 27if (process.env.NODE_ENV === 'development') { 28 const getInfos = [{ id: 3000 }, { 29 test: 'This is test data', 30 }]; 31 // trigger as folloing will let Shim plugin cache result for the params 32 api.use('post', 'buy', getInfos[0]).with([400, getInfos[1]]).mock(); 33} 34 35export default { 36 getUser() { 37 return api.use('get', 'user').with([200, { 38 username: 'Johnny', 39 age: 3333, 40 }]).run(); 41 }, 42 postBuy({ id }) { 43 return api.use('post', 'buy', { 44 id, 45 }).with([200, { 46 normal: 'Here is normal response text', 47 }]).run(); 48 }, 49}
Copyright (c) 2020-present, Johnny Wang
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no SAST tool detected
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
40 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-03-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 More