省流:请不要在hardhat测试的时候,beforeEach中还嵌套了loadFixture
背景:
在hardhat中,使用ethers.js测试一个改装过的erc20合约
今天碰到了一个很离谱的事情:
本英俊在部署一个erc20合约进行hardhat测试的时候,碰到了如上图所示的错误
百思不得其解
Error: call revert exception [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (method="name()", data="0x", errorArgs=null, errorName=null, errorSignature=null, reason=null, code=CALL_EXCEPTION, version=abi/5.7.0)
在第一个describe块中,总是出现莫名其妙的问题。
兄弟我测试一个symbol()函数
都会出现问题,搞了大半天。百思不得其解啊,毕竟第一个测试的name()函数
是好的。
后来赫然发现,为啥只有第一个函数成功了?然后把name()和symbol()调换一下位置
,结果就发现一个神奇的事情:symbol()可以运行了,name()不行
。
这时候我就猜测是夹具loadFixture
导致的问题,因为在下一个describe块中我没有嵌套夹具
,所以没有出现类似的问题。
所以,请不要在hardhat测试的时候,beforeEach中还嵌套了loadFixture,因为其本身就是起代替各类before、after的东西用的
hardhat关于夹具的原文:
The `loadFixture` helper in the Hardhat Network Helpers fixes both of these problems. This
helper receives a *fixture*, a function that sets up the chain to some desired state. The
first time `loadFixture` is called, the fixture is executed. But the second time, instead
of executing the fixture again, `loadFixture` will reset the state of the network to the
point where it was right after the fixture was executed. This is faster, and it undoes any
state changes done by the previous test.
该 `负载夹具` Hardhat Network Helpers中的helper解决了这两个问题。此帮助器接收 *夹具*将链设置为
某个所需状态的函数。第一次 `负载夹具` 则执行该夹具。但第二次,不是再次执行夹具, `负载夹具` 会将
网络的状态重置为刚好在执行夹具之后的点。这样更快,而且它撤消前一个测试所做的任何状态更改。
主要原因是为了解决beforeEach导致的速度慢和变量沟通难的问题
所以,你懂的,希望你不再踩坑,因为你快乐就是我快乐。