Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking axios with Jest throws error “Cannot read property 'interceptors' of undefined”

I’m having trouble mocking axios with Jest and react-testing-library. I’m stuck on an error around axios interceptors and can’t make my way around it.

This is my api.js file:

import axios from 'axios';

const api = axios.create({
  baseURL: window.apiPath,
  withCredentials: true,
});

api.interceptors.request.use(config => {
  const newConfig = Object.assign({}, config);
  newConfig.headers.Accept = 'application/json';

  return newConfig;
}, error => Promise.reject(error));

The call to api in my component:

const fetchAsync = async endpoint => {
  const result = await api.get(endpoint);
  setSuffixOptions(result.data.data);
};

Then in my spec file:

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

test('fetches and displays data', async () => {
  const { getByText } = render(<Condition {...props} />);
  await expect(getByText(/Current milestone/i)).toBeInTheDocument();
});

The test fails with this message:

    TypeError: Cannot read property 'interceptors' of undefined

       6 | });
       7 |
    >  8 | api.interceptors.request.use(config => {
         |                ^
       9 |   const newConfig = Object.assign({}, config);
      10 |   newConfig.headers.Accept = 'application/json';
      11 |

What am I doing wrong here?

like image 204
Brandon Durham Avatar asked Sep 19 '20 22:09

Brandon Durham


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

the create method is what creates the api which has the get and interceptors methods. So you need to create a dummy api object:


jest.mock('axios', () => {
  return {
    create: jest.fn(() => ({
      get: jest.fn(),
      interceptors: {
        request: { use: jest.fn(), eject: jest.fn() },
        response: { use: jest.fn(), eject: jest.fn() }
      }
    }))
  }
})
like image 87
cyberwombat Avatar answered Oct 24 '22 14:10

cyberwombat