Created
March 7, 2019 12:34
-
-
Save amoHoban/20297239aca22e77c1528f5d9c3386af to your computer and use it in GitHub Desktop.
mock fetch calls, overriding the response (e.g. Server down during development)
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
// e.g. mockFetch({'avengers/me': {'name': "iron man", 'rank': 2}}) | |
function mockFetch(urlResponseMap) { | |
window.fetchOriginal = window.fetch | |
window.fetch = (...params) => { | |
const lookFor = Object.keys(urlResponseMap); | |
const url = typeof params[0] == 'object' ? params[0].url : params[0]; | |
lookFor.forEach(str => { | |
const returnObj = urlResponseMap[str]; | |
if (url.includes(str)) { | |
console.log("returning mock response for ", str) | |
return new Promise(() => ( | |
{ | |
...returnObj, | |
toString: () => (returnObj), | |
json: () => (returnObj) | |
} | |
)) | |
} | |
else { | |
const arg = typeof params == 'object' ? Object.assign({}, params) : params; | |
window.fetch = window.fetchOriginal; | |
window.fetchOriginal.apply(window, arg) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment