iTranslated by AI
Tips: Simplifying Smart Contract Testing with Regular Expressions
In this article, I will share some tips on using regular expressions when performing contract tests with Hardhat.
Actually, the chai library used in the Hardhat testing environment has a feature to test whether a certain string matches a regular expression instead of a plain string.
Therefore, by utilizing this feature, you can write your tests more smartly, although its application is limited.
Let's Put It Into Practice
For example, an error from OpenZeppelin's AccessControl contract when a role is not assigned follows this format:
AccessControl: account accountAddress is missing role roleHash
And if you expect an error in the above format in a certain test, writing the code straightforwardly would look like this:
...
await expect(transasction).to.revertedWith(
`AccessControl: account ${addres} is missing role ${roleHash}`
);
...
This test can be written using a regular expression like this:
...
// Expected to return an error because the role is missing.
const ERROR_MISSING_ROLE =
/AccessControl: account 0x(.*) is missing role 0x(.*)/;
await expect(transasction).to.revertedWith(ERROR_MISSING_ROLE);
...
In this code, representing the error from AccessControl with a regular expression makes the code more elegant.
I believe this becomes even more effective when testing the same error repeatedly, as you can reuse the same regular expression.
Conclusion
By using the tips introduced this time, I think you can write slightly cooler code.
This method is not applicable everywhere; since most contract errors in the world are constants, there is often no need to use regular expressions in the first place, but I hope you keep it in the back of your mind.
Discussion