Skip to content

Instantly share code, notes, and snippets.

@sunnymui
Created March 4, 2022 06:20
Show Gist options
  • Save sunnymui/6144d879700fac39bd2a1dc5ef325902 to your computer and use it in GitHub Desktop.
Save sunnymui/6144d879700fac39bd2a1dc5ef325902 to your computer and use it in GitHub Desktop.
Mock a File Upload Server Response
const mockUpload = (files = []) =>
// return a promise so we can use async features like then/async/await
new Promise((resolve, reject) => {
// throw error if no files
if (!files || !files.length) {
return setTimeout(
() => reject(new Error('Not found')),
1250
);
}
// create a mock server response
const responseInit = { "status" : 200 , "statusText" : "OK" };
const fakeBlob = [JSON.stringify({response:"Test"}, null, 2)];
setTimeout(() => resolve(
new Response(new Blob(fakeBlob, {type : 'application/json'}), responseInit)
), 1250);
});
// do a fake upload
const uploadedFiles = [{thing: ""}];
mockUpload(uploadedFiles)
.then((res) => {
if (res.status !== 200) {
throw new Error('Service error!')
}
return res.blob();
})
.then((blob) => blob.text())
.then((result) => {
// upload happened successfully!
console.log('success', result);
}).catch((error) => {
// something went wrong with the api!
console.log(error.toString())
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment