0

I want to test whether my smart contract functions return the correct error messages

example function in solidity

function transform (uint256 input) public returns (uint256){
require (input>1, "the value has to be greater than 1"
}

However, when i try to test whether a value of 0 triggers the correct error message, my test fails.

expect(await contract.connect(addr1).transform(0)).to.throw("values smaller than 1 are not allowed");

The error I am receiving:

 1 passing (828ms)
  1 failing

  1) Minting of Tokens
       transform should throw the correct errors:
     Error: VM Exception while processing transaction: reverted with reason string 'values smaller than 1 are not allowed'
    at ProjectL.mintLottoSchein (contracts/tests.sol:104)
    at EdrProviderWrapper.request (node_modules\hardhat\src\internal\hardhat-network\provider\provider.ts:446:41)
    at HardhatEthersSigner.sendTransaction (node_modules\@nomicfoundation\hardhat-ethers\src\signers.ts:125:18)
    at send (node_modules\ethers\src.ts\contract\contract.ts:313:20)
    at Proxy.mintLottoSchein (node_modules\ethers\src.ts\contract\contract.ts:352:16)
    at Context.<anonymous> (test\test.js:42:14)

Could someone please help me out?

thx

2
  • What’s the error that you’re getting? Commented Jun 25 at 12:27
  • I added it to the original question
    – PupSt4r
    Commented Jun 25 at 12:36

1 Answer 1

0

You need to use .to.be.revertedWith and the exact error string used in the require, like:

expect(await contract.connect(addr1).transform(0)).to.be.revertedWith("the value has to be greater than 1");

P.S., You have to install @nomicfoundation/hardhat-chai-matchers dependency, if it’s not installed already.

3
  • Can you share the minimum reproducible code via GitHub, so that I can try debugging the same on my end? Commented Jun 26 at 5:56
  • 1
    It works now. In your code example, the "await" keyword is at the beginning of the line. In my code, the "await" was inside the expect() function. I changed it accordingly and then received an error that led me to install @nomicfoundation/hardhat-chai-matchers. Now it works perfectly. thank you for your help!
    – PupSt4r
    Commented Jun 26 at 6:18
  • Great. Thanks for pointing out. I’ve edited the answer accordingly. Commented Jun 26 at 6:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.