如何使用Hardhat和Chai测试Solidity异常



我是Solidity的新手。我有一个非常简单的合同,正在做一些验证

function withdraw(uint amount) external {
uint balance = wallets[msg.sender];
require(balance >= amount, "Pool: not enough balance");
....

我想测试一下,所以试过这样的

try {
await sut.connect(lp1).withdraw(utils.parseUnits("500000000000"))
} catch(e) {
console.log(e)
}

但它给了我以下错误

未捕获的运行时间错误:中止(错误:处理时出现VM异常事务:已还原,原因字符串为"池:余额不足"(。有关详细信息,请使用-s ASSERTIONS=1进行构建。

我的try/catch似乎不起作用。我试着期望(…(.to.throw((,但结果是一样的。

看起来好像有什么东西在VM级别中断了,JS没有什么可做的。我用的是硬帽、打字和柴。

知道吗?我试图找到一个解决方案,但一无所获。。。这很奇怪,测试这种情况很常见。

感谢

试试这个。首先使用您喜欢的软件包管理器(yarn-xD(安装ethereum-waffle

import { solidity } from "ethereum-waffle";
import { use, expect } from "hardhat";
use(solidity);
describe("...", async () => {
it("...", async () => {
await expect(erc721.tokenURI(0)).to.be.revertedWith("ERC721: the token does not exist");
});
}
`

我找到了一种方法,可能是因为我按照承诺使用了types/chai

const withdraw = sut.connect(lp1).withdraw(utils.parseUnits("500"))
await expect(withdraw).eventually.to.rejectedWith(Error, "VM Exception while processing transaction: reverted with reason string 'Pool: not enough balance'")

诀窍不是在预期内等待,然后使用最终.to.rejectedWith

最新更新