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

Leo*_*ban 3 javascript typescript jestjs axios

不知道为什么我收到以下错误:

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

我的服务:

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

我的笑话测试:

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

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

小智 12

使用 import asimport Axios from "axios";代替import { Axios } from "axios";


tys*_*skr 5

请看:MDN

正如那里提到的,您需要一个值来收集default export和 其余的X。在这种情况下,您可以:

import axios, * as others from 'axios';
Run Code Online (Sandbox Code Playgroud)

X在others这里。

代替

import * as axios from 'axios';
Run Code Online (Sandbox Code Playgroud)

假设:... from 'axios'指的是你的玩笑模拟。如果这能回答您的问题,请告诉我。