The following module will allow you to make fake HTTP requests:
Code:
const fakeHttpRequest = {};
fakeHttpRequest.success = (url, options, delay, data) => {
delay = delay || 0;
if (!Number.isInteger(delay)) {
const errorMessage = 'delay: Expected an integer';
throw new TypeError(errorMessage);
}
data = data || {};
return new Promise((resolve, reject) => {
setTimeout(() => {
const response = {
ok: true,
status: 200,
json: () => Promise.resolve({ data }),
};
resolve(response);
}, 2000);
});
};
fakeHttpRequest.fail = (url, options, delay, data) => {
delay = delay || 0;
if (!Number.isInteger(delay)) {
const errorMessage = 'delay: Expected an integer';
throw new TypeError(errorMessage);
}
data = data || {};
return new Promise((resolve, reject) => {
setTimeout(() => {
const response = {
ok: true,
status: 200,
json: () => Promise.reject({ data }),
};
resolve(response);
}, 2000);
});
};
export { fakeHttpRequest };
Usage:
Code:
<script type="module" src="./fake-http-request.js"></script>
<script>
import { fakeHttpRequest } from './fake-http-request.js';
window.addEventListener('load', () => {
fakeHttpRequest.success('./api/data', null, 2500, { response: 'hello world' })
.then(response => response.json())
.then(data => {
console.log(data.response);
})
.catch(error => console.error(error));
}, false);
</script>