Mocking HTTP Requests with Axios Mock Adapter

less than 1 minute read

Axios is a promise based HTTP client. In unit tests, sending an actual request to the server when executing the test is not a good practice.

Let’s say we have a library which uses axios to make HTTP requests as follows.

// lib.js

import http from 'axios';

export function fetchPost() {
  return http
    .then((response) => {

We want to unit test this method but without acually sending a request to the server. That’s where axios-mock-adapter comes to rescue.

// lib.test.js

import { expect } from 'chai';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { fetchPost } from './lib'

describe('Lib', () => {
  it('Should return data from response', (done) => {
    let mockAdapter = new MockAdapter(axios);

     mockAdapter.onGet('').reply(200, {
       data: {
         posts: ['Intro to git']

     let response = fetchPost();

     setTimeout(() => {
        expect(response.posts[0])'Intro to git');
     }, 0)

Hope this small write up helps you to test your components which uses axios to send HTTP requests.

Happy unit testing!

Leave a Comment