"Exploring the world of mocking module functions in Jest

I have been working on making assertions with jest mocked functions, and here is the code I am using:

const mockSaveProduct = jest.fn((product) => {
  //some logic
  return
});

jest.mock('./db', () => ({
  saveProduct: mockSaveProduct
}));

The assertion I want to make is:

expect(mockSaveProduct.mock.calls[0][0]).toBe(product)

However, I encountered the following error:

ReferenceError: Cannot access 'mockSaveProduct' before initialization at the line saveProduct: mockSaveProduct

Answer №1

jest.mock() gets hoisted. This means the code runs in the following way:

jest.mock('./db', () => {
  return {
    saveProduct: saveProductMock
  }
})

const saveProductMock = jest.fn((product) => {
  //someLogic
  return
});

//WAS HERE

One solution is to include the logic inside jest.mock();.

jest.mock('./db', () => {
    return {
        saveProduct: jest.fn((product) => {
            //someLogic
            return
        })
    }
})

Another option is to mock the entire module and then specify an explicit return value to use.

const db = require('./db');
jest.mock('./db');

it("example", () => {
    db.saveProduct.mockReturnValue(123);
    /** different types of return methods */
    // db.saveProduct.mockResolvedValue(123);

    const product = db.saveProduct();
    const expectedProduct = "xyz";
    expect(product).toBe(expectedProduct)
})

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

How can I gather information from members who have already signed up?

I have a form that submits data to the Angular Firebase database. Once the form is submitted, I want to display the previously submitted data in the form if the user signs in again. Below is my .ts file: import { Component, OnInit } from '@angular/c ...

Creating a Dynamic Canvas Rendered to Fit Image Dimensions

I'm struggling with a piece of code that creates an SVG and then displays it on a canvas. Here is the Jsbin Link for reference: https://jsbin.com/lehajubihu/1/edit?html,output <!DOCTYPE html> <html> <head> <meta charset=&qu ...

Transferring Data Between Two Forms

Is there a way to transfer data between two HTML forms? For example, let's say we have two forms: Form 1: Contains a field for name and a submit button. Form 2: Contains fields for name, email, and a submit button. I would like to be able to fill o ...

JavaScript not functioning properly for the Sibice challenge on Kattis

Currently, I am in the process of learning JavaScript and a friend recommended trying out Kattis for solving tasks, even though it might not be ideal for JS. As part of this challenge called Sibice, the goal is to determine if matches will fit into a box. ...

Issue with API showing return value as a single value instead of an array

My database consists of collections for Teachers and Classes. In order to fully understand my issue, it's important to grasp the structure of my database: const TeacherSchema = new Schema( { name: { type: String, required: true } ...

Do individual JavaScript script tags operate independently of one another in terms of error handling?

My main goal is to establish a connection to my server using websockets and send messages to the browser for remote page reloads. I want to ensure that this code runs independently of any other errors on the page, allowing me to remotely refresh the page i ...

Having trouble with sending a post request through ajax

Whenever I try to initiate an Ajax request upon clicking a button, the request never seems to get executed. Below is the snippet of my HTML code : <!DOCTYPE html> <html lang="en"> <head> <title>User Form</title> ...

Other options for positioning background in SVG or using CSS within SVG could include center center alignment settings

I am currently developing a website where I have a div covered by an SVG. When I use this SVG as a background image and apply background-position: center center, it functions as expected. However, my issue arises when I try to add additional CSS in this ma ...

FoxyWeb Requests: Utilizing XMLHttpRequest in Firefox Extensions

While I've come across plenty of examples on how to create xhr requests from Firefox Add-ons, I'm currently exploring the new WebExtensions framework (where require and Components are undefined) and facing an issue with sending a simple XmlHttpRe ...

Better ways to conceal notifications as soon as a new one appears with Toastr

Whenever a new notification pops up in my application, I desire for the previous one to automatically disappear. It is crucial for only one notification to be displayed at any given time. Is there a way to accomplish this using toastr? ...

Execute a grandchild function in Angular that triggers its grandparent function

I'm currently working with a component structure that looks like this: Component A -> Component B -> Component C Within the template of Component C, there is a button that triggers a function in the 'code behind' when clicked. My goal is ...

Is this jQuery script not functioning properly?

I came across this code on jsfiddle, and I really want to incorporate it into my PHP file. However, when I tried to do so, it didn't work even though I simply copied and pasted the code without making any changes. Here is my code: <!DOCTYPE html& ...

Manufacturing TypeScript classes that are returned by a factory

Developed a custom library that generates classes based on input data and integrates them into a main class. To enhance code maintainability and readability, the logic for generating classes has been extracted into a separate file that exports a factory f ...

``Why Ionic 3 Popover Sizes Should Adapt to Different Screen

Currently in my Ionic 3 project, I am utilizing a popover with a set height using the following code snippet: editOpty(rw){ let popover = this.editOptyPopup.create(EditOptyPopoverComponent, rw, { cssClass: 'edit-opty-popover'}); popover ...

Utilizing Angular 2+ to effectively manipulate the HTML Document Object Model with JavaScript in order to execute scripts

I'm facing an issue with inserting a script into my Angular project that has a specific format. <script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-events.js"> { "width": "510", "height": "600", "impo ...

Guide on utilizing the h function in Vue3 for seamless binding and passing of properties and events from parent to child components

Utilizing Vue3 and naive ui for front-end development has been a challenge for me as I primarily focus on back-end development and lack expertise in front-end technologies. To enhance user interaction, I incorporated naive ui’s BasicTable along with an ...

Attempting to extract decibel levels from an audio file using JavaScript

I've been exploring the details provided here: Is there a way get something like decibel levels from an audio file and transform that information into a json array? However, when attempting to execute the JSBin snippet below, I encountered some conf ...

A guide on importing images into a CSS file with Reactjs

Currently, I am utilizing Reactjs (Nextjs) and have placed my images folder within the "public" directory. In my "style.css" file, I adjusted the path for the image, but unfortunately it is not displaying. Can you please help me identify where I may have ...

What causes the HTML element's X position value to double when its X position is updated after the drag release event in Angular's CDK drag-drop feature?

I am facing a challenge with an HTML element that has dual roles: Automatically moving to the positive x-level whenever an Obsarbalve emits a new value. Moving manually to both positive and negative x-levels by dragging and dropping it. The manual drag a ...

React - Refreshing a component with the help of another component

I've created a NavBar component that contains a list of links generated dynamically. These links are fetched from the backend based on specific categories and are stored within a child component of NavBar named DrawerMenu. The NavBar itself is a chil ...