Exploring the default export function in Jest manual mock can be done through a series of

While testing Jest, I encountered the following issue with the manual mock file of isomorphic-fetch:

// __mocks__/isomorphic-fetch.ts

import * as req from "./requestData";

const Fetch = (url: string, options: any): Promise<any> => {
  const resultPromise = {
    text: () => {
      return Promise.resolve(req.generateMockResponseData(url, options.body));
    },
  };
  return Promise.resolve(resultPromise);
};

export default Fetch;

Despite returning the expected values, when attempting to analyze the arguments passed to it, I found that the mock property on fetch was undefined. I tried two different approaches to resolve this issue:

Firstly, I wrapped the Fetch function in a jest.fn like so:

const Fetch = jest.fn((url: string, options: any): Promise<any> => {
// implementation remains the same
});

export default Fetch;

After adding

import _fetchMock  from "isomorphic-fetch"
const fetchMock = _fetchMock as jest.Mock<Promise<any>>;

to the test file, I was able to inspect fetch calls using

fetchMock.mock.calls[0]

However, now during tests, fetch in the application code started returning undefined for some reason.

Secondly, I removed the jest.fn wrapper from Fetch and included

jest.mock("isomorphic-fetch")

in the test file. This led to fetch returning the expected values during tests in the application code, but fetchMock.mock became undefined again.

For Jest configuration, refer to the snippet below:

// jest.config.js
module.exports = {
  "clearMocks": true,
  "coverageDirectory": "../coverage",
  "resetMocks": true,
  "restoreMocks": true,
  "rootDir": "./src",
  "testEnvironment": "jsdom",
  "preset": "ts-jest",
  "coveragePathIgnorePatterns": ["Error.ts"],
  "testEnvironmentOptions": {
    "resources": "usable",
    "features": {
      "FetchExternalResources": ["script", "iframe"],
      "ProcessExternalResources": ["script", "iframe"],
    }
  }
}

For a detailed example, please visit GitHub.

Answer №1

When working with Jest, it's important to note that a Jest spy and a regular mocked function can exhibit different behaviors even if they have the same implementation. This is because a Jest spy has the ability to be reset to act as a no-op.

Here's an example scenario in a Jest setup where this behavior occurs:

...
"resetMocks": true,
"restoreMocks": true,
...

The restoreMocks option is generally preferred as it helps prevent test cross-contamination by reverting spied methods back to their original implementations.

On the other hand, the resetMocks option is usually not recommended since it resets reusable spies from __mocks__ to behave as no-op functions.

In summary, using the resetMocks configuration option or jest.resetAllMocks() can lead to the destruction of implementations for reusable spies and should be avoided. Instead, if you need to reset a specific spy, it's better to do so on a case-by-case basis using the mockReset method.

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

In JavaScript, an HTTP request file includes a JavaScript variable

I am currently working on a Node.js project that involves making an HTTP request to fetch a JavaScript file. For example, let's say we have a file named a.js: var a = 'i am a.js'; var b = 'please convert me to js'; Here is the a ...

Insight into Typescript types through dot notation

Here is the interface I am working with: export interface IRenderStruct { type: string; props: { className?: string; children?: (string | IRenderStruct) | (string | IRenderStruct)[]; [propName: string]: any; }; } The objects created bas ...

Try out different widths to evaluate the responsiveness of your React components

A scenario is described where a Drawer and a Button are implemented in the DOM to only appear when the window width is less than 600. The following code represents the implementation of the Drawer and Button. <Hidden smUp> <Button className ...

grab the content from a text editor and insert it into a div element

Currently, I am trying to extract text from my content editable div and place it in another div (similar to the one seen on stack overflow). However, I am encountering a frustrating issue. 1. My content div seems to be lagging behind. When I type in my ed ...

ESlint is preventing the creation of a Next.js 15 application due to an error variable in a try-catch block that is not being used

I am currently delving into the world of nextJS 15 and I am in the process of developing an application using the pokeAPI. However, when I execute npm run build, eslint raises a concern with the following message: Error: 'error' is defined but n ...

Generating objects dynamically using an array of paths in dot notation

Is it possible to dynamically generate an object with an array of strings in dot notation? The idea is to construct a JSON object from a CSV file, filter the properties, and create a new JSON object. Let's say we want to pass something like this... ...

Setting up NextJS on Vercel for website deployment can encounter a common error known as ENOENT Error, which is caused by the absence of a specific file or

Everything works perfectly on my local machine: import fs from 'fs' import path from 'path' export default function createNewDirectory (tokenSignature: string) { const directoryPath = path.join(process.cwd(), 'notes', to ...

Is there a jQuery or Javascript alternative to CSS Counter?

Can a counter be implemented that changes the text of a tag directly using jQuery/Javascript? For example, if there were two tags like this: <a>hello</a> <a>bye</a> After executing the jQuery/JS function, the result would be: < ...

Error message displayed when attempting to send emails through an HTML form obtained from a complimentary template site

Currently, I am in the process of learning to code basic websites but I'm facing some challenges with getting the contact form to function properly. I decided to work with a free template that can be found at this link: and uploaded it to a shared ho ...

Utilizing Typescript and sinon to mock the functionalities of jsonwebtoken

Looking for help with mocking the function verify in Typescript's jsonwebtoken library. I've installed typescript, jsonwebtoken, sinon, mocha, and chai along with their corresponding types. However, when trying to stub the function, an error occu ...

Issue with React.js code not being detected in TSX file (Visual Studio 2015 Update 1 RC)

Currently, I am utilizing Visual Studio 2015 with update 1 release candidate. Interestingly, I have managed to successfully incorporate React.js code and syntax highlighting within a .JSX file. However, when it comes to a .TSX file, nothing seems to be wor ...

What is the best way to choose the unique identifier of an HTML element inside a for loop in a Django template?

I need help selecting an HTML button that is generated within a for loop in a Django template using JavaScript. How can I assign a unique ID to each button and select it correctly in JavaScript? Currently, all buttons have the same ID within the loop, resu ...

Setting up WebDriverIO with BrowserMobProxy allows for seamless integration between the

Is there a good example available for setting up BrowserMobProxy along with WebDriverIO? I need to capture network traffic. I had it working previously with WebDriverJS, but that version is now deprecated in favor of WebDriverIO. ...

What is the correct way to format responses written within response.write() in NodeJS?

Just starting out with NodeJS and express and following a tutorial on displaying two headings in the browser. Came across an issue where using res.send() twice wasn't working, so my instructor introduced me to the write method. Interestingly, when she ...

Issue encountered while generating dynamic Routes using the map function

When attempting to dynamically use Route from an array, I encounter an error. Warning: Incorrect casing is being used. Use PascalCase for React components, or lowercase for HTML elements. The elements I am utilizing are as follows: const steps = [ { ...

How can one effectively separate logic in AngularJS for optimal performance?

I've been diving into AngularJS and it's been quite fascinating, although I do run into some architectural challenges at times. Let me illustrate with an example. Imagine we have an application that enables users to create bills. Each bill consi ...

Unpredictable hue of text

Is it possible to fill text with a combination of 2-3 random colors? ...

Comparing and highlighting words in strings using JavaScript

Seeking assistance with comparing and styling words as shown in the image below: https://i.stack.imgur.com/Ffdml.png I attempted using JavaScript for this task but have not been successful so far. <div class="form-group"> <div class="col-md ...

What measures can be taken to avoid RowIDs resetting in jqGrid?

After each pagination action (such as increasing the number of rows or moving to the next page), I noticed that the rowIDs get reset for some reason. For example, let's say I have a total of 75 records. I am displaying 15 records per page, resulting ...

Having issues with array.push functionality in JavaScript

let chatConversations = new Array(); jQuery('.CChatWindow').each(function(){ if (jQuery(this).is(":visible") && jQuery(this).attr("data-conversationid") != 0) { alert(jQuery(this).attr("data-conversationid")); // returns 1 and ...