Skip to content

Instantly share code, notes, and snippets.

@neodigm
Created May 17, 2021 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neodigm/2cfed8cf6e3e24a0fcca19f8f4d692b4 to your computer and use it in GitHub Desktop.
Save neodigm/2cfed8cf6e3e24a0fcca19f8f4d692b4 to your computer and use it in GitHub Desktop.
window fetch overload
const {fetch: origFetch} = window;
window.fetch = async (...args) => {
console.log("fetch called with args:", args);
const response = await origFetch(...args);
/* work with the cloned response in a separate promise
chain -- could use the same chain with `await`. */
response
.clone()
.json()
.then(body => console.log("intercepted response:", body))
.catch(err => console.error(err))
;
/* the original response can be resolved unmodified: */
//return response;
/* or mock the response: */
return {
ok: true,
status: 200,
json: async () => ({
userId: 1,
id: 1,
title: "Mocked!!",
completed: false
})
};
};
// test it out with a typical fetch call
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(response => response.json())
.then(json => console.log("original caller received:", json))
.catch(err => console.error(err))
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment