2

In my hardhat project I'm testing my smart contracts using chai.

For the sake of simplicity let's assume my contract is:

contract MyContract {

  function a() external {
    b();
  }

  function b() public{
  }

}

I'm testing function a and would like to make sure that function b has been called once (from a), something like:

//ACT
await myContract.a();
//ASSERT
expect(b).to.have.been.calledOnce

How can I achieve this?

2 Answers 2

1

if by called once you mean you want to be sure it has been called at least once by your tests, then you could use coverage which will tell you if each branch of code has been tickled by your tests.

https://www.npmjs.com/package/coverage

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |    95.15 |    79.52 |      100 |    95.09 |                   |
 index.js |     90.6 |    75.38 |      100 |    90.52 |... 44,148,152,156 |
 lib.js   |      100 |    94.44 |      100 |      100 |               107 |
----------|----------|----------|----------|----------|-------------------|

if you don't get 100 in % Branch, you can look at the index.html report created in the coverage directory to see what was missed.

It's a cracking tool and very easy to use. If you're using hardhat, instead of

npx hardhat test

it's

npx hardhat coverage

which runs your tests but adds the coverage to it

1
  • Thanks, I need this to be an automated test while your solution is manual.
    – forhas
    Commented Jun 7, 2022 at 14:09
1

This is not answer I just lack reputation to comment 😄

There's no Sinon like thing for Solidity smart contracts as far as I know, so my take would be trying to assert results of invoking b() by actually invoking a().

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.