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.

request.js

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

    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 => {
      expect(response).toEqual({
        data: {},
      });
    });
    expect(mockAxios.request).toHaveBeenCalledWith({
      method: 'get',
      url: '/test'
    });
    expect(mockAxios.request).toHaveBeenCalledTimes(1);
    expect(consoleErrorSpy).not.toHaveBeenCalled();
    done();
  });

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.

Discussion (5)

Collapse
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

Collapse
richierunner profile image
Richie

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

Collapse
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.

Collapse
bmuthoga profile image
andela-bm

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

Collapse
hashinclude72 profile image
Shubham Jaswal

bruuuuuuuuuuuuuuuuuuh ... read comments like half hour later