A better way to mock Axios requests

Jorge Sanes
Condor Labs Engineering
2 min readSep 30, 2022

--

Up until a few days ago, the strategy I used for testing Axios requests was stubbing the module and returning the pieces of data I needed for the specific test, depending on the order of the requests, just like this:

In the previous snippet, requests is a function that calls Axios internally. In the component, there are 4 Axios requests:

  • The first one should return objectA
  • The second one should return objectB
  • The third one should return objectC
  • The fourth one should return objectB, too (For any weird reason)

Finally, I stub the get function of requests.

There are a few problems with this approach. First, the test is brittle; if you change the order of the requests or add a new one before any of the existing requests, the test will fail. Second, these tests are difficult to write and maintain, and also time consuming.

Luckily, Sinon offers another way to handle this. We can intercept the requests and then we can decide what to return depending on the URL. We don’t care about the order of the requests anymore!

This makes requests run a custom function instead of its own code. This allows us to get the URL as an argument and decide what to return depending on it. Note that the url comes as a String inside an Array; that’s why I used args[0].

Also, I used the String includes method but you can use Regular Expressions. You can opt to use a switch statement or any way you want to decide what to return.

I hope this article helps you on your tests writing endeavor, by making Axios requests easy and fun to stub. Thank you for reading.

Special thanks to Raúl Flórez for his help.

--

--