3

According to Hardhat Tutorial, while writing tests, some cases are written like

expect(await hardhatToken.totalSupply()).to.equal(ownerBalance);

while others are written

await expect(hardhatToken.transfer(addr1.address, 50)).to.changeTokenBalances(hardhatToken, [owner, addr1], [-50, 50]);

What is the rule behind positioning await statement in tests? When should it go before and when inside of expect() function?

1 Answer 1

4

You should use await inside expect when you want to use pre-fetched exact result for comparison.

You should use await outside expect when you want chai matchers to fetch the result in "the functions way".

1st example is about comparing two numbers, and its properly used inside the expect

2nd example requires chai matchers to do some additional checks, like fetching balance before and after, so the function cannot be pre-fetched and needs to be invoked by the matcher.

await outside is commonly used to test for reverts, because using it straight away would throw an exception, but the matcher will protect from that and check the result of the exception

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.