13

When running a test using jest I have the basic test suit syntax:

jest.mock('axios');

describe('app', () => {
    let render

    beforeEach(() => {
        axiosMock.get.mockResolvedValueOnce({
            data: {greeting: 'hello there'},
        }),
        render= renderApp()
    });

    test('should render something', () => {
        expect(something).toBeInTheDocument();
    });


});

The problem is I have interceptors in my code which when running the test with jest command outputs:

TypeError: Cannot read property 'interceptors' of undefined

and points to the interceptors object

axiosInstance.interceptors.request.use(...

axiosInstance is the a variable storing the return of axios.create

export const axiosInstance = axios.create({...

Refered to this axios thread on SO How do I test axios in jest but it doesn't involve any interceptors so didn't really help.

A Jar of Clay
  • 5,622
  • 6
  • 25
  • 39
EugenSunic
  • 13,162
  • 13
  • 64
  • 86

3 Answers3

17

This was enough in the end, plain and simple jest.fn()

jest.mock('axios', () => {
    return {
        interceptors: {
            request: { use: jest.fn(), eject: jest.fn() },
            response: { use: jest.fn(), eject: jest.fn() },
        },
    };
});
EugenSunic
  • 13,162
  • 13
  • 64
  • 86
  • I didb't created axios instance using axios.create, how can I mock interceptors ? In my unit test axios is mocked like this jest.mock('axios'); const mockedAxios = axios as jest.Mocked; – sagar Oct 12 '21 at 13:03
7

Make sure to mock out the interceptors and axios.create if used:

// Replace any instances with the mocked instance (a new mock could be used here instead):
axios.create.mockImplementation((config) => axios);

// Mock out the interceptor (assuming there is only one):
let requestCallback = () => {
  console.log("There were no interceptors");
};
axios.interceptors.request.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"
  };
});

Note if this doesn't work:

This example assumes that the create and interceptor calls are in a place where Jest can mock them out. Placing the axios.create or axiosInstance.interceptors.request.use lines outside the scope of the function may cause the above mocking to fail. This is an example file where Jest can mock them out:

const axios = require('axios');

const DEBUG = true;

const customRequest = (url) => {
  // Example of axios.create from https://www.npmjs.com/package/axios#axioscreateconfig
  const axiosInstance = axios.create({
    baseURL: 'https://some-domain.com/api/',
    timeout: 1000,
    headers: {'X-Custom-Header': 'foobar'}
  });

  // Example of interceptor taken from https://stackoverflow.com/a/52737325/7470360:
  axiosInstance.interceptors.request.use((config) => {
    if (DEBUG) { console.info("Request called", config); }
    return config;
  }, (error) => {
    if (DEBUG) { console.error("Request error ", error); }
    return Promise.reject(error);
  });

  return axiosInstance.get(url);
}

module.exports = customRequest;

The mocking code will mock out the axios.create call and the axiosInstance calls in customRequest. Moving either the creation or interception outside the function will cause the mocks to fail.

A Jar of Clay
  • 5,622
  • 6
  • 25
  • 39
  • 1
    Tnx for the help however I've been able to mock it with usual jest.mock('axios',callback) Anyways I've ran into another issue so if you could take a look at it https://stackoverflow.com/questions/60428640/how-to-mock-axios-createconfig-function-to-return-its-instance-methods-inste Upvoted this answer yesterday – EugenSunic Feb 27 '20 at 08:00
6

Here is how I mocked axios.create and its interceptors:

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

Afterwards I was able to call the following in my test code:

const client = axios.create({
  baseURL: 'http://some-url.com',
});

client.interceptors.request.use(config => {
  // some other test code
  return config;
});
Benny Code
  • 51,456
  • 28
  • 233
  • 198