Created
August 16, 2023 17:18
-
-
Save amitozdeol/d0c6d4715676aa169093fdb105b87827 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function mockFetch(config: { data?: any; headers?: any; json?: boolean; blob?: boolean; text?: boolean | string; status?: any; statusText?: string; error?: object | string; delay?: boolean }) { | |
const { data, headers, json = false, blob = false, text = false, status = 200, statusText = 'Success', error = '', delay = false } = config; | |
if (status >= 400) { | |
return jest.fn().mockImplementation(() => Promise.reject(error)); | |
} | |
const local_headers = { 'Content-type': 'application/json' }; | |
const res = new window.Response(data, { | |
status, | |
statusText, | |
headers: headers && Object.keys(headers).length === 0 ? local_headers : headers, | |
}); | |
if (blob) { | |
res.blob = () => Promise.resolve({} as any); | |
} | |
if (json) { | |
res.json = () => Promise.resolve(data); | |
} | |
if (text) { | |
res.text = () => Promise.resolve(JSON.stringify(Array.isArray(data) ? data[0] : data)); | |
} | |
if (delay) { | |
return jest.fn().mockImplementation( | |
() => | |
new Promise((result) => | |
setTimeout(() => { | |
result(res); | |
}, 200) | |
) | |
); | |
} else { | |
return jest.fn().mockImplementation(() => Promise.resolve(res)); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment