Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock axios using axios interceptors

I'm trying to use mockAxios for testing with axios interceptors.

export default {
    get: jest.fn(() => Promise.resolve({ data: {} }))
}

import axios from 'axios';

export const configurateAxios = () => {
    axios.interceptors.response.use(
        response => {
          return response;
        },
        error => {
          return Promise.reject(error);
        }
    );
}

When I created mockAxios:

export default {
    get: jest.fn(() => Promise.resolve(data: {}))
}

All of my tests failed with the follow message: cannot read property response of undefined inside of axios interceptors. It happens because mock axios doesn't return response. It could just return a plain object.

So how can I use axios interceptors with mockAxios for testing?

like image 805
Dat Vu Avatar asked Feb 01 '19 16:02

Dat Vu


People also ask

How do you mock Axios interceptor in jest?

use. mockImplementation((callback) => { requestCallback = callback; }); // Mock out the get request so that it returns the mocked data but also calls the // interceptor code: axios. get. mockImplementation(() => { requestCallback(); return { data: "this is some data" }; });


1 Answers

This how I achieved

Interceptor.js

/* Module that I want to test
 * Intercepts every axios request and redirects to login on 401
 */

import axios from 'axios';

export default () => {
  axios.interceptors.response.use(
    response => {
      // Return a successful response back to the calling service
      return response;
    },
    error => {
      // Return any error which is not due to authentication back to the calling service
      if (error.response.status !== 401) {
        return new Promise((resolve, reject) => {
          reject(error);
        });
      } else {
        window.location.href = '/operator-portal/login';
        return false;
      }
    }
  );
};

Interceptor.test.js

import axios from 'axios';
import interceptor from '../../src/apis/interceptor';

jest.mock('axios');

describe('interceptor', () => {
  it('redirects to login route when response status is 401', () => {
    delete global.window.location;
    global.window = Object.create(window);
    Object.defineProperty(window, 'location', {
      value: {
        href: 'url'
      }
    });
    axios.interceptors.response.use = jest.fn((successCb, failCb) => {
      failCb({
        response: {
          status: 401
        }
      });
    });
    interceptor();
    expect(window.location.href).toEqual('/login');
  });

  it('redirects to login route when success handler is called', () => {
    axios.interceptors.response.use = jest.fn(successCb => {
      successCb();
    });
    interceptor();
    window.location.href = 'url';
    expect(window.location.href).toEqual('url');
  });
});
like image 177
Swapnil Navalakha Avatar answered Oct 21 '22 23:10

Swapnil Navalakha