Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
};
like image 871
Leon Gaban Avatar asked Jan 28 '23 10:01

Leon Gaban


2 Answers

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.

like image 109
trk Avatar answered Jan 31 '23 22:01

trk


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

like image 26
Shailesh Patel Avatar answered Jan 31 '23 21:01

Shailesh Patel