4

I am testing some deployment features of my contracts, and I would like to reset the local hardhat network to initial state between some of the tests, in particular, to clear out all previously deployed contracts from the test net. (I am not using an independent note -- ust the one that gets created when you type hh test.)

Is there a way to do this inside a test suite, rather than having to rerun it all together?

GGizmos
  • 741
  • 6
  • 23

2 Answers2

9

Use hardhat_reset in a beforeEach hook:

describe("suite", function () {
  beforeEach(async function () {
    await hre.network.provider.send("hardhat_reset")
  })

it("first test", function () { // Fresh instance of the hardhat network

// Send txs

})

it("second test", function () { // Fresh instance of the network again

// The txs sent in the previous test won't 
// be reflected here.

}) })

Franco Victorio
  • 2,862
  • 17
  • 27
-2

Yes to do this you should search for Mocha test and Chai to see how it's made.

Basicaly

Mytest(){

beforeEach() =>{

// deploy a new instanse }

it() =>{ // run a test on this deployment instance. }

}

// here your previous deployment don't exist anymore // it will not reset you eth balance.

Here is an example of what these test looks like and you can take as example to start testing.

https://github.com/MadeInDreams-Team/idecentralize/blob/master/test/Token.test.js

I doub't that the process that runs inside the HRE can trigger the resset of the node. Never seen it done.

If your looking to automate a series of test. The best place to do it would be within task.

task( "My task", ... =>{
// run test one script
// reset node
// run test 2 script
}
MadeInDreams
  • 1,500
  • 1
  • 9
  • 19
  • Um, this is basically untrue. I know how to writte a test, but it doesn't automatically reset the entire chain to the state it was in when you initially start your test suite. deployed contracts are still on chain, accounts lose value throughout your tests.As it turns out there is a way to reset HRE to initial state. await hre().network.provider.send("hardhat_reset"); – GGizmos Oct 27 '21 at 00:16
  • Yes but that wont happen within the test. You could make several test and run a reset between them that would make sense. But not reset the node while the test is running inside the node. I guess your looking to automate your testsuite right? – MadeInDreams Oct 27 '21 at 00:41
  • You use reset within the test suite. For example if you want to reset the local node between each test, you can put it in beforeEach() – GGizmos Oct 27 '21 at 02:27