Axios simulation: Total calls received: 0

Having trouble with my mock for the getAll method. The error I'm seeing is:

Expected number of calls: 1 Received number of calls: 0

Here are the mock configurations I've set up:

jest.mock("axios", () => {
  return {
    create: jest.fn(() => ({
      get: jest.fn(() => Promise.resolve({ data: [{ name: "test_role" }] })),
      post: jest.fn(() => Promise.resolve({ data: { name: "test_role" } })),
      put: jest.fn(() => Promise.resolve({ data: { name: "updated_role" } })),
      delete: jest.fn(() => Promise.resolve({ data: "" })),
      interceptors: {
        request: { use: jest.fn(), eject: jest.fn() },
        response: { use: jest.fn(), eject: jest.fn() },
      },
    })),
  };
});

And here's my test script:

it("Testing getting all roles", async () => {
  //Arrange
  const allRoles = [{ name: "test_role" }];

  //Act
  const result = await role.getAll();

  //Assert
  expect(JSON.stringify(result.data)).toBe(JSON.stringify(allRoles));
  expect(jest.fn()).toHaveBeenCalledTimes(1);
});

Answer №1

mockFunction() creates a brand new mock function with no connection to any other functions it may have originated from. Therefore, you must be explicit in specifying which mock function you anticipate being invoked. For example, if you are expecting the fetch function to be called, you would define it like so:

expect(api.fetch).toHaveBeenCalledTimes(1);

This technique can also be applied to anticipate calls to other methods.

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

Accessing element from view within controller in Ionic version 3.5

I am currently working on a project in Ionic 3.5, where I need to implement a feature that automatically loads an image "ad" after the page finishes loading. Right now, clicking a button successfully displays the image. However, I want this functionality ...

Sync user information when alterations are made on a different device

As I create a Discord clone using Next.js, I've encountered an issue where when a server is deleted, another client can still see and use the server until the page is reloaded. When testing out the official Discord web app, changes seemed to happen in ...

Creating an array object in TypeScript is a straightforward process

Working on an Angular 4 project, I am attempting to declare an attribute in a component class that is an object containing multiple arrays, structured like this: history: { Movies: Array<Media>, Images: Array<Media>, Music: Array<Medi ...

Is it feasible to return data when utilizing the ModalController in Ionic 5, specifically when executing a swipeToClose or backdropDismiss action?

With the latest update to Ionic 5's ModalController, a new feature allows users to swipe down on a modal to close it in addition to using the backdropDismiss parameter. Here is an example of how to enable this functionality: const modal = await this. ...

Tips for extracting IDs from multiple checkboxes that have been selected upon submission in an Ionic 2+/Angular 2+ environment

I am facing an issue with retrieving the ID of the checked item upon submission. While I can successfully fetch the selected ID on change, I am unable to do so on submit. It is worth noting that the data I am receiving does not include a "checked" value. T ...

Displaying error.response.data on the frontend as a user-friendly message

When a user signs up, I need to display the error.response.data as a message. This data will contain either "Email is invalid" or "Email is already registered." My technology stack includes React, Node, and Axios. ...

Obtaining the attribute value from a custom tag in Angular: A comprehensive guide

I am currently working on creating a customized password component in Angular5. I am having difficulty obtaining the minimum and maximum attribute values required to validate the password. I attempted to retrieve the values using JavaScript's getAttr ...

Missing data list entries for next js server actions

After successfully running my add function, I noticed that the data I added earlier is not being reflected in the list when I check. import React, { useEffect, useState } from "react"; import { createPost } from "./actions"; import { SubmitButton } from ". ...

A guide to using Angular to emphasize text based on specific conditions met

Currently, I am developing a testing application that requires users to choose radio type values for each question. The goal is to compare the selected answers with the correct answers stored in a JSON file. To achieve this, I have implemented an if-else ...

The intricate field name of a TypeScript class

I have a TypeScript class that looks like this - export class News { title: string; snapshot: string; headerImage: string; } In my Angular service, I have a method that retrieves a list of news in the following way - private searchNews(sor ...

In what ways does PROJEN streamline project configuration for infrastructure and application projects?

Exploring PROJEN and AWS CDK has raised questions for me regarding how PROJEN contributes to standardizing project configurations in the context of multiple projects or repositories. While I see its usefulness for a single project or repository through the ...

Jest may come across test suites, but it discreetly disregards the individual tests

Having encountered an issue with Jest testing in a Nuxt/Vue v2 project, I found that after making some changes, the tests were no longer running. The unit tests were either passing or failing initially, but suddenly stopped running altogether. ----------|- ...

Angular's custom reactive form validator fails to function as intended

Struggling to incorporate a customized angular validator to check for date ranges. The validator is functioning correctly and throwing a validation error. However, the issue lies in the fact that nothing is being displayed on the client side - there are n ...

Typescript headaches: Conflicting property types with restrictions

Currently, I am in the process of familiarizing myself with Typescript through its application in a validation library that I am constructing. types.ts export type Value = string | boolean | number | null | undefined; export type ExceptionResult = { _ ...

What is the best way to declare strings within a Typescript interface?

I have an array of Projects with multiple strings in the stack property const projects: IProject[] = [ {name: '', description: '', stack: {'php', 'sql'}} ] What is the best approach for defining the interface? ...

What is the best way to retrieve an object when a value is not found? Consider implementing a looping mechanism with a specific condition in React and TypeScript to successfully

Greetings, I am faced with an array of objects structured as follows: const arr_obj = [ { id: '1', jobs: [ { completed: false, id: '11', run: { ...

An issue arises when using enums in TypeScript

Let's analyze this demonstration. Initially, an enum is created as follows: enum myEnum { a = 'a', b = 'b' } The next step involves creating a similar enum but with the addition of one more numeric value! This alteration is c ...

One-time export feature similar to Typescript's export_once functionality

When I have the following code structure: File1.ts function someFunction(){...} export default someFunction(); and then File2.ts import File1 from "./File1"; File3.ts import File1 from "./File1"; My question is, will the export de ...

What is the process of retrieving a string in a method within an Ionic TypeScript file and storing it in a variable?

Having trouble returning a string to another method in an Ionic TypeScript file. Our goal is to return JSON.stringify(res) and assign it to the stringset variable. We initially tried testing by simply returning the string "hi", but even that did not work. ...

Extracting the year, month, and date values from a ngbDatepicker and sending them over httpClient

Attempting to choose a date using a ngbDatepicker and then sending the year, month, and date values via httpClient to the backend in order to filter a Page of Entities named "Show" based on that date. The backend requires the Integers "year", "month", and ...