Search code examples
mocha.jsblockchainsmartcontractshardhat

Chain tests in mocha framework with smart contract testing


I am doing smart contract testing with hardat and mocha framework. Suppose I have two following it blocks testing contract A.

it('test1', () => {
  contractA.updateValue(val);
  // some other testing code
});
it('test2', () => {
  contractA.useUpdatedValue();
  // some other testing code
}); 

Here, contracA is defined in the global scope. Is there a way to persist the smart contract state in test1 and then do test2 to use the updated state of the smart contract?


Solution

  • You could probably create a global contractA variable for this, but I don't know if this is a good approach. Generally it tests are independent of one another for various reasons. And tools also assume they are independent. If you really wanted to, then at the very least you would need to run the mocha tests using https://mochajs.org/api/mocha#bail.

    Or much better is using the fixtures feature of Waffle: https://ethereum-waffle.readthedocs.io/en/latest/fixtures.html

    If you were creating a sample app with Hardhat, then you are already using Waffle. Further explanations can be seen here https://soliditydeveloper.com/waffle.