Intercept Axios
requests and return Mock
data for testing and development.
(mockDatas: MockConfig[], mockOptions?: MockOptions | undefined) => void
: Mock Axios
mockDatas
: an array, whenaxios
requests, it will check the correspondingurl
,method
, and return the correspondingresponse
data when it matches.url
:string | RegExp
type, the url to match, can be a string or a regular expression. When it is a string, it will check whether theurl
requested byaxios
contains theurl
. When it is a regular expression, it will check whether theurl
requested byaxios
matches theurl
.method
:GET
|POST
|PUT
|DELETE
|PATCH
, default is empty to match all types of requeststimeout
:number
type, default value:300
, unit:ms
, the delay time of returning the resultresponse
: the data object of the returned mockadapter
: custom adapter function, refer to adapter, this function accepts two parameters, one isconfig
, one is It is the matchedmockData
object, and the return value is the data object ofresponse
. Through this parameter, you can define the returned data more freely (such as verifying interface permissions).
mockOptions
isUseDefaultAdapter
:Boolean
, defaults totrue
, if enabled, requests that are not intercepted will be sent in the default mode ofaxios
isEffect
:Boolean
, default istrue
, with this parameter you can enablemockAxios
in test environment and disablemockAxios
in production environmentisLog
:Boolean
, the default istrue
, whether to print the request log ofmockAxios
logger
:Function
, replace the default log function
import { mockAxios } from '@ckpack/mock-axios';
mockAxios([{
url: 'https://test.com/v1/user/1',
response: {
data: {
id: 1,
name: 'admin',
},
},
}], {
isEffect: process.env.NODE_ENV === 'development',
});
(mockDatas: MockConfig[]) => MockConfig[]
: Helper function for constructing mockDatas. This function can be used with the IDE to get type hints
mockDatas
: Same as themockDatas
parameter ofmockAxios
.
import { defineConfig } from '@ckpack/mock-axios';
const mockDatas = defineConfig([
{
url: 'https://test.com/v1/user/1',
response: {
data: {
id: 1,
name: 'admin',
},
},
},
]);
// mockAxios.js
import { mockAxios } from '@ckpack/mock-axios';
mockAxios([{
method: 'GET',
url: /https:\/\/test.com\/v1\/user\/\d+/,
response: {
data: [{
id: 1,
name: 'admin',
}],
},
}, {
method: 'POST',
url: 'https://test.com/v1/user/create',
adapter: (axiosConfig) => {
return {
data: axiosConfig.data,
};
},
}]);
in other files
import axios from 'axios';
import './mockAxios.js';
await axios.get('https://test.com/v1/user/1');
// return { data: [{ id: 1, name: 'admin' }] }
await axios.post('https://test.com/v1/user/create', {
id: 1,
name: 'admin',
});
// return { data: { id: 1, name: 'admin' } }
await axios.post('https://test.com/v1/user/create', {
id: 2,
name: 'test',
});
// return { data: { id: 2, name: 'test' } }