Typescript's way of mocking fetch for testing purposes

I have a query regarding the following code snippet:

import useCountry from './useCountry';
import { renderHook } from '@testing-library/react-hooks';
import { enableFetchMocks } from 'jest-fetch-mock';
enableFetchMocks();

it('should make proper api call', async () => {
  const resultCountries = {
    PL: 'Poland',
    CA: 'Canada',
  };

  jest.spyOn(global, 'fetch').mockImplementation(() =>
    Promise.resolve({
      json: () => Promise.resolve(resultCountries),
    } as Response),
  );

  const expected = [
    { code: 'PL', name: 'Poland' },
    { code: 'CA', name: 'Canada' },
  ];

  const { result, waitForNextUpdate } = renderHook(() => useCountry());
  await waitForNextUpdate();

  expect(fetch).toHaveBeenCalled();
  expect(result.current).toEqual(expected);
});

Upon removing as Response, I am encountering a Typescript warning:

TS2345: Argument of type '() => Promise<{ json: () => Promise<{ PL: string; CA: string; }>; }>' is not assignable to parameter of type '(input?: string | Request | undefined, init?: RequestInit | undefined) => Promise'.   Type 'Promise<{ json: () => Promise<{ PL: string; CA: string; }>; }>' is not assignable to type 'Promise'.     Type '{ json: () => Promise<{ PL: string; CA: string; }>; }' is missing the following properties from type 'Response': headers, ok, redirected, status, and 11 more.

I am seeking guidance on how to effectively mock the fetch without using as Response as it seems like an unfavorable practice.

Answer №1

When facing issues with mocking the fetch function, I found a solution by incorporating the following code snippet within my .test.tsx file.

//app.test.tsx
global.fetch = jest.fn(async () =>
  Promise.resolve({ json: async () => Promise.resolve({ id: 0 }) })
) as jest.Mock;

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

Is it possible to retrieve values from my model when working with Django Templates and incorporating them in the JavaScript header?

With Django, I have managed to successfully retrieve and display data from my model in the content section of the template. However, I am facing issues retrieving data from the model in the header section of the template. Below is the code --> view.py ...

Is it possible for a draggable position:absolute div to shrink once it reaches the edge of a position:relative div

I am facing an issue with draggable divs that have position:absolute set inside a position:relative parent div. The problem occurs when I drag the divs to the edge of the parent container, causing them to shrink in size. I need the draggable divs to mainta ...

I am looking to switch themes on the homepage using a button from an imported component

I have successfully created a toggle button on my main page in app.js to switch between dark and light themes. However, I am facing difficulty in putting the button inside my nav component and using it from that page imported in app.js. Can anyone guide me ...

What is the best approach for overlaying random meshes onto a terrain using a heightmap in three.js?

I'm interested in plotting randomly generated meshes at the y-position that corresponds to the terrain's height in three.js. While browsing through the documentation, I came across the raycaster method, which seems like it could be useful. Howeve ...

What are the benefits of sharing source files for TypeScript node modules?

Why do some TypeScript node modules, like those in the loopback-next/packages repository, include their source files along with the module? Is there a specific purpose for this practice or is it simply adding unnecessary bulk to the module's size? ...

JavaScript Automation Script for QuickTime Screen Recording

Recently, I've been working on a JavaScript Automation script to record my screen on my Mac. However, I encountered an issue with the API when it reaches the line doc.close(). QuickTime would hang indefinitely and eventually my Script Editor would tim ...

Display or conceal elements within a Component with the help of a Service

After developing a custom Tabs component, I have implemented it in the following way (StackBlitz example): <tabs> <tab title="Tab 1"> <div toolbar> <message><span>Message 1: </span></message> &l ...

Injecting services differently in specific scenarios in AngularJS

I have a unique angular service called $superService that I utilize across many of my directives and controllers. However, there is one specific directive where I want to implement the following behavior: If another directive utilizes $superService in its ...

Is there a way to retrieve the list element that was added after the HTML was generated?

How can I reference a list element added using the append function in jQuery within my onclick function? See my code snippet below: $(function() { let $movies = $('#showList') let $m = $('#show') $.ajax({ method: 'GET ...

Combine collapse and popover in Bootstrap 3 for enhanced functionality

I'm facing some issues trying to use the badge separately from the collapse feature. $(function (e) { $('[data-toggle="popover"]').popover({html: true}) }) $('.badge').click($(function (e) { e.stopPropagation(); }) ) Check o ...

Is there a way to find the JavaScript Window ID for my current window in order to utilize it with the select_window() function in

I'm currently attempting to choose a recently opened window while utilizing Selenium, and the select_window() method necessitates its WindowID. Although I have explored using the window's title as recommended by other sources, and enabled Seleni ...

Using Highmaps in a VueJs application involves passing a state to the mapOptions for customization

I'm currently struggling with passing a vuex state to mapOptions in vuejs components. Here is the code snippet: <template> <div> <highcharts :constructor-type="'mapChart'" :options="mapOptions" class="map">&l ...

What causes the NavBar to show and hide within a specific range?

Recently, I encountered a perplexing issue with my navbar. It functions correctly except for one strange behavior that has left me baffled. Why does the menu appear when I adjust the width to 631px, but disappear at 600px? And vice versa – why does it wo ...

What steps should I take to resolve this issue? ERROR TypeError: Unable to access property 'user' of null object

Is there a way to resolve the error I'm encountering in my project? The error message is: ERROR TypeError: null is not an object (evaluating 'userdata.user'). Using React Native Expo, I am facing this issue after logging into my app and navi ...

Ui-router experiencing issues with nested view loading due to changes in URL

I have been developing an application and previously used ui-router successfully with Ionic. The issue I am facing now is that although the URL changes correctly as expected, nothing happens afterwards. I am certain that the template is being found because ...

Retrieving the output from a nested scope within a function

I have a scenario where I am working with a function that has a nested "then" function containing a return statement. My goal is to combine this inner return data with the outer return data. Below is the code snippet: public async getAllWidgets(): Promis ...

Working with conditional statements in ReactJS and Javascript

As I navigate the circle object using arrow keys, I am facing a challenge in limiting its movement within the height and width of the svg area. Despite my efforts to use conditional statements, the ball tends to get trapped at the edges and fails to contin ...

Stripping away HTML tags from a JSON output

I'm attempting to retrieve a JSON result using jQuery. $.ajax({ type: "GET", url: "http://localhost:8080/App/QueryString.jsp?Query="+query, contentType:"text/html; charset=utf-8", dataType: "json", success: function(json) { if(data!="") ...

Items added to a form using jQuery will not be submitted when the form is posted

Issues with posting data from dynamically appended options in a form select using jQuery have been noticed. When an appended option is selected and the form is submitted, the value does not get posted (in this case, in an email template). Adding another no ...

Utilize the map function on an array object to present data in a table using React framework

My parent component passes an array object that looks like this: https://i.sstatic.net/Nqh81.png I want to organize these values into a table with the keys in one column and their corresponding values in other columns. The desired format is shown here: ht ...