Skip to content

Instantly share code, notes, and snippets.

@amoHoban
Created March 7, 2019 12:34
Show Gist options
  • Save amoHoban/20297239aca22e77c1528f5d9c3386af to your computer and use it in GitHub Desktop.
Save amoHoban/20297239aca22e77c1528f5d9c3386af to your computer and use it in GitHub Desktop.
mock fetch calls, overriding the response (e.g. Server down during development)
// 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