4

I have a custom error described as such:

error AlreadyListed(address nftAddress, uint256 tokenId);

And in my tests, I'd like to check to see that it's thrown:

expect(await nftMarketplace.listItem(basicNft.address, TOKEN_ID, PRICE)).to.be.revertedWith(`AlreadyListed`)

However, this of course fails with:

 Error: VM Exception while processing transaction: reverted with custom error 'AlreadyListed("0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512", 0)

Do I need to string interpolate with quotes and such, or is there a better way? This looks ugly:

expect(await nftMarketplace.listItem(basicNft.address, TOKEN_ID, PRICE)).to.be.revertedWith(`AlreadyListed("${basicNft.address}", ${TOKEN_ID})`)

2 Answers 2

5

Try moving the await before the expect. e.g.

await expect(nftMarketplace.listItem(basicNft.address, TOKEN_ID, PRICE)).to.be.revertedWith(`AlreadyListed`)

That's what my tests use for custom errors

Hope this helps

3
  • Facepalm... Thank you Mar 9 at 2:10
  • this worked. any idea why it didn't worked when written "await" inside bracket? May 25 at 11:50
  • Anything inside the parenthesis will be fully executed before being passed into expect(). Thus, if awaiting the call will fail, expect() will never even be called to check. Instead, we just pass in the Promise<> to expect() and await for expect() to decide what to do -- which it is fully capable of catching and comparing Promise<> errors when used with .to.be.revertedWith() May 26 at 13:36
1

Update to selected answer

await expect(contract.call()).to.be.revertedWithCustomError(
  contract,
  "SomeCustomError"
);

got from hardhat docs https://hardhat.org/hardhat-chai-matchers/docs/overview

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.