Testing smart contract

We are going to talk about Mocha testing. Mocha is a JavaScript testing framework that is used for smart contracts. It is best practice to test your smart contracts so that you know that each function in your contract is working properly.

Testing with Hardhat

Testing is important like I mentioned above especially because money is at stake and once a contract is deployed it cannot be changed.

When we test with hardhat we use the Hardhat test network. This is a local ethereum network that is built into Hardhat.

Testing

  • create a directory called test
  • create a file called myToken.js

      describe("MyToken contract", function () {
        it("Deployment should assign the total supply of tokens to the owner", async function () {
          const [owner] = await ethers.getSigners();
    
          const MyToken = await ethers.getContractFactory("MyToken");
    
          const hardhatMyToken = await MyToken.deploy();
    
          const ownerBalance = await hardhatMyToken.balanceOf(owner.address);
          expect(await hardhatMyToken.totalSupply()).to.equal(ownerBalance);
        });
      });
    

Next run

$ npx hardhat test

    MyToken contract
      ✓ Deployment should assign the total supply of tokens to the owner (654ms)


    1 passing (663ms)

You should get this as the result and that means that the test passed. This is the basics of testing with hardhat.