Every once in a while we need to test API requests. Axios is one of the most popular JavaScript libraries to fetch data from remote APIs . Hence, we will use Axios for our data fetching example â however, the following tutorial should make it possible to exchange axios with any other data fetching library.
In this data fetching example with axios, we provide a query parameter to the function to search on Hacker News via its API . If the request is successful, we will return the response. If the request runs into a network error, the function will throw an error which we would have to capture outside of it.
Now we are going to use Jest to test the asynchronous data fetching function. Jest is used as a test runner (alternative: Mocha), but also as an assertion utility (alternative: Chai). In addition, it comes with utilities to spy, stub, and mock (asynchronous) functions. Thatâs how we will use Jest to mock Axios.
First, we will mock Axios with Jest. And second, we will give Axiosâ get method a mock implementation to resolve and reject a promise for both tests.
Last but not least, we will make our assertion with Jest in the cases of resolving the promise successfully or erroneously:
As bonus, we can also assert that Axiosâ get has been called with the correct URL:
Thatâs it for creating a Jest mock for Axios by going through one example. You can find this Axios mocking with Jest example in this GitHub repository . A few more thoughts: