DEV Community

Cover image for Mastering Smart Contract Testing: A Comprehensive Guide to Hardhat
Chandan | Web3 for BuildBear

Posted on

Mastering Smart Contract Testing: A Comprehensive Guide to Hardhat

In this Tutorial, you will learn how to test smart contracts using the Hardhat framework

Testing smart contracts is a crucial aspect of the development process to ensure that the contracts function correctly and are error-free. Hardhat is a development environment for Ethereum applications that offers various tools and libraries to facilitate smart contract testing.

Here are the benefits of testing smart contracts with Hardhat:

  1. Rapid Testing: Hardhat enables developers to create a local Ethereum blockchain for testing, resulting in quicker tests than on a live blockchain.
  2. Cost Savings: Testing on a local blockchain saves developers from paying for actual transactions on the live blockchain, resulting in significant cost savings.
  3. Control Over Testing Environment: Testing on a local blockchain gives developers complete control over the testing environment, including the option to reset the blockchain at any time.
  4. Integration: Hardhat seamlessly integrates with leading testing frameworks such as Mocha and Chai, making it easy for developers to write and run tests for their smart contracts.
  5. Flexibility: Hardhat provides several tools and libraries for testing smart contracts, allowing developers to select the testing approach that best suits their requirements.

To help you get started quickly, we have set up everything you need, from the contract to the test scripts, in this repository.

Let’s Cloning the Repo

1.1 Forking the Tutorial Repository:

  • Head over to our Tutorial Repository and click on the “Fork” button to create a copy of the repository on your own account. Wait for the forking process to finish before proceeding.

1.2 Cloning the repository locally:

  • Go to your forked repository on GitHub.
  • Click the “Code” button and copy the HTTPS or SSH URL.
  • Open your terminal or Git Bash.
  • Navigate to the directory where you want to clone the repository.
  • Run the below command to clone the Repo.
git clone <paste the URL you copied>
Enter fullscreen mode Exit fullscreen mode
  • Wait for the cloning process to complete. Once it’s done, you should see a new directory with the name of the repository in the directory.
  • To move into the cloned repository, use this commandcd <Name of the cloned Repo> , then move to the MultiContractTutorial folder using this commandcd MultiContractTutorial .

Image description
The structure of a Hardhat project folder typically includes the following:

  1. contracts/: This folder contains the Solidity source code for the project's contracts.
  2. test/: This folder contains the JavaScript test files for the smart contracts.
  3. hardhat.config.js: This is the primary configuration file for the Hardhat project. It specifies various options, such as the Ethereum network to use for deployment, the Solidity compiler to use, and the test runner to use.
  4. package.json: This file contains metadata about the project, such as the project's name, version, dependencies, and scripts.
  5. scripts/: This folder includes deployment scripts for deploying smart contracts using Hardhat.

Understanding The Testing Script

Image description
In the test folder, there are several test scripts that cover different smart contracts.

Let's start by understanding the simple-test.js script this is associated with SimpleStorage.sol contract.

Image description

In the first two lines of the script, we are importing the dependencies needed for testing:

  • Chai: used to write assertions for the contract testing.
  • Ethers: used to interact with Ethereum blockchain and to deploy smart contracts.

The script defines a describe block for a group of tests related to the SimpleStorage contract:

  • It gets the contract factory using ethers.getContractFactory("SimpleStorage").
  • Deploys a new instance of the "SimpleStorage" contract using simpleStorageFactory.deploy().

Image description

This code defines an it block, which is a single test within the describe block for the SimpleStorage contract. The test does the following:

  • Calls the retrieve function and stores the return value in currentValue.
  • Uses the assert function from the Chai library to assert that the currentValue.toString() is equal to 0.

In summary, this test checks the default value of favoriteNumber when the contract is deployed to be equal to zero.

Image description

The second test does the following:

  • Calls the store function on the contract instance with argument 7.
  • Calls the retrieve function and stores the return value in updatedValue.
  • Uses the assert function from the Chai library to assert that the updatedValue.toString() is equal to 7.

In summary, this test checks the store function of SimpleStorage contract and verifies whether it updates the favoriteNumber correctly by the specified number.

Similarly, in the fourth test block, we are testing the addPeople function.

ERC20 Token Testing

Image description

Let's understand the Token-test.js script.

In this script, we are testing the Token.sol contract.

The script is divided into two describe blocks:

Deployment:

  • This block is used to test the deployment of the contract and its properties after deployment.
  • Two tests are defined inside the describe block.
  • In the first test, we are checking whether the contract owner has the correct balance of tokens after deployment, which should be 1000 tokens.
  • In the second test, we are checking whether the total supply of the token is set to 1000.

Transactions:

  • This block is used to test the functionality of the Token contract methods such as transfer, balanceOf, and approve.
  • Three tests are defined inside the describe block.
  • In the first test, we are checking if the transfer method transfers tokens between accounts correctly.
  • In the second test, we are checking if the transfer method reverts if the sender doesn't have enough tokens to transfer.
  • In the third test, we are checking if the approve method updates the allowance for the buyer account correctly.

In summary, this test is checking the successful deployment of the Token contract and its functionality to transfer tokens between accounts, check the token balance, and update the allowance.

Running the Test

To install the necessary packages, please execute the following command:

npm install
Enter fullscreen mode Exit fullscreen mode

As per standard practices, hardhat test scripts are mostly executed locally, and this has a major drawback in that we can’t debug the failed transaction. So, we are going to use BuildBear.io. With BuildBear, all our transactions can be debugged easily using their in-built transaction tracer.

3.1 To start using BuildBear, visit the BuildBear App.

3.2. Create your Private Testnet forking from the Ethereum Mainnet, feel free to fork any Chain.

https://miro.medium.com/v2/resize:fit:588/1*2M9wY3bsj3uWxAX_sFSi4Q.png

3.3. Add your Private Testnet to your MetaMask wallet by using the “Add to Metamask” button:

https://miro.medium.com/v2/resize:fit:506/1*hhrVwlwyI22XrK1303-CDw.png

Update thehardhat.config.js .

  • Head to your Dashboard and click on “verify contract”.

https://miro.medium.com/v2/resize:fit:519/1*dclMYtIErTLTCPr2yzgI4A.png

https://miro.medium.com/v2/resize:fit:588/1*sKH90uducy-KiB9KrQXO-w.png

  • Copy the BuildBear and Etherscan objects, and update the [hardhat.config.js](https://github.com/BuildBearLabs/Tutorials/blob/main/NFTMarketplace/hardhat.config.js) file.

To run all the tests in your project, open your terminal and type the following command:

npx hardhat test
Enter fullscreen mode Exit fullscreen mode

This command will execute each test case in the project and output the results to the terminal.

If all tests pass successfully, you should see a long list of passing test results displayed in the terminal, like the example shown below:

Untitled

These results indicate that all of our tests have passed successfully.

CONGRATULATIONS! YOU HAVE LEARNED HOW TO TEST SMART CONTRACTS USING HARDHAT! 🎉🎉🎉

If you appreciate what we are doing, please follow us on Twitter, and LinkedIn and Join the Telegram group if you haven’t done yet.

And please give us a clap 👏 if you like our work.

Github Repo : Buildbear Tutorials

About BuildBear:

BuildBear is a platform for testing dApps at scale, for teams. It provides users with their own private Testnet to test their smart contracts and dApps, which can be forked from any EVM chain. It also provides a Faucet, Explorer, and RPC for testing purposes.

BuildBear aims to build an ecosystem of tools for testing dApps at scale for the teams.

Read our past articles and keep learning :

Authors: Chandan

Top comments (0)