Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@B-Esmaili B-Esmaili commented Jun 9, 2021

Greate! Thanks for sharing.

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