TypeError:axios.get不是函数吗?

时间:2018-09-19 01:29:02

标签: javascript typescript axios jestjs

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

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

2 个答案:

答案 0 :(得分:1)

请查看:MDN

从那里开始,您需要一个值来收集default export,其余作为X。在这种情况下,您可以:

import axios, * as others from 'axios';

X在此处为others

代替

import * as axios from 'axios';

假设:... from 'axios'是指您的笑话模拟。让我知道是否能回答您的问题。

答案 1 :(得分:0)

您有import * as axios from 'axios';。在这种情况下,axios不是默认的导出。您的模拟假设是这样的:

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

修复

删除默认导出,并替换您的模拟结构以在使用axios时映射其导出结构。