用 Jest 模拟 axios 会抛出错误“无法读取未定义的属性‘拦截器’”

Bra*_*ham 7 javascript jestjs axios

我在用 Jest 和 react-testing-library 模拟 axios 时遇到了麻烦。我被 axios 拦截器的错误困住了,无法绕过它。

这是我的api.js文件:

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));
Run Code Online (Sandbox Code Playgroud)

在我的组件中调用 api:

const fetchAsync = async endpoint => {
  const result = await api.get(endpoint);
  setSuffixOptions(result.data.data);
};
Run Code Online (Sandbox Code Playgroud)

然后在我的规范文件中:

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();
});
Run Code Online (Sandbox Code Playgroud)

测试失败并显示以下消息:

    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 |
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么?

cyb*_*bat 11

create方法就是创造它具有的APIgetinterceptors方法。所以你需要创建一个虚拟的 api 对象:


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() }
      }
    }))
  }
})
Run Code Online (Sandbox Code Playgroud)