How do I reset Hardhat's mainnet fork between tests?
Asked Answered
R

1

5

I'm writing unit tests in Hardhat using Hardhat's mainnet fork, however it seems that the results from one test are affecting future tests and causing my assertions to fail. I'm forking using Alchemy and from block #14189520.

For example:

it("Test 1", async function () {
    const provider = ethers.provider;
    const [owner, addr1] = await ethers.getSigners();

    // Assert owner has 1000 ETH to start
    ownerBalance = await provider.getBalance(owner.address);
    expectedBalance = ethers.BigNumber.from("10000000000000000000000");
    assert(ownerBalance.eq(expectedBalance));

    // Send 1 Ether to addr1
    sendEth(1, owner, addr1);
});

it("Test 2", async function () {
    const provider = ethers.provider;
    const [owner, addr1] = await ethers.getSigners();

    // ownerBalance is now only 999 Eth because of previous test
    ownerBalance = await provider.getBalance(owner.address);
});

Is there a way I can reset the mainnet fork so each test starts from a fresh forked state?

Reggi answered 9/4, 2022 at 19:25 Comment(0)
R
7

You can reset the mainnet fork by using hardhat_reset in the beforeEach() method, like so:

beforeEach(async function () {
  await network.provider.request({
    method: "hardhat_reset",
    params: [
      {
        forking: {
          jsonRpcUrl: <ALCHEMY_URL>,
          blockNumber: <BLOCK_NUMBER>,
        },
      },
    ],
  });
});

it("Test 1", async function () {
   ...
}

You can also use this method to fork from a different block number or just disable forking. Here's the relevant section from the Hardhat docs.

Reggi answered 9/4, 2022 at 19:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.