简体   繁体   中英

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?

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() }
      }
    }))
  }
})

You must mock api.js, not Axios.

    import { FuncToCallAPI } from './funcAPI';
    import api from './api';

    describe('Mock api.ts', () => {
      it('should get data', async () => {
       
        const Expected = { status: 200, data: {} };

        jest.spyOn(api, 'get').mockResolvedValue(Expected);

        const result = await FuncToCallAPI('something');

        expect(result).toEqual(Expected);
  });
});

Then create a test for api.js, mocking the axios.create as you did before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM