Skip to content

Instantly share code, notes, and snippets.

@donaldpipowitch
Created November 6, 2019 07:43
Show Gist options
  • Save donaldpipowitch/f000f4d27d1b738ee05050af06e88eb0 to your computer and use it in GitHub Desktop.
Save donaldpipowitch/f000f4d27d1b738ee05050af06e88eb0 to your computer and use it in GitHub Desktop.
Mock Upload Progress with axios-mock-adapter
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
const mock = new MockAdapter(axios);
// this mocks a request which is always at 40% progress
mock.onPost('/upload-1').reply((config) => {
const total = 1024; // mocked file size
const progress = 0.4;
if (config.onUploadProgress) {
config.onUploadProgress({ loaded: total * progress, total });
}
return new Promise(() => {});
});
const sleep = (value: number) =>
new Promise((resolve) => setTimeout(resolve, value));
// this mocks a request which slowly resolves (20% progress every 500ms)
mock.onPost('/upload-2').reply(async (config) => {
const total = 1024; // mocked file size
for (const progress of [0, 0.2, 0.4, 0.6, 0.8, 1]) {
await sleep(500);
if (config.onUploadProgress) {
config.onUploadProgress({ loaded: total * progress, total });
}
}
return [200, null];
});
@B-Esmaili
Copy link

Greate! Thanks for sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment