如何在测试之间重置 Hardhat 的主网分叉?
How do I reset Hardhat's mainnet fork between tests?
我正在使用 Hardhat 的主网分支在 Hardhat 中编写单元测试,但似乎一项测试的结果正在影响未来的测试并导致我的断言失败。我正在使用 Alchemy 和区块 #14189520 进行分叉。
例如:
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);
});
有没有办法重置主网分叉,以便每个测试都从新的分叉状态开始?
您可以在 beforeEach()
方法中使用 hardhat_reset
重置主网分叉,如下所示:
beforeEach(async function () {
await network.provider.request({
method: "hardhat_reset",
params: [
{
forking: {
jsonRpcUrl: <ALCHEMY_URL>,
blockNumber: <BLOCK_NUMBER>,
},
},
],
});
});
it("Test 1", async function () {
...
}
您也可以使用此方法从不同的区块编号进行分叉或仅禁用分叉。 Here's the relevant section from the Hardhat docs.
我正在使用 Hardhat 的主网分支在 Hardhat 中编写单元测试,但似乎一项测试的结果正在影响未来的测试并导致我的断言失败。我正在使用 Alchemy 和区块 #14189520 进行分叉。
例如:
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);
});
有没有办法重置主网分叉,以便每个测试都从新的分叉状态开始?
您可以在 beforeEach()
方法中使用 hardhat_reset
重置主网分叉,如下所示:
beforeEach(async function () {
await network.provider.request({
method: "hardhat_reset",
params: [
{
forking: {
jsonRpcUrl: <ALCHEMY_URL>,
blockNumber: <BLOCK_NUMBER>,
},
},
],
});
});
it("Test 1", async function () {
...
}
您也可以使用此方法从不同的区块编号进行分叉或仅禁用分叉。 Here's the relevant section from the Hardhat docs.