How to mock a ethereum provider for unit testing of REST API?

REST API has following basic structure(index.js)where provider,wallets are created using web3HttpProvider and etherjs when server is started.

Solution tried: index.test.js

const web3HttpProvider= require ("web3-providers-http)
return provider;});

console.log("test:",new web3HttpProvider(url,null));});

Error:Which results in web3HttpProvider is not a constructor.


const web3HttpProvider=require("web3-providers-http");
const {ethers}= require ("ethers");

const app= express();
var provider=new web3HttpProvider (url,options);
var deploymentProvider= new ethers.providers.Web3Provider(provider);
Var wallet= new ethers.Wallet(privatekey, deploymentProvider);
var contractInstance= new ethers.Contract(address,abi,wallet);

var response=await instance.greeting();

app.listen(port,()=>{console.log("server listening")});

2 Answers 2


This library should help you with that https://github.com/rsksmart/mock-web3-provider


I had this same issue using Web3Modal. I solved it by partially mocking a class, more info in the Jest docs page. I'm sure you can apply this same concept to web3HttpProvider

In my connectWallet.test.js file I have the following:

This const declaration corresponds to a class named InjectedRepository with a connectWallet method:

const InjectedRepository = {
   connectWallet: () => {
     return {
        account: "0x22933773a6020feb3bc10d4c8c8d47b033fa20cc",
        hasWallet: true,
        isActive: true,
        isCorrectChain: true,
        isWalletConnected: true,
        library: "Web3Provider",
        provider: "Proxy",
        selectedChain: "undefined",
        signer: "JsonRpcSigner",

Later, I use jest.mock to point to the actual class, and then returns the previous declared varaible instead(InjectedRepository):

jest.mock("../blockchain/repositories/InjectedRepository", () => {
  return { InjectedRepository }

Hope it helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.