How to mock a Fetch API request with Jest and TypeScript
You probably had some problems testing async functions like Fetch API and XMLHttpRequest (XHR). I will show you the best way to test a code that uses these fetch methods.
In this example, I’m using TypeScript, but you can use the same strategy with just JavaScript as well.
Mocking Fetch API
This piece of code uses Fetch API to fetch some resources across the network. In this example, it fetches a user’s repositories from GitHub.
The following helper function gets the global object in the current environment. Basically, it checks if the global
variable exists, if it’s not, it will verify the window
or the self
variables as well.
Next, the mockFetch
function uses the getGlobalObject
to create a mock function…