Playfully imitating cross-fetch

I am currently running tests on a Next/React project using Jest with Node. I have also implemented cross-fetch in my project.

However, I encountered an issue when trying to mock cross-fetch for a specific component:

import crossFetch from 'cross-fetch'
jest.mock('cross-fetch')
        crossFetch.mockResolvedValue({
          status: 200,
          json: () => {{ 
            user : testUser 
          }},
        })
        render(<UserProfile />)

Despite setting up the mock, the API request in "getServerSideProps" always returns a 500 error code:

export async function getServerSideProps({ query: { userId } }) {
  let user = null
  let code = 200
  try {
    let response = await fetch(`https://example.com/users/${userId}`, { method: 'GET' }) 
    let statusCode = response.status
    let data = await response.json()
    if (statusCode !== 200) {
      code = statusCode
    } else {
      user = data.user
    }
  } catch (e) {
    console.log(e.message)
  }
  return {
    props: {
      user,
      code,
    },
  }
}

I suspect that the issue might be related to the testing environment not accurately reflecting the browser, where the actual HTTP request is initiated. This could explain why the mocking of the fetch library may not be working as expected. However, this is just a hypothesis.

Thank you in advance for any assistance provided.

Answer №1

It could be possible that the issue lies with the default export function. You may want to give this a try instead:

//test.js
import crossFetch from 'cross-fetch';

jest.mock('cross-fetch', () => {
  //Mocking the default export
  return {
    __esModule: true,
    default: jest.fn()
  };
});

test('attempting a mock fetch', () => {
  crossFetch.mockResolvedValue({
    status: 200,
    json: () => {{ 
      user: testUser 
    }},
  });
  expect(crossFetch().status).toEqual(200);
});

Answer №2

When it comes to testing fetch calls, I rely on the power of fetch-mock (). To ensure that fetch is properly understood in Jest tests, a polyfill may be required, such as:

import "cross-fetch/polyfill";
placed in the file where fetch is utilized. It's worth noting that Create React App automatically handles these polyfill imports, though it remains unclear if Next.js offers a similar solution.

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

Securing routes with server-side validation

I've been experimenting with different methods to secure a route for unauthenticated users, but I'm facing difficulties in implementing it effectively. One common issue I encountered while attempting authentication from getServerSideProps was th ...

Analyze the JSON data retrieved from the API endpoint to determine any

I am currently attempting to utilize axios to send an API request in order to validate login credentials, but I am facing difficulties retrieving the result from the API. The MongoDB .find function successfully locates the correct row, however, I am encoun ...

Enabling table row scrolling with keyboard navigation in React

Struggling to figure out how to make my table scroll while navigating through the rows using the onKeyDown event. It seems that the event isn't updating when using the keyboard, even though the highlighting of the selected row with selected is working ...

Top method for directly converting SVG to JSX within a popular React component library

Currently, I am exploring the most effective method to directly import SVG images as JSX components into my React common component library. By "common component library," I am referring to a distinct package that houses shared components utilized by variou ...

React button remains inactive

After only four months of learning and developing in react, I decided to create a simple portfolio for myself. However, I encountered an issue with a toggler and a button that I included in the navbar - they simply won't respond when clicked no matter ...

Utilizing command line parameters in Node.js through package.json configuration

The Jest documentation includes the following quote: Jest documentation: Node.js v6.* has Proxy enabled by default; if you are not using Node v6.*, be sure to run Jest with node --harmony_proxies node_modules/.bin/jest. My tests are running via npm tes ...

Is it necessary to store tokens in cookies, local storage, or sessions?

I am currently utilizing React SPA, Express, Express-session, Passport, and JWT. I find myself puzzled by the various client-side storage options available for storing tokens: Cookies, Session, and JWT/Passport. Is it necessary to store tokens in cookies, ...

Is React.lazy() compatible with Create React App?

I recently developed a React App using npx create-react-app my-app command, utilizing the React 17 version. However, I ran into an issue when trying to update a traditional component. import Component from './Component' to const Component = Rea ...

Rendering on the server with a focus on the header

Can server side rendering be limited to only <head></head> data? I am exploring options similar to next.js: export async function getServerSideProps(context) { return { props: {}, // will be passed to the page component as props } } Ba ...

Unravel intricate JSON data and display it in a Material-UI table

How to convert the complex JSON data provided below into a material-ui table similar to the example shown. Each row may contain either a single value or multiple rows in a single box. I have attempted to display the data in 2 columns only, but need help wi ...

Error: Empty reference found in Popover

Struggling to set autofocus on an input element when opening a popover. Check out the sandbox here: https://codesandbox.io/s/green-bash-x6bj4?file=/src/App.js The issue I'm facing is that the current property is always null on ref. Is this a situatio ...

Using a System Environment Variable within an Environment Variable in Vercel: A Step-by-Step Guide

Currently, I am in the process of deploying a NextJs project using Vercel and integrating Kinde for authentication purposes. Kinde requires a specific environment variable to be set: KINDE_SITE_URL:http://localhost:300 // Value in local .env file In my V ...

Reset input field when checkbox is deselected in React

How can I bind value={this.state.grade} to clear the input text when the checkbox is unchecked? The issue is that I am unable to modify the input field. If I were to use defaultValue, how would I go about clearing the input box? http://jsbin.com/lukewahud ...

React components are failing to display data as expected

I need to display certain data based on the id provided in the url. When I use console.log() with res.json, I can see the data but I'm unsure how to pass it to the 'articleComponent'. const Articles = () => { const query = (id) => ...

Harnessing the Power of Google Tag Script in Next.js

After researching How to load Google Tag Manager with the next/script component (Next.js 11) and reviewing this documentation page, my issue remains unresolved. I am looking to implement Google Tag on multiple websites developed using nextjs, so I created ...

Using HTML and CSS to implement a broadened perspective for a specific design

https://i.stack.imgur.com/ckQHa.png Hello, I am facing an issue with a UX design that is optimized for 1200px resolution width. However, when the HTML is loaded in a browser on a larger window resolution, there is a 200px gap on the right side. How can I ...

What steps can I take to troubleshoot and resolve this issue with the yarn.lock conflict

Currently, I am working on a next.js project using yarn and bitbucket. As I attempt to merge my branch with the origin, I encounter a conflict issue specifically related to the yarn.lock file. The differences between the version in the origin and that in ...

Is React Spring failing to trigger animations properly on iOS devices?

I have a code that functions perfectly on my desktop and across all browsers. Each button is designed to trigger a 4-second animation upon load or hover, initiating the playback of various videos. However, there's an issue with iOS where the video or ...

React Native Flatlist does not deselect onPress

In my app, I have a flat list that allows users to select items by touching a row. When a user touches a row, the item is selected and its id is stored in an array. However, when the user tries to un-select the item by touching it again, the item is not re ...

The date picker in Hijri Material UI displays the months in the Gregorian calendar

I am utilizing the material UI datepicker and have enabled the option to display the Hijri calendar. However, I have encountered an issue where the months displayed in the month picker are in the Gregorian format (Arabic translation of January, February, e ...