fetch vs axios using enzyme & jest

13 January 2019 — Written by kevin phung
#hack reactor#axios#react#enzyme#jest#kevin phung#javascript

The team and I went through rendering our components and services with minimal issues. It’s when we ran into Component Testing where we had to put our thinking caps on and figure out which test suite and supporting utility would best suit our application needs. We chose Jest which is an open source Facebook testing suite as well as Airbnb’s testing utility Enzyme which supports React’s library.

My fellow team engineers have Medium articles that document setting up these tests and what problems they encountered implementing the tests here and here, so I won’t dive deep on those topics.

Which leads to the topic of my post, the decision behind switching from the standard browser Fetch API to using third-party Axios for HTTP requests. Initially, I made the conscious decision to avoid any third-party libraries if I can use any browser built-ins. I have become comfortable using Fetch API in past projects and had no issues grabbing data from our database. It did not make sense to use a third party library like JQuery if all I was using it for was Ajax calls. I wanted to minimize bloat on the client side and it worked well initially.

The issue came when Fetch API was not available on the backend. I had to install a third-party library called npm-fetch and import it globally in order for the test suite to use it. Although the tests passed, I had a few TypeError issues such as ‘Only absolute URLs are supported’. I was not able to find any solutions online thus far but perhaps when we deploy and use a non-local URL, the issue would resolve.

The decision to switch to Axios was made easier when I realized Fetch API actually makes you do an additional step to handle JSON data. Axios automatically transforms JSON data while .fetch() requires you to request the data then call the .json() method on the response.

Lastly, Axios made HTTP requests in Node without giving me any Typescript errors. Overall, I learned a ton and will report back with any tradeoffs I encounter as we march towards the finish line!