Axios

Learn how to properly mock API calls made with the popular Axios library.

Why do we mock Axios?

Axios, one of the most popular packages available on the npm and Yarn registries, is “a Promise based HTTP client for the browser and node.js.” In other words, we can use it to make API calls both from our client and from our server, as long as they are both in JavaScript. It’s extremely helpful, abstracting much of the lengthy manual configurations of request creation into helper methods, such as axios.get, axios.head, and axios.request. This makes our code more readable and easier to navigate.

In our test suites, though, we don’t actually want our Axios functions to run. Perhaps we’d want the setting of headers to execute so that we can test that we are in fact setting the headers as we expect to be. However, if we don’t test it, we would be making GET and POST requests into the abyss. With no actual server to request against, our calls hang, awaiting a response and slowing down our entire test run, only to fail upon completion. Even if we do have access to the API, e.g., a public API with no authorization requirements (or simple basic auth that can be set from our test suite), we still don’t want to do this. It is inefficient and difficult to manage. It also leaves our tests open to failing due to external causes, such as the API being down temporarily.

Get hands-on with 1200+ tech skills courses.