Testing – How to Test for Custom Error Reverts in Hardhat with Detailed Steps

custom-errorshardhattestingwaffle

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})`)

Best Answer

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