Solidity – Test Fails with Custom Error Despite Having MyCustomError: Diagnosis and Fixes

custom-errorshardhatsolidity

I'm writing a test that requires enterRaffle() to be reverted with MyCustomError – "Raffle__NotEnoughEthEntered"

describe("enterRaffle", async function () {
              it("reverts when you don't pay enough", async function () {
                  await expect(raffle.enterRaffle()).to.be.revertedWith(
                      "Raffle__NotEnoughEthEntered"
                  )
              })
          })

The test fails with error;

1) Raffle
       enterRaffle
         reverts when you don't pay enough:
     AssertionError: Expected transaction to be reverted with reason 'Raffle__NotEnoughEthEntered', but it reverted with a custom error
      at processTicksAndRejections (node:internal/process/task_queues:96:5)
      at Context.<anonymous> (test/unit/Raffle.test.js:32:19)

Why is Raffle__NotEnoughEthEntered not a custom error?

I have read other similar issues but they don't solve my problem.

Raffle.sol error & enterRaffle
error Raffle__NotEnoughEthEntered();

////////////////////////////////////////////////////////////////////////////////////////////////////

function enterRaffle() public payable {
        // you can do this,
        //require (msg.value > i_enteranceFee, "Not Enough ETH!")

        // but we will use error codes for gas efficiency since storing strings if supper expensive
        if (msg.value < i_enteranceFee) {
            revert Raffle__NotEnoughEthEntered();
        }

        if (s_raffleState != RaffleState.OPEN) {
            revert Raffle__NotOpen();
        }
        s_players.push(payable(msg.sender));

        //Emit an event when we update a dynamic array or mapping
        //name events with fuction name reversed. in this case event RaffleEnter()
        emit RaffleEnter(msg.sender);
    }

Best Answer

as far as I know to.be.revertedWith is used for catching string errors. To expect a Custom Error you need to use to.be.revertedWithCustomError(contractInstance,NameOfTheCustomError). Also if the custom error have args you can add .withArgs(..args).

You can check an example for the use in the lsp-smart-contract repo.

Check the hardhat config file to see which package to use. I assume it's @nomicfoundation/hardhat-toolbox.

Related Topic