Skip to content

Instantly share code, notes, and snippets.

@miladd3
Created April 17, 2023 14:39
Show Gist options
  • Save miladd3/8d2c09d92c215bd5dc1e65bf8e5c84e3 to your computer and use it in GitHub Desktop.
Save miladd3/8d2c09d92c215bd5dc1e65bf8e5c84e3 to your computer and use it in GitHub Desktop.
mock http calls with payload
/**
* for mocking api with a timeout to test loadings
*
* @example
*
* const someEvent = async () => {
* try {
* await mock({mockedKey: '' } ,true, 1000);
* await mock({mockedKey: '' });
* await mock({mockedKey: '' } ,true);
* } catch (e) {
* console.log(e.message);
* }
* }
*
* @param {unknown} payload the data that you want to send with this api
* @param {boolean} success if it will be successfully
* @param {number} timeout
* @returns {Promise<unknown>}
*/
export const mock = (payload, success = true, timeout = 800) => new Promise((resolve, reject) => {
setTimeout(() => {
if (success) {
resolve(payload);
} else {
// eslint-disable-next-line prefer-promise-reject-errors
reject({ message: 'Error' });
}
}, timeout);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment