Created
November 6, 2019 07:43
-
-
Save donaldpipowitch/f000f4d27d1b738ee05050af06e88eb0 to your computer and use it in GitHub Desktop.
Mock Upload Progress with axios-mock-adapter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Greate! Thanks for sharing.