0.0.6 • Published 4 years ago
@ckpack/mock-axios v0.0.6
mock-axios
Intercept Axios requests and return Mock data for testing and development.
API
mockAxios
(mockDatas: MockConfig[], mockOptions?: MockOptions | undefined) => void: Mock Axios
mockDatas: an array, whenaxiosrequests, it will check the correspondingurl,method, and return the correspondingresponsedata when it matches.url:string | RegExptype, the url to match, can be a string or a regular expression. When it is a string, it will check whether theurlrequested byaxioscontains theurl. When it is a regular expression, it will check whether theurlrequested byaxiosmatches theurl.method:GET|POST|PUT|DELETE|PATCH, default is empty to match all types of requeststimeout:numbertype, 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 matchedmockDataobject, 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).
mockOptionsisUseDefaultAdapter:Boolean, defaults totrue, if enabled, requests that are not intercepted will be sent in the default mode ofaxiosisEffect:Boolean, default istrue, with this parameter you can enablemockAxiosin test environment and disablemockAxiosin production environmentisLog:Boolean, the default istrue, whether to print the request log ofmockAxioslogger: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',
});defineConfig
(mockDatas: MockConfig[]) => MockConfig[]: Helper function for constructing mockDatas. This function can be used with the IDE to get type hints
mockDatas: Same as themockDatasparameter ofmockAxios.
import { defineConfig } from '@ckpack/mock-axios';
const mockDatas = defineConfig([
{
url: 'https://test.com/v1/user/1',
response: {
data: {
id: 1,
name: 'admin',
},
},
},
]);Example
// 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' } }