Skip to content Skip to sidebar Skip to footer

How To Test Axios Interceptors With Jest

In my project, I have a namespace that exports some functions that use Axios, in the same file I add an interceptor to axios instance like that : axios.interceptors.response.use(

Solution 1:

What about pulling the function out and testing it without axios?

import axios, { AxiosError, AxiosResponse } from'axios'exportconstonFullfilled = (response: AxiosResponse) => {
  // Your interceptor handling a successful response
}
exportconstonRejected = (error: AxiosError) => {
  // Your interceptor handling a failed response
}

axios.interceptors.response.use(onFullfilled, onRejected)

Now you can test the functions onFullfilled and onRejected with less dependencies to axios.

Solution 2:

You have to mock the interceptor and run the callbacks.

Here is an example on how to do it:

httpService.ts

import axios from"axios";
import { toast } from"react-toastify";

axios.interceptors.request.use((config) => {
  config.baseURL = process.env.API_URL || "http://localhost:5000";
  return config;
});

axios.interceptors.response.use(null, (error) => {
  const expectedError =
    error.response &&
    error.response.status >= 400 &&
    error.response.status < 500;

  if (!expectedError) {
    toast.error("An unexpected error occured");
  }

  returnPromise.reject(error);
});

exportdefault {
  get: axios.get,
  post: axios.post,
  put: axios.put,
  delete: axios.delete,
};

httpService.test.ts

import axios from"axios";
import { toast } from"react-toastify";
import"./httpService";

jest.mock("axios", () => ({
  __esModule: true,
  default: {
    interceptors: {
      request: { use: jest.fn(() => {}) },
      response: { use: jest.fn(() => {}) },
    },
  },
}));

const fakeError = {
  response: {
    status: undefined,
  },
};

const mockRequestCallback = (axios.interceptors.request.useas jest.Mock).mock
  .calls[0][0];
const mockResponseErrorCallback = (axios.interceptors.response.useas jest.Mock)
  .mock.calls[0][1];
const toastErrorSpy = jest.spyOn(toast, "error");

beforeEach(() => {
  toastErrorSpy.mockClear();
});

test("request error interceptor", () => {
  expect(mockRequestCallback({})).toStrictEqual({
    baseURL: "http://localhost:5000",
  });
});

test("unexpected error on response interceptor", () => {
  fakeError.response.status = 500;

  mockResponseErrorCallback(fakeError).catch(() => {});
  expect(toastErrorSpy).toHaveBeenCalled();
});

test("expected error on response interceptor", () => {
  fakeError.response.status = 400;

  mockResponseErrorCallback(fakeError).catch(() => {});
  expect(toastErrorSpy).not.toHaveBeenCalled();
});

Solution 3:

Use this mock functionality

jest.mock('axios',()=> {
   return {
      interceptors: {
         request: {
            use:jest.fn(),
            eject:jest.fn()
         },
         response: {
            use:jest.fn(),
            eject:jest.fn()
         },
      },
   };
});

Post a Comment for "How To Test Axios Interceptors With Jest"