Mastering Smart Contract Testing: A Comprehensive Guide to Hardhat
Published: 2023-05-11 05:21:38



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](https://github.com/BuildBearLabs/Tutorials).

**Let’s Cloning the Repo**

1.1 Forking the Tutorial Repository:

- Head over to our [Tutorial Repository](https://github.com/BuildBearLabs/Tutorials) 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>
```

- 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 command`cd <Name of the cloned Repo>` , then move to the MultiContractTutorial folder using this command`cd MultiContractTutorial` .

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fjpdna9dqfbrvmapohew.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u78zbxe73xs7fdq31edi.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7tfjbvyelhqxjrqa313p.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kpiziak8dddi66pitkax.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s0inbjbgjcb3wy9e3vxh.png)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3wba5kplhvimlqg8gy3c.png)



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
```

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](http://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](https://buildbear.io/)**.

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](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](https://miro.medium.com/v2/resize:fit:506/1*hhrVwlwyI22XrK1303-CDw.png)

Update the`hardhat.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:519/1*dclMYtIErTLTCPr2yzgI4A.png)

![https://miro.medium.com/v2/resize:fit:588/1*sKH90uducy-KiB9KrQXO-w.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
```

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](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/ee72e0bd-8226-46db-b397-a115e5f0d40a/Untitled.png)

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](https://twitter.com/_BuildBear), and [LinkedIn](https://www.linkedin.com/company/build-bear/) and [Join the Telegram](https://t.me/+6mjOnBFUR9xjN2U1) group if you haven’t done yet.

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

Github Repo : [Buildbear Tutorials](https://github.com/BuildBearLabs/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 :**

- **[Learn how to Create, Deploy an NFT Smart Contract and Develop a Front End App in 15mins](https://medium.com/buildbear/learn-how-to-create-deploy-an-nft-smart-contract-and-develop-a-front-end-app-in-15mins-a7d9c2a16237)**
- **[Learn how to create, Deploy a Soul Bound Token(SBT)](https://medium.com/buildbear/find-out-what-is-sbt-auth-and-learn-to-create-your-own-system-12c5f65e40b7)**
- **[Generate NFT with AI and Deploy the NFT smart contract, and the Front End App](https://medium.com/buildbear/generate-nft-with-ai-and-deploy-the-nft-smart-contract-and-the-front-end-app-94c64a93d8b1)**
- **[Learn, code, and deploy your own MultiSig Wallet](https://medium.com/buildbear/learn-code-and-deploy-your-own-multisig-wallet-and-test-it-with-your-friends-now-cb86cdcb8c8)**
- **[Let’s understand Subscription NFTs and mint a few](https://medium.com/buildbear/lets-understand-subscription-nfts-and-mint-a-few-6ae9e695a1fc)**

Authors: [Chandan](https://twitter.com/chandan1_)