Leon Gaban
Leon Gaban

Reputation: 39038

TypeError: axios.get is not a function?

Not sure why I'm getting the following error:

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 |

My service:

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

My jest test:

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

In the src/__mocks__/axios.js I have this:

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

Upvotes: 14

Views: 86619

Answers (4)

Shailesh Patel
Shailesh Patel

Reputation: 139

Use import as import Axios from "axios"; instead of import { Axios } from "axios";

Upvotes: 14

Nadun Yalegama
Nadun Yalegama

Reputation: 31

You need to import axios like this:

import axios, * as others from 'axios';

Upvotes: 2

trk
trk

Reputation: 2228

Please look at: MDN

As mentoined there, you need a value to collect the default export and the rest as X. In this case you could:

import axios, * as others from 'axios';

X being others here.

Instead of

import * as axios from 'axios';

Assumption: ... from 'axios' is referring to your jest mock.

Upvotes: 21

basarat
basarat

Reputation: 275987

You have import * as axios from 'axios';. In this case axios is not a default export. Your mock assumes it is so:

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

Fix

Remove the default export and replace your mock structure to map the export structure of axios as you are using it.

Upvotes: 2

Related Questions