@pivoto/mock
v1.0.0
Published
扩展`mockjs`对`xhr`、`fetch`的模拟方法,示例
Downloads
118
Readme
扩展mockjs
对xhr
、fetch
的模拟方法,示例
import mock from '@mmp/mock'
mock.setup({
timeout: '100-200'
})
mock.mock(/\/api\/.*/, () => {
return {response: {success: true, data: {}}, status: 200, statusText: 'OK', headers: {'x-api': 1}}
})
mock.mock(/\/test\/.*/, () => {
return {response: {success: true, data: {}}, status: 200, statusText: 'OK', headers: {'x-test': 1}}
})
function test1() {
window.fetch('/api/xxx').then(r => {
console.log(r)
r.json().then(d => {
console.log(d)
})
})
}
function test2() {
window.fetch('/test/xxx').then(r => {
console.log(r)
r.text().then(d => {
console.log(d)
})
})
}
function test3() {
let responseType = 'json'
let request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (!request || request.readyState !== 4) {
return;
}
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
return;
}
let responseHeaders = {}
request.getAllResponseHeaders().split('\n').forEach((e, i) => {
let kv = e.split(':', 2)
responseHeaders[kv[0]] = kv[1]
});
let responseData = responseType === 'json' ? request.response : request.responseText;
let response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
request: request
};
console.log(response)
}
request.open('post', '/api/xxxxx')
request.responseType = responseType
request.send('test')
}