0
0
Blockchain / Solidityprogramming~30 mins

Hardhat testing setup in Blockchain / Solidity - Mini Project: Build & Apply

Choose your learning style9 modes available
Hardhat Testing Setup
📖 Scenario: You are building a simple smart contract project using Hardhat. To make sure your contract works correctly, you want to write tests. This project will guide you step-by-step to set up the testing environment in Hardhat.
🎯 Goal: Set up a Hardhat project with a basic test file that checks if the contract deploys successfully.
📋 What You'll Learn
Create a Hardhat project with npm init -y and install hardhat
Create a sample contract file
Write a test file using Mocha and Chai
Run the test and see the output
💡 Why This Matters
🌍 Real World
Testing smart contracts before deploying them to a blockchain helps catch bugs early and saves money.
💼 Career
Blockchain developers must write and run tests to ensure their contracts work correctly and securely.
Progress0 / 4 steps
1
Initialize Hardhat Project
Run npm init -y to create a package.json file and then install Hardhat by running npm install --save-dev hardhat. After that, create a Hardhat project by running npx hardhat and choose create a basic sample project. This will create the initial project files including hardhat.config.js.
Blockchain / Solidity
Need a hint?

Use your terminal to run the commands exactly as shown to set up the Hardhat project.

2
Create a Sample Contract
Delete the default contracts/Lock.sol and test/Lock.js files. Create a new file called contracts/SimpleStorage.sol with this exact Solidity code:
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 public storedData;

    function set(uint256 x) public {
        storedData = x;
    }

    function get() public view returns (uint256) {
        return storedData;
    }
}
Blockchain / Solidity
Need a hint?

Make sure the contract file is saved exactly as contracts/SimpleStorage.sol with the given code.

3
Write a Test for the Contract
Create a test file called test/sample-test.js with this exact JavaScript code:
const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("SimpleStorage", function () {
  it("Should deploy and set value correctly", async function () {
    const SimpleStorage = await ethers.getContractFactory("SimpleStorage");
    const simpleStorage = await SimpleStorage.deploy();
    await simpleStorage.deployed();

    await simpleStorage.set(42);
    expect(await simpleStorage.get()).to.equal(42);
  });
});
Blockchain / Solidity
Need a hint?

Make sure the test file is saved exactly as test/sample-test.js with the given code.

4
Run the Test and See the Output
Run the test by executing npx hardhat test in your terminal. You should see output that shows the test passed with a message like 1 passing.
Blockchain / Solidity
Need a hint?

Use your terminal to run npx hardhat test and look for the message 1 passing to confirm the test passed.