Member-only story

How to test API calls

Daniel Afonso
3 min readMay 21, 2021

Hey everyone, recently I’ve seen a couple of questions regarding testing in the JavaScript ecosystem. Some of the questions are:

  • How to test API calls?
  • How to test axios?
  • How to test API calls fired from a useEffect hook?
  • How to test API calls from React Query?

During this blog post, I’ll give you all the ways that I know off about how to test API calls. For learning purposes, I’ll be using axios for my examples.

Scenario

Let’s imagine that we have a component that will fire an API request either being through the useEffect hook or a useQuery custom hook. When we received the data we destructure the name from it and render it. Here is a possible implementation

Now a typical way to test this would be to render our component and wait for the name returned from the API call to be rendered on the screen. Using React Testing Library the expected test should be the following:

--

--

Daniel Afonso
Daniel Afonso

Written by Daniel Afonso

Building content, code, and memes🦔💻 🥑Developer Advocate at OLX Group

No responses yet