Last active
May 2, 2023 16:59
-
-
Save johnnyshankman/7c10d5699992e10daa56f1d7829f4ac4 to your computer and use it in GitHub Desktop.
Catch and assert the value of any custom error thrown by a smart contract in Truffle unit testing by using just the built in web3.js module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const expectCustomRevertError = async function(promise, expectedErrorSignature) { | |
try { | |
await promise; | |
} catch (error) { | |
const encoded = web3.eth.abi.encodeFunctionSignature(expectedErrorSignature); | |
const returnValue = Object.entries(error.data).filter(it=>it.length>1).map(it=>it[1]).find(it=>it!=null && it.constructor.name==="Object" && "return" in it).return | |
assert.equal(returnValue, encoded); | |
return; | |
} | |
expect.fail('Expected an exception but none was received'); | |
} | |
// Usage | |
await expectCustomRevertError( | |
contract.someMethod(), | |
"TheCustomError()" // In Solidity: error TheCustomError(); | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment