Home > Net >  How to mock ethers.js provider for metamask detection in tests?
How to mock ethers.js provider for metamask detection in tests?

Time:11-17

I want to write a test for metamask detection:

const provider = new ethers.providers.Web3Provider(window.ethereum, "any");
const signer = provider.getSigner();
const address = await signer.getAddress() //Get metamask address from browser

So I think I need to mock ethers provider and somehow inject a fake address that I can later assert. Any ideas?

I've tried multiple libraries but nothing seemed to work for my case.

Thanks!

CodePudding user response:

Something like this should solve your problem

import { ethers } from "ethers";
import mocked = jest.mocked;


const mockGetSigner = jest.fn();
const mockGetFunction = jest.fn();

mockGetAddress.mockImplementation(() = {
   return { address object or string not sure}
})

mockGetSigner.mockImplementation(() => {
      return { getAddress: mockGetAddress };
    });

 mocked(ethers.providers. Web3Provider).mockImplementation(() => {
      return { getSigner: jest.fn() };
    });

jest.mock("ethers", () => {
  return {
    ...jest.requireActual("ethers"),
    ethers: {
      Contract: jest.fn(),
      Wallet: jest.fn(),
      providers: {
        Web3Provider: jest.fn(),
      },
    },
  };
});
  • Related