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?