openzeppelin-test-helpers: expectRevert should be able to check for custom errors

Since 0.8.4 we have use of new and cheap custom errors https://blog.soliditylang.org/2021/04/21/custom-errors/

Using them in contract code, but in test I need to use expectRevert.uspecified to handle them in any way.

Reproduce:

pragma solidity ^0.8.4;

contract Test {
    uint256 public num;
    error CustomErrorMessage();

    function willThrowOnZero(uint256 param) external {
        if (param == 0) revert CustomErrorMessage();
        num = param;
    }
}
const { contract } = require('@openzeppelin/test-environment');

const { expectRevert } = require('@openzeppelin/test-helpers');

const Test = contract.fromArtifact('Test');

describe('Custom test', function () {
    let test;
    before(async function () {
        test = await Test.new();
    })
    describe('Test check', function () {
        it('throws on zero', async function () {
            await expectRevert.unspecified(test.willThrowOnZero('0'))
        })
        it('passes on non-zero', async function () {
            await test.willThrowOnZero('1');
        })
        it('can not catch error name', async function () {
            await expectRevert(test.willThrowOnZero('0'), "CustomErrorMessage")
        })
    })
})

Test running throws: image

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 1
  • Comments: 18 (5 by maintainers)

Most upvoted comments

Well, alright. Anyways, I created a separate library for this: https://www.npmjs.com/package/custom-error-test-helper It’s based on rsodre’s code, but supports decoding errors with parameters, too.