0

Say I want to make a test for this sample contract:

// assume we import OpenZeppelin's Ownable

contract Metaverse extends Ownable, ... {
    ...
    // Assume this is just to experiment and learn.
    // Then I can question myself how useful is to
    // actually do this, and why.
    function renounceOwnership() public override onlyOwner {
        revert("I explicitly disabled this method");
    }
    ...
}

And, using trufflesuite I want to make a test for when the method reverts:

const Metaverse = artifacts.require("Metaverse");

contract("Metaverse", function (accounts) {
  const deployer = accounts[0];
  const newOwner = accounts[1];

  it("respects the safe-ownership appropriately", async function () {
    let metaverse = await Metaverse.deployed();

    try
    {
      metaverse.renounceOwnership({from: deployer});
      assert.fail("Ownership should not be rejected");
    }
    catch(e) { /* Ok :) - It will be an AssertionError */ }
  });
});

So far, this WORKS, but I want to make it cleaner. So I divide my question in two:

  1. Is there a STANDARD AND CLEANER/BETTER way to assert when a method reverts?
  2. If not: How do I test that e is of type AssertionError? Where do I import that assertion error from?

1 Answer 1

1

You can use Waffle with the revertedWith Chai Matcher: https://ethereum-waffle.readthedocs.io/en/latest/matchers.html#revert-with-message

An example for this can be seen here: https://github.com/gnosis/safe-contracts/blob/main/test/libraries/MultiSend.spec.ts#L51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.