Mocking XHR request with Jest

Cesar William Alvarenga
The Startup
Published in
2 min readJun 27, 2020

--

Icons made by Eucalyp from www.flaticon.com

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 show how to mock an XMLHttpRequest (XHR) using the same stack: Jest and TypeScript.

Why I still use XHR instead of the Fetch API?

The principal 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.

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.

If all these tests fail, use the XHR API.

Let’s create the XHR mock!

--

--