Jest is simulating a third-party library, yet it is persistently attempting to reach

Here's a function I have:

export type SendMessageParameters = {
  chatInstance?: ChatSession,
  // ... other parameters ...
};

const sendMessageFunction = async ({
  chatInstance,
  // ... other parameters ...
}: SendMessageParameters): Promise<void> => {
  // await chatInstance?.sendMessage()
  // implementation details here
};

export default sendMessageFunction;

ChatSession comes from @google/generative-ai.

In my testing file, I want to create a mock like this:

let defaultParams: SendMessageParameters;

beforeEach(() => {
  jest.mock('@google/generative-ai', () => ({
    ChatSession: {
      sendMessage: async (content: string) => content,
    },
  }));
  defaultParams = {
    chatInstance: new ChatSession('', ''),
    // ... other params ...
  };
});

afterEach(() => {
  jest.clearAllMocks();
});

it('should send message', async () => {
  // await sendMessage();
});

Upon running npm run test, an error occurs:

 FAIL  tests/logic/actions/sendMessage.test.ts
  ● should send message

    ReferenceError: fetch is not defined

     ...

This error indicates that the chatInstance.sendMessage method is using the actual implementation instead of the mock. I'm curious about why this is happening and how to resolve it.

Your help is appreciated.


Environment

  • Node 20.11.0 (lts/iron)
  • Jest 29.7.0
  • @google/generative-ai 0.5.0 (if relevant)

Answer №1

When using the sendMessage function, you can create a mock chatSession to pass as its parameter without the need for jest.mock().

For example:

script.js:

import { ChatSession } from "@google/generative-ai";

export type SendMessageParams = {
  chatSession?: ChatSession;
};

const sendMessage = async ({ chatSession }: SendMessageParams): Promise<void> => {
  await chatSession?.sendMessage('hello');
};

export default sendMessage;

script.test.js:

import { ChatSession } from '@google/generative-ai';
import sendMessage from '.';

it('should send message', async () => {
  const chatSession = {
    sendMessage: jest.fn().mockImplementation((content) => content),
  } as unknown as ChatSession;

  await sendMessage({ chatSession });
  expect(chatSession.sendMessage).toHaveBeenCalledWith('hello');
});

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

Effortlessly submit multiple forms at once with just a single click using the WordPress form

One issue I'm experiencing is that the forms on my site are generated using shortcodes. I have a suspicion that the buttons I created, which lead to submission form1 and then form2, may not be working properly because of this. This is the current set ...

Navigate within the div by scrolling in increments of 100%

I am facing an issue with a div that contains multiple children set to 100% height. My goal is to scroll exactly the height of one child (which is also 100%) on each scroll. However, I am struggling to prevent scrolling multiple steps at a time. I have tri ...

Compilation failure due to Typescript initialization issue

Encountering a TypeScript error in my IntelliJ-Idea 2017.1.1 IDE I have enabled JavaScript, NodeJS, and TypeScript Compiler. I have exhausted all solutions but the issue persists, perhaps I am missing something. Error: Initialization error (typescript ...

What is the method for enabling imports from .ts files without file extensions?

While trying to open a Svelte project with TypeScript, I encountered an issue where all imports from .ts files were showing "Cannot resolve symbol" errors. https://i.stack.imgur.com/FCVxX.png The errors disappear when the .ts extension is added to the im ...

Passing Data from Child to Parent Components in ReactJS

I'm new to React and JavaScript, currently working on a website. I've encountered an issue with passing data between components from child to parent. Here's the scenario: In my App.js script, I'm using react-router-dom for routing. I ...

Issues persist with the Angular UI Tree Module: the removed callback is not functioning as

I am currently utilizing a module that can be found at the following URL: https://github.com/angular-ui-tree/angular-ui-tree Unfortunately, I am facing an issue with getting the removed callback to work properly. The accept callback seems to be functionin ...

What measures can be taken to restrict users from inputting decimal values?

My website includes an order page where users can input quantities for various items. While some items allow for decimal quantities, others do not. What is the most effective method to restrict users from entering decimal quantities? (Besides using an ale ...

Guide: Generating a DIV Element with DOM Instead of Using jQuery

Generate dynamic and user-defined positioning requires input parameters: offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth ...

Explore the XML format within a JavaScript string

Currently, I am retrieving a string from PHP using AJAX. This string contains data from a database formatted in XML tags. Upon receiving this string in JavaScript, my objective is to display it as an XML document on the web browser to verify its proper fo ...

Strange Typescript Issue: Dependency Imports Not Recognized as Top-Level Module

Attempting to move a custom token from one account to another by following this detailed tutorial. Facing an issue with four errors showing up for all imports from the @solana/spl-token package. Tried removing the node-modules folder and reinstalling npm ...

experiencing an excessive amount of rerenders when trying to utilize the

When I call the contacts function from the main return, everything seems fine. However, I encounter an error at this point: const showContacts = React.useCallback( (data: UsersQueryHookResult) => { if (data) { return ( < ...

The NextJS API is throwing an error due to a mysterious column being referenced in

I am currently in the process of developing an API that is designed to extract data from a MySQL table based on a specific category. The code snippet below represents my current implementation: import { sql_query } from "../../../lib/db" export ...

What could be causing the routing to fail in this script?

Currently working on a small project to dive into AngularJS, and I'm facing some challenges with getting the routing to function properly. Despite following numerous tutorials, my code doesn't seem to be working as expected. If anyone could lend ...

What steps should I take to resolve npm start issues within my Node.js application?

Upon completing the npm install, I attempted to run npm start for my project. Unfortunately, an error was displayed. What steps can be taken to resolve this issue?view image of the error here ...

Sending files to the server through HTML5

Could someone assist me with uploading a file after it has been selected using HTML5? Here's the code snippet for selecting the file: <input type="file" .... /> The input field above allows you to choose a file, but I also need help with uploa ...

What is the mechanism Angular utilizes to determine the exact location of directives within a webpage?

Can you explain how Angular is able to locate the directives on a webpage and establish connections with or observe those elements? I've searched through the DOM reference, but it seems like methods like getElementbySomething and querySelectorAll may ...

Unable to prepend '1' to the list

My goal is to display a list as '1 2 3...', but instead it is showing '0 1 2...' var totalLessons = $('.lesson-nav .mod.unit.less li').length; for (var i = 0; i < totalLessons; i++) { $('.lesson-nav .mod.unit.les ...

Vue.js Google Places Autocomplete Plugin

I'm currently working on integrating Google Places Autocomplete with Vue.js. According to the API documentation, the Autocomplete class requires an inputField:HTMLInputElement as its first parameter, like shown in their example: autocomplete = new g ...

Which is better: JQuery, YUI, or another option for JavaScript and CSS frameworks?

It's been about 6 years since I last dipped my toes into web development. Attempting to re-enter the field, I find myself overwhelmed by all the new technologies and trends. For my upcoming project, I've decided to go with Perl and Catalyst. The ...

Implementation of a recursive stream in fp-ts for paginated API with lazy evaluation

My objective involves making requests to an API for transactions and saving them to a database. The API response is paginated, so I need to read each page and save the transactions in batches. After one request/response cycle, I aim to process the data an ...