【问题标题】:how to run the rest of the test code after a failed call to the contract in hardhat?在安全帽中调用合约失败后如何运行其余的测试代码?
【发布时间】:2022-11-02 05:58:12
【问题描述】:

我正在尝试使用 js 在安全帽中为我的智能合约编写一个测试,我想检查一些东西以防我的合约调用失败问题是当“失败的合约调用”行运行时它会恢复整个块测试并且不会运行它的其余部分。 我怎样才能让它工作?

some code 1
await contract.function()
// contract call fails intentionally
some code 2

我需要“一些代码 2”的结果,但我只是收到一个错误,即调用失败。

【问题讨论】:

    标签: javascript testing solidity hardhat evm


    【解决方案1】:

    这是测试的标准要求,只需使用chai,不要创建自己的测试引擎。 https://www.chaijs.com/api/bdd/

    【讨论】:

    • 据我所知,即使使用 Chai,如果期望失败,整个测试也会失败,这不是真的吗?
    【解决方案2】:

    假设您使用的是 Hardhat Chai Matchers 扩展,您可以使用 expect() 验证函数调用恢复

    • to.be.reverted
    • to.be.revertedWith()
    • to.be.revertedWithPanic()
    • to.be.revertedWithCustomError()
    • to.be.revertedWithoutReason()

    例子:

    it("fails to call the function", async () => {
        await expect(
            contract.function()
        ).to.be.revertedWith("Custom revert message");
    });
    

    文档:https://hardhat.org/hardhat-chai-matchers/docs/overview#reverts

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-05
      • 2021-06-05
      • 2022-12-23
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多