DEV Community

Ben Weiser
Ben Weiser

Posted on

Testing Axios Requests With Jest

Let's say we have a simple async function that calls some remote data. We pass in our query and configuration object. To see an example of what can be passed through this request config see the Axios docs. My query in this case is just the url key in the config for example /user which could be an API end point. This function simply returns the data from axios (the actual response body from your endpoint). If we fail to get a response from our endpoint, the function is going to catch and we'll throw a console error.


export const fetchData = async (query, config
) => {
  try {
    const { data } = await axios.request({
      method: 'get',
      url: encodeURI(query),

    return data;
  } catch (e) {
    console.error('Could not fetchData', e);

Now let's create a new file request.spec.js we want to add two imports

import mockAxios from 'axios';
import { fetchData } from '../request';

In order to test this we need to use a mocked version of Axios which is conveniently imported from the core library. We're now ready to write our test

  it('should call a fetchData function', done => {
    fetchData('/test', {}).then(response => {
        data: {},
      method: 'get',
      url: '/test'

First we call then function with a test query and an empty config to ensure then test that our response is correct. Now we are testing mockAxios.request that it was called with the arguments we expected, that it was called only one time, and that our function did not throw an error. Finally we call the done() callback which let's just know our asynchronous operations are complete.

Top comments (5)

jtmorrisbytes profile image
Jordan Morris

So I just want to say for future reference here:
when you see 'import (somename) from "some-library", that gets whatever the default value is for that library. it will not matter what the name is, it will refer to the same default value
EX: import axios from "axios" is the same as
import mockAxios from "axios" but
import {axios} from "axios" is not the same as
import {mockAxios} from "axios

richierunner profile image

mockAxios is not a module from the core axios library. This should not be working.

clfposthumus profile image
C. Posthumus

Second this. This article is the worst type of BS I have seen in a long time. MockAxios should be a selft written implementation.

bmuthoga profile image

Was scratching my head wondering how?! this could possibly work, then I saw your comment, lol 😂

hashinclude72 profile image
Shubham Jaswal

bruuuuuuuuuuuuuuuuuuh ... read comments like half hour later