Mocking Axios

In this example, we send a mock request to Axios.

Before we move on to the actual tests, we have to lay out some infrastructure to mock the axios library. With Jest, we can create overrides for any imported library using the built-in mocking features.

We need to create a __mocks__ directory at the same level in the project as the node_modules directory. Inside we can place files named to override any Node package. For example, the axios.js file will override import axios from 'axios' in our project.

Next, we need to update the package.json file to include a jest key with an axios property pointing to the axios mock directory:

"jest": {
    "axios": "<rootDir>/__mocks__/axios.js"
  }
}

Now, our mocked axios library will allow us to mock successful and failing API requests:

// axios mock
let mocked = null;

//if no request
const noMocks = () => throw('No request mocked');

//response object
export const mockResponse = (status, statusText, data) => ({
  data,
  status,
  statusText
});


const handleResponse = (mockedUrl, response) =>
  // function for mock implementation
  mocked = jest.fn().mockImplementation(({ url }) => {
    mocked = null;

    if (url === mockedUrl) {
      return response;
    }

    throw('Unknown URL: ' + url);
  });

export const clearMock = () => mocked = null;

//complete mockRequeest object
export const mockRequest = (mockedUrl, status, data) =>
  handleResponse(
    mockedUrl,
    Promise.resolve(mockResponse(status, null, data)));

export const mockRequestError = (mockedUrl, state, error) =>
  handleResponse(
    mockedUrl,
    Promise.reject(mockResponse(state, error, '{}')));

export default {
  // request parameters
  request: (params) => (mocked || noMocks)(params),
  // get parameters
  get: (url) => (mocked || noMocks)({ url }),
  name: 'mock'
};

The main two APIs we use are the mockRequest() and mockRequestError() functions. When the mock receives a call, it will create a promise to be returned once our code uses axios:

// Sample mocked server access code
import { mockRequest } from 'axios';
import axios from 'axios';

mockRequest('http://redux-book.com/status.json', 200, { status: 'ok' });

axios.get('http://redux-book.com/status.json')
  .then(data => console.log(data));

In this example we mock access to 'http://redux-book.com/status.json', making an axios.get() request to return { status: 'ok' } as the data.

Get hands-on with 1400+ tech skills courses.