Mocking default constructor in Jest

Here is some code I'm struggling with:

import Web3 from 'web3';

jest.mock('web3', ()=>{
    return jest.fn().mockImplementation(()=>'Hello, world!')
});

describe('app', ()=>{
    test('mock web3', ()=>{
        console.log('web3:', Web3);
        let web3 = new Web3(window.ethereum);
        console.log("new web3:", web3);
    });
});

package.json:

{
    "name": "test",
    "dependencies": {
        "react-scripts": "5.0.1",
        "web3": "^1.7.5"
    },
    "devDependencies":{
    },
    "scripts": {
        "test": "react-scripts test"
    }
}

If you run npm i && npm test;, the first console.log shows the module is mocked. However, the second console.log is not what I expected:

new web3: mockConstructor {}

Instead, I was hoping for:

new web3: "Hello, world!"

I've tried various solutions, like moving the import below jest.mock and using const Web3 = require('web3');. Removing the require or import results in a failure as anticipated.

I've looked at similar questions on Stack Overflow, like Jest : mock constructor function and Jest mock a constructor. However, those examples deal with named imports, whereas I'm working with a default import.

Do you have any suggestions on how to mock the Web3 constructor successfully?

Answer №1

It appears that utilizing a jest.fn in this manner is not functioning as expected. Despite numerous resources indicating that it should work, it appears to be a potential issue. As an alternative solution, consider using a standard function:

jest.mock('web3', ()=>{
    return function notJestFn() {return 'Hello, world!';}
});

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

Getting data from a wordpress database using javascript

After setting up a table named inspirationWall in my database with id and Visit_Count as INT, I inserted a row with id=1 and Visit_Count = 2. Now, attempting to fetch the Visit_Count value in WordPress and show it in an alert for testing purposes. I have ...

What is the best location to create the content for a sidebar?

Currently in the process of building my new website using express. The layout consists of various "sections" such as a blog, project information, and more. I want to have a unique sidebar next to the main content for each section. For instance, in the "blo ...

The inclusion of a content editable feature within a carousel is leading to unexpected event propagation

I am dynamically creating an editable div using the code snippet below. <div class='reflection-field' contenteditable="true" data-number="${index}"></div> Expected Outcome: When I click on the generated div, I anticipate that the c ...

Making modifications to the database will trigger real-time updates in the web interface. How is it possible to achieve this seamlessly?

Can someone please help me understand how to automatically insert news or new events from a Facebook page as an event in a webpage? I am a programmer and currently, the data is retrieved from the database using AJAX without reloading the page. However, I ...

Establish a predetermined selection for a radio button and its associated checkbox option

I am working on a React material UI group input field that is mapping a dataset. The result consists of one radio button and one checkbox performing the same action. Initially, I attempted to set the state to establish one data item as default. While I fol ...

Simple solution for storing key-value pairs temporarily in a form using JQuery

Is there an elegant method to temporarily store an array of string values in a form? In my article editing form, users can add tags as string values. I don't want these tags to be persisted until the user saves the entire article, so I require a way ...

I'm currently troubleshooting the code for the Gallery project. The gallery is supposed to have 4x4 grids, but for some reason, the grids are

It seems like I am struggling to identify the exact issue. The display on mobile looks fine but not on desktop. I attempted to tweak the isotope configuration without success. Even manipulating the server-side code didn't reveal any obvious problems. ...

vue-router: error encountered while attempting to load asynchronous component for rendering

I'm new to vue-router and having trouble getting it to work. When I try to start my app, these errors pop up: [vue-router] Failed to resolve async component render: TypeError: _vm is undefined 49:16:39 [vue-router] uncaught error during route navigat ...

Is it possible to perform a PHP redirect after the headers have been

I am encountering an issue with a function that needs to redirect the page once a variable is set. The challenge arises from the fact that this function is located at the bottom of the PHP page. As a result, I have already displayed a significant amount ...

The Google Apps Script will activate only on weekdays between the hours of 10 AM and 5 PM, running every hour

function Purchase() { var ss=SpreadsheetApp.getActive(); var sheet=ss.getSheetByName("Buy"); var Cvalues=sheet.getRange(2,3,sheet.getLastRow()-1,1).getValues(); var Avalues=sheet.getRange(2,1,sheet.getLastRow()-1,1).getValues(); var r ...

I encountered an issue while attempting to utilize a JavaScript script - I received an error message stating "Uncaught ReferenceError: jQuery is not defined."

Currently, I am utilizing a template with multiple pages and I need to use one of them. I followed all the necessary steps correctly, but I encountered an error in the console that says Uncaught ReferenceError: jQuery is not defined. Below is my HTML scrip ...

Showing a collection of cards within a dynamic container set up in a 3x3 grid layout to start

In an attempt to showcase cards within a responsive container utilizing bootstrap and django, my goal is to create a 3x3 grid layout on extra-large screens with scrollable overflow that adjusts based on device width. Initially, I experimented with wrapping ...

What are the best practices for utilizing "async/await" and "promises" in Node.js to achieve synchronous execution?

I'm fairly new to the world of web development and still grappling with concepts like promises and async/await. Currently, I'm working on a project to create a job posting site, but I've hit a roadblock trying to get a specific piece of code ...

Encountered an error involving the SequenceExpression node type while using Jest

While adding a snapshot test to my React code, I encountered an unexpected error message: Unexpected node type: SequenceExpression (This is an error on an internal node. Probably an internal error. Location has been estimated.) The code transpiles withou ...

How can you fix the "bad value" response in mongodb when utilizing query parameters in the url?

{ "ok": 0, "code": 2, "codeName": "BadValue", "name": "MongoError" } Whenever I attempt to use query parameters skip and limit in the url, this error message pops up. localhost:5 ...

What is the best way to connect individual buttons to a dynamic div that displays different content depending on the button clicked?

Hey there! I'm diving into the world of JavaScript and HTML, and I need some guidance on creating a menu that can toggle visibility of specific content in div(s) depending on which button (picture1-12) is clicked. My idea is to have one div that can d ...

Effortlessly switching classes in JavaScript for seamless transitions

I'm currently working on an animation project where I want the title to be visible on the page initially, and then slowly fade away as you scroll down, with a subtitle fading in right after. While I've managed to get the title part working, I&apo ...

Guide on comparing a string value with a date in the format of YYYY-MM-DD using protractor in a node js environment

In my application, I am retrieving the date field in string format using the getText() function. I need assistance in determining whether the captured date is earlier than the current date. Can someone provide guidance on this? var actDate = locator.getTex ...

Unexpected net::ERR_CONNECTION_REFUSED error occurs when trying to access the server, even though the server is functioning correctly. This

There seem to be numerous discussions on this topic already, so I apologize if this is redundant. What's peculiar and potentially unique (although I can't be sure) is that the server appears to be operational and handling the API call correctly. ...

Guide to creating a nested table with JavaScript

Currently, I am utilizing JavaScript to dynamically generate a table. To better explain my inquiry, here is an example of the HTML: <table id='mainTable'> <tr> <td> Row 1 Cell 1 </td> ...