0

I have a smart contract that implements OZ's onlyOwner modifier for several functions. I am testing it using truffle and have written a unit test where a non-owner account calls an onlyOwner function.

it("non-owner cannot create race", async () => {
        const instance = await raceFactory.deployed();
        const race = await instance.createUpcomingRace({from: accounts[1]});
        assert.equal(????);
    });

The response is exactly what I wanted: Error: Returned error: VM Exception while processing transaction: revert Ownable: caller is not the owner -- Reason given: Ownable: caller is not the owner.

What is the correct way to catch this exception in the test above so that this error gives a passing test?

1

You could use expectRevert from @openzeppelin/test-helpers.

Example from GitHub:

it('reverts when transferring tokens to the zero address', async function () {
    // Conditions that trigger a require statement can be precisely tested
    await expectRevert(
      // TX expected to revert
      this.erc20.transfer(constants.ZERO_ADDRESS, this.value, { from: sender }),
      // expected revert message
      'ERC20: transfer to the zero address',
    );
  });

For your code:

it("non-owner cannot create race", async () => {
        const instance = await raceFactory.deployed();
        await expectRevert(instance.createUpcomingRace({from: accounts[1]}), "Ownable: caller is not the owner");
    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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