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

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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1