类型错误:axios.get不是函数?

mv1qrgav  于 2022-11-05  发布在  iOS
关注(0)|答案(4)|浏览(253)

不确定为什么会出现以下错误:

TypeError: axios.get is not a function

    4 |
    5 | export const getTotalPayout = async (userId: string) => {
  > 6 |   const response = await axios.get(`${endpoint}get-total-payout`, { params: userId });
    7 |   return response.data;
    8 | };
    9 |

我的服务:

import * as axios from 'axios';

const endpoint = '/api/pool/';

export const getTotalPayout = async (userId: string) => {
  const response = await axios.get(`${endpoint}get-total-payout`, { params: userId });
  return response.data;
};

"我的玩笑测试“

// import mockAxios from 'axios';
import { getTotalPayout } from './LiquidityPool';

const userId = 'foo';

describe('Pool API', () => {
  it('getTotalPayout is called and returns the total_payout for the user', async () => {
    // mockAxios.get.mockImplementationOnce(() => {
    //   Promise.resolve({
    //     data: {
    //       total_payout: 100.21,
    //     },
    //   });
    // });

    const response = await getTotalPayout(userId);
    console.log('response', response);
  });
});

在src/mocks/axios.js中,我有以下内容:

// tslint:disable-next-line:no-empty
const mockNoop = () => new Promise(() => {});

export default {
  get: jest.fn(() => Promise.resolve({ data: { total_payout: 100.21 }})),
  default: mockNoop,
  post: mockNoop,
  put: mockNoop,
  delete: mockNoop,
  patch: mockNoop
};
1bqhqjot

1bqhqjot1#

请看:MDN网络
正如上面提到的,你需要一个值来收集default export,其余的作为X。在这种情况下,你可以:

import axios, * as others from 'axios';

这里X是others
而不是

import * as axios from 'axios';

假设:... from 'axios'指的是你的玩笑模拟。

wnrlj8wa

wnrlj8wa2#

使用import作为从“axios”导入Axios;而不是从“axios”导入{ Axios };

6rqinv9w

6rqinv9w3#

您有import * as axios from 'axios';。在本例中,axios * 不是默认导出 *。您的mock假设它是这样的:

export default {
  get: jest.fn(() => Promise.resolve({ data: { total_payout: 100.21 }})),
  default: mockNoop,
  post: mockNoop,
  put: mockNoop,
  delete: mockNoop,
  patch: mockNoop
};

修复

删除默认导出并替换您的mock结构,以便在使用axios时Map它的导出结构。

e4yzc0pl

e4yzc0pl4#

您需要像这样导入axios:

import axios, * as others from 'axios';

相关问题