How to Perform Unit Tests on Smart Contracts?

Unit Testing is the most crucial testing method to be carried out of every other testing method; There are many frameworks, tools, and libraries that help you in testing your application one of which is Hardhat. Hardhat helps in compiling and testing smart contracts at the very core. And also has its own built-in Hardhat Network (Local Ethereum Network design for development purposes). It also allows you to deploy contracts, run tests, and debugging of code.

Installing Hardhat

1. To install hardhat to the current project directory, run the following commands in your terminal.

npm init
npm install --save-dev hardhat

2. Next you need to set up your project in the current working directory in order to connect with the Hardhat development environment. For projects set up in the current directory, paste the below command in the command prompt by changing the directory to the current directory you want to set up your project.

npx hardhat

Select Create an empty hardhat.config.js with your keyboard and hit enter, once you’ve run the above command. hardhat.config.js file is important for a hardhat project.

Fig 1.1. Create Hardhat Project

3. Create three important folders in the working directory.

  • contracts: To create a smart contract.
  • scripts: To run deployment scripts.
  • tests: To run and test smart contracts using hardhat on the local blockchain, using JavaScript Framework ‘Mocha’.

Below is the expected folder structure:

Fig 1.2. Folder Structure

4. Other necessary installations (plugins) required, which help in developing a smart contract, testing, and creating an environment. To install it run this in your project working directory. Recommended for npm 7+ versions.

npm install --save-dev @nomicfoundation/hardhat-toolbox

For the npm 6 version or less, it might require installing a few more dependencies,

npm install --save-dev @nomicfoundation/hardhat-toolbox @nomicfoundation/hardhat-network-helpers @nomicfoundation/hardhat-chai-matchers @nomiclabs/hardhat-ethers @nomiclabs/hardhat-etherscan chai ethers hardhat-gas-reporter solidity-coverage @typechain/hardhat typechain @typechain/ethers-v5 @ethersproject/abi @ethersproject/providers

5. In case the above installation fails or shows errors like peer dependency conflict in the dependency tree, is most likely because of the npm version you have installed the error is most probably shown in the npm version above 7. Because npm version 7 and above treats peer dependency conflicts as errors. To tackle such a situation, install the npm version under 7.

OR

`npm install --leagacy-peer-deps`
`npm config set legacy-peer-deps true` to permanently resolve the error

6. Add the installed libraries/modules to hardhat.config.js file, add the ‘ require(“@nomicfoundation/hardhat-toolbox”); ‘ statement as shown below:

Javascript




require("@nomicfoundation/hardhat-toolbox");
module.exports = {
     solidity: "0.8.17",
 };


Contract Creation and Compile using Hardhat

Create any basic solidity smart contract under the contracts folder. For example:

Solidity




// SPDX-License-Identifier: UnLicensed
pragma solidity >=0.5.0 <0.9.0;
import "hardhat/console.sol";
contract Token{
    string public name  = "Hardhat Token";
    string public symbol  = "HHT";
    uint256 public totalSupply = 10000;
 
    address public owner;
 
    mapping (address => uint256) balances;
 
    constructor(){
        /* i.e the deployer will be the owner at first he can then transfer tokens to any
        other account addresses and he will have all the tokens in his wallet at first.*/
         
        balances[msg.sender] = totalSupply;
        owner = msg.sender;
    }
 
    function transfer(address to, uint256 amount) external {
        require(balances[msg.sender]>=amount, "Not enough tokens");
 
        console.log( "Transferring from %s to %s %s tokens",msg.sender,to,amount);
 
        balances[msg.sender] -= amount;
        balances[to] += amount;
 
    }
 
    function balanceOf(address account) external view returns (uint256) {
        return balances[account];
    }
     
}


Compile the smart contract to check if there are any errors or anomalies, using the hardhat compiler, use the following command,

npx hardhat compile

How to Test a Smart Contract for Ethereum?

Public Blockchains like Ethereum are immutable, it is difficult to update the code of a smart contract once it has been deployed. To guarantee security, smart contracts must be tested before they are deployed to Mainnet. There are several strategies for testing contracts, but a test suite comprised of various tools and approaches is suitable for detecting both minor and significant security issues in contract code.

Similar Reads

Smart Contract Testing

Smart contract testing is the process of ensuring that a smart contract’s code operates as intended. Testing is important for determining whether a certain smart contract meets standards for dependability, usability, and security. Approaches may differ, but most testing methods need to run a smart contract with a subset of the data it promises to handle. It is presumed that the contract is working properly if it gives correct outcomes for sample data. Most testing tools include resources for creating and executing test cases to determine if a contract’s execution matches the intended outcomes....

Importance of Testing a Smart Contract

Testing Smart Contracts is a critical and significant process in the development phase since it involves deploying it on the network every time and determining whether it works as expected or whether it needs some fine-tuning to enhance and satisfy its requirements....

Problems Due to Insufficient Smart Contracts Testing

Not testing smart contracts thoroughly can lead to various problems and vulnerabilities, including:...

Methods for Smart Contract Testing

Automated and manual testing approaches for Ethereum smart contracts can be coupled to develop a strong framework for contract analysis....

Formal Verification and Smart Contract Testing

Testing can help validate a smart contract’s expected behaviour for certain data inputs, but it cannot provide definitive proof for inputs that were not included in the tests. Therefore, testing alone cannot ensure the complete “functional correctness” of a program, meaning it cannot guarantee that the program will behave as intended for all possible input values....

Testing Tools and Libraries

Here are some tools and libraries for Unit Testing smart contracts:...

How to Perform Unit Tests on Smart Contracts?

Unit Testing is the most crucial testing method to be carried out of every other testing method; There are many frameworks, tools, and libraries that help you in testing your application one of which is Hardhat. Hardhat helps in compiling and testing smart contracts at the very core. And also has its own built-in Hardhat Network (Local Ethereum Network design for development purposes). It also allows you to deploy contracts, run tests, and debugging of code....

Testing of Smart Contract

...

Manual Testing: Deploying on Live Test Network & Local Hardhat Blockchain Environment

...