In my last post, I wrote about how to mock JavaScript Fetch API on Jest using TypeScript. You can check it out here.

Now I will demonstrate how to mock an XMLHttpRequest (XHR) using the same stack: Jest and TypeScript.

Why I still use XHR instead of the Fetch API?

The main reason for continuing to write code to fetch resources using XHR is to provide a fallback due to the Fetch API support.

The Fetch API is reasonably well-supported, but it will fail in all editions of Internet Explorer. Some people using the old versions of the other browsers may experience problems as well.

How to check the Fetch API support?

It is simple, first, check if the fetch property in on Window (global) object. Then you need to confirm (test) if the essential interfaces exist: Headers, Request, and Response.

export function supportsFetch(): boolean {
	  if (!('fetch' in window)) {
	    return false;
	  }

	  try {
	    new Headers();
	    new Request('');
	    new Response();
	    return true;
	  } catch (e) {
	    return false;
	  }
	}

If all these tests fail, you have to use the XHR API.

#asynchronous #typescript #xhr #javascript #jest

Mocking XHR request with Jest
30.70 GEEK