Search code examples
soliditytruffleopenzeppelin

How to properly test a revert for 'onlyOwner' modifier?


In my Solidity contract that inherits from OpenZeppelin's Ownable and AccessControl I have a function that the contract owner can call to give an account the ADMIN role. It looks like this:

function addAdmin(address account) public virtual onlyOwner {
   _grantRole(ADMIN, account);
}

In my test file I am using OpenZeppelin's test-environment and test-helper with Mocha and Chai. I'm trying to test for the failure of calling addAdmin() from a non-owner account. My test looks like this:

it('denies access to non-Owners to add a new ADMIN', async function() {
   await expectRevert(
      await pool.addAdmin(notlisted1, { from: notlisted2 }),
      "Ownable: caller is not the owner"
   );
});

It appears that addAdmin() correctly reverts but the test fails. The message I see at the command line when this test fails is:

Error: Returned error: VM Exception while processing transaction: revert Ownable: caller is not the owner -- Reason given: Ownable: caller is not the owner.

Any thoughts on what's going on here? Why doesn't the expectRevert() assert pass?


Solution

  • This was actually a simple mistake. Using await before pool.addAdmin() was incorrect. Removing that solved this issue.