繁体   English   中英

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

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

我在用 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));

在我的组件中调用 api:

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

然后在我的规范文件中:

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

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

    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 |

我在这里做错了什么?

create方法是创建具有getinterceptors方法的 api 的方法。 所以你需要创建一个虚拟 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() }
      }
    }))
  }
})

你必须模拟 api.js,而不是 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);
  });
});

然后为 api.js 创建一个测试,像以前一样模拟 axios.create。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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