The error message you are encountering is: "Error: Unable to find function axios

Can't figure out why I'm encountering this error message:

TypeError: axios.get is not functioning properly

    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 |

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

This is 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);
  });
});

The content of src/__mocks__/axios.js looks like 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
};

Answer №1

If you're looking for more information, check out this resource: MDN

According to the information provided there, you will need a variable to capture the default export and then use another variable for the remaining exports, labeled as X. One way to achieve this is by using the following syntax:

import axios, * as others from 'axios';

In this case, the variable others represents X.

Instead of writing:

import * as axios from 'axios';

It can be assumed that ... from 'axios' in this context is related to your jest mock setup.

Answer №2

When importing Axios, always use

import Axios from "axios";
rather than
import { Axios } from "axios";

Answer №3

If you have import * as axios from 'axios';, it means that axios is not a default export. However, your mock seems to assume otherwise:

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

Solution

To fix this issue, remove the default export and adjust your mock structure to match the export structure of axios according to how you are importing it.

Answer №4

In order to use axios in your code, make sure to import it as shown below:

import axios, * as other from 'axios';

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refresh Ionic 2 Platform

I'm currently working on an Ionic 2 app and whenever I make a change to the .ts code, I find myself having to go through a tedious process. This involves removing the platform, adding the Android platform again, and then running the app in Android or ...

Experiencing compatibility issues with NextAuth and Prisma on Netlify when using NextJS 14

While the website is functioning correctly on development and production modes, I am encountering issues when testing it on my local machine. After deploying to Netlify, the website fails to work as expected. [There are errors being displayed in the conso ...

Develop a Rails object using AJAX and JavaScript

Within a music application built on Rails, I am attempting to monitor plays for tracks by artists. This involves creating a unique play object each time a visitor plays a track on the site. These play objects are assigned their own distinct IDs and are ass ...

Exploring the File Selection Dialog in Node.js with TypeScript

Is it possible to display a file dialog in a Node.js TypeScript project without involving a browser or HTML? In my setup, I run the project through CMD and would like to show a box similar to this image: https://i.stack.imgur.com/nJt3h.png Any suggestio ...

Identify alterations in an input field after selecting a value from a dropdown menu

Is there a way to detect changes in the input field when selecting a value from a drop-down menu, similar to the setup shown in the image below? html: <input type="text" class="AgeChangeInput" id="range"/> js:(not working) <script> $(docume ...

Renaming properties in an AngularJS model

After receiving the data in a structured format, my task is to present it on a graph using radio buttons. Each radio button should display the corresponding category name, but I actually need each button to show a custom label instead of the original categ ...

Retrieve the decimal separator and other locale details from the $locale service

After reviewing the angular $locale documentation, I noticed that it only provides an id (in the form of languageId-countryId). It would be helpful to have access to more specific information such as the decimal separator character. Is there a way to retri ...

TS - Custom API hook for making multiple API requests - incompatible type with 'IUseApiHook'

What is my objective? I aim to develop a versatile function capable of handling any type of API request for a frontend application. Essentially, I want to add some flair. Issue at hand? I find myself overwhelmed and in need of a fresh perspective to revi ...

"Real-time image upload progress bar feature using JavaScript, eliminating the need for

I have successfully implemented a JavaScript function that displays picture previews and uploads them automatically on the onchange event. Now, I am looking to add a progress bar to show the upload status. However, all the solutions I found online are rel ...

Is it possible to append an "index" to a database field using Express, Loopback, or NodeJS?

Currently, we are utilizing the Express/Loopback Framework for our backend. I am currently working on ensuring that indexes on certain fields in models are properly created in MongoDB. Is there a way to utilize meta-tags within the models so that DataJuggl ...

JavaScript loop used to create markers on Google Maps

I am currently in the process of developing a basic Google map which includes markers and involves looping through the data source for the markers. When I replace key.lng or key.lat with hardcoded values in the code below, everything functions correctly. ...

Troubleshooting an issue with a Typescript React component that is generating an error when using

I am in the process of implementing unit testing in a Typescript and React application. To start off, I have created a very basic component for simplicity's sake. import React from "react"; import ReactDOM from "react-dom"; type T ...

Guidelines for utilizing React to select parameters in an Axios request

As a newcomer to ReactJs, I am working with a Product table on MySQL. I have successfully developed a dynamic table in the front-end using ReactJS along with MySQL and NodeJs on the backend. The dynamic table consists of four columns: Product, Quantity, Pr ...

Resolving type error issues related to using refs in a React hook

I have implemented a custom hook called useFadeIn import { useRef, useEffect } from 'react'; export const useFadeIn = (delay = 0) => { const elementRef = useRef<HTMLElement>(null); useEffect(() => { if (!elementRef.current) ...

Resetting input field based on callback function

In my simple script, I have two pages - script.php and function.php. The script.php page contains an input field with the ID #code, a link with the ID #submit, and a jQuery function. $('#submit').click(function () { $.ajax({ url: 'f ...

c3.js Error: The value of b is not defined

Struggling to create a graph using a JSON object generated in PHP. Despite following the documentation example, I keep encountering a TypeError: b.value is undefined in the JS log. The data seems to be structured correctly. for($i = 0; $i < 10; $i++){ ...

Issue with jQuery .hover() not functioning as expected

The issue I'm encountering is just as described in the title. The code functions correctly on all divs except for one! $(".complete-wrapper-1").hide(); var panelHH = $(".file-select-wrapper").innerHeight; $(".files-button").hover(function(){ $(" ...

Sharing socket data between different namespaces in Socket.ioSocket.io enables the

Is there a solution to sharing data set in a socket in one namespace and accessing it on another namespace? While I understand that data can be attached to the socket object itself, a problem arises when trying to access the data in a different namespace. ...

What is the reason behind the checkbox event status returning the string "on" rather than true/false?

I have implemented a custom checkbox as a child component within a parent component. I properly pass the ngModel, name, etc., and attempt to update the model with a boolean status (true/false) based on the checkbox status using an EventEmitter. However, t ...

MUI Data Table - Error: Undefined property accessed (name)

Utilizing Material UI's datagrid to display data in a table, I made the switch to RTK query from redux for caching and eliminating global state management in the project. However, I encountered a problem as mentioned in the title. The current error I ...