Hardhat Solidity Unit Testing: A Complete Developer Guide

Hardhat Solidity Unit Testing: A Complete Developer Guide

Smart contracts are immutable once deployed. A bug in production doesn't just break your app—it can drain wallets, lock funds permanently, or destroy user trust overnight. This is why unit testing Solidity with Hardhat isn't optional; it's the foundation of every serious blockchain project.

In this guide, you'll learn how to set up Hardhat for Solidity testing, write comprehensive unit tests using Mocha and Chai, handle edge cases, test for reverts, and structure your test suite for maintainability. Every concept comes with working code you can drop into your project today.

Why Hardhat for Solidity Testing?

Hardhat is the dominant development environment for Ethereum smart contracts. It ships with:

  • A built-in Ethereum network (Hardhat Network) that runs locally at full speed
  • First-class TypeScript support
  • Stack traces for failed transactions—something that was painful to get before
  • Console.log inside Solidity during testing
  • A plugin ecosystem covering coverage, gas reporting, and contract verification

Compared to Truffle (now deprecated by Consensys) and Foundry, Hardhat sits at the sweet spot of JavaScript familiarity and EVM fidelity. If your team already writes JavaScript or TypeScript, the learning curve is minimal.

Project Setup

Install Hardhat and its peer dependencies:

mkdir my-contracts && cd my-contracts
npm init -y
npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox
npx hardhat init

Choose "Create a JavaScript project" when prompted. Hardhat generates the standard structure:

contracts/    ← Solidity source files
scripts/      ← deployment scripts
test/         ← your test files
hardhat.config.js

The @nomicfoundation/hardhat-toolbox bundles ethers.js, Waffle matchers, Chai, Mocha, and TypeChain—everything needed to write and run tests without hunting for plugins.

The Contract Under Test

Let's work with a realistic contract: a simple ERC-20 token with minting permissions.

// contracts/GovernanceToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract GovernanceToken is ERC20, Ownable {
    uint256 public constant MAX_SUPPLY = 1_000_000 * 10 ** 18;
    mapping(address => bool) public minters;

    event MinterAdded(address indexed minter);
    event MinterRemoved(address indexed minter);

    error NotMinter(address caller);
    error ExceedsMaxSupply(uint256 requested, uint256 available);

    constructor(address initialOwner)
        ERC20("Governance Token", "GOV")
        Ownable(initialOwner)
    {}

    modifier onlyMinter() {
        if (!minters[msg.sender]) revert NotMinter(msg.sender);
        _;
    }

    function addMinter(address minter) external onlyOwner {
        minters[minter] = true;
        emit MinterAdded(minter);
    }

    function removeMinter(address minter) external onlyOwner {
        minters[minter] = false;
        emit MinterRemoved(minter);
    }

    function mint(address to, uint256 amount) external onlyMinter {
        uint256 available = MAX_SUPPLY - totalSupply();
        if (amount > available) revert ExceedsMaxSupply(amount, available);
        _mint(to, amount);
    }
}

Install OpenZeppelin contracts:

npm install @openzeppelin/contracts

Writing Your First Test File

// test/GovernanceToken.test.js
const { expect } = require("chai");
const { ethers } = require("hardhat");
const { loadFixture } = require("@nomicfoundation/hardhat-toolbox/network-helpers");

describe("GovernanceToken", function () {
  // Fixtures reset state between tests without redeploying from scratch
  async function deployTokenFixture() {
    const [owner, minter, user1, user2] = await ethers.getSigners();

    const GovernanceToken = await ethers.getContractFactory("GovernanceToken");
    const token = await GovernanceToken.deploy(owner.address);

    return { token, owner, minter, user1, user2 };
  }

  describe("Deployment", function () {
    it("should set the correct name and symbol", async function () {
      const { token } = await loadFixture(deployTokenFixture);
      expect(await token.name()).to.equal("Governance Token");
      expect(await token.symbol()).to.equal("GOV");
    });

    it("should assign ownership to the deployer", async function () {
      const { token, owner } = await loadFixture(deployTokenFixture);
      expect(await token.owner()).to.equal(owner.address);
    });

    it("should start with zero total supply", async function () {
      const { token } = await loadFixture(deployTokenFixture);
      expect(await token.totalSupply()).to.equal(0n);
    });
  });

Testing Access Control

Access control is one of the most common sources of exploits. Test every permission boundary explicitly:

  describe("Minter Management", function () {
    it("owner can add a minter", async function () {
      const { token, owner, minter } = await loadFixture(deployTokenFixture);

      await expect(token.connect(owner).addMinter(minter.address))
        .to.emit(token, "MinterAdded")
        .withArgs(minter.address);

      expect(await token.minters(minter.address)).to.be.true;
    });

    it("non-owner cannot add a minter", async function () {
      const { token, user1, minter } = await loadFixture(deployTokenFixture);

      await expect(
        token.connect(user1).addMinter(minter.address)
      ).to.be.revertedWithCustomError(token, "OwnableUnauthorizedAccount")
        .withArgs(user1.address);
    });

    it("owner can remove a minter", async function () {
      const { token, owner, minter } = await loadFixture(deployTokenFixture);

      await token.connect(owner).addMinter(minter.address);
      await expect(token.connect(owner).removeMinter(minter.address))
        .to.emit(token, "MinterRemoved")
        .withArgs(minter.address);

      expect(await token.minters(minter.address)).to.be.false;
    });
  });

Testing the Core Mint Logic

  describe("Minting", function () {
    async function minterReadyFixture() {
      const base = await deployTokenFixture();
      await base.token.connect(base.owner).addMinter(base.minter.address);
      return base;
    }

    it("minter can mint tokens to a user", async function () {
      const { token, minter, user1 } = await loadFixture(minterReadyFixture);
      const amount = ethers.parseEther("1000");

      await expect(token.connect(minter).mint(user1.address, amount))
        .to.changeTokenBalance(token, user1, amount);
    });

    it("non-minter cannot mint", async function () {
      const { token, user1, user2 } = await loadFixture(minterReadyFixture);
      const amount = ethers.parseEther("100");

      await expect(
        token.connect(user1).mint(user2.address, amount)
      ).to.be.revertedWithCustomError(token, "NotMinter")
        .withArgs(user1.address);
    });

    it("reverts when minting exceeds MAX_SUPPLY", async function () {
      const { token, minter, user1 } = await loadFixture(minterReadyFixture);
      const maxSupply = await token.MAX_SUPPLY();
      const overAmount = maxSupply + 1n;

      await expect(
        token.connect(minter).mint(user1.address, overAmount)
      ).to.be.revertedWithCustomError(token, "ExceedsMaxSupply")
        .withArgs(overAmount, maxSupply);
    });

    it("allows minting exactly MAX_SUPPLY over multiple calls", async function () {
      const { token, minter, user1, user2 } = await loadFixture(minterReadyFixture);
      const half = (await token.MAX_SUPPLY()) / 2n;

      await token.connect(minter).mint(user1.address, half);
      await token.connect(minter).mint(user2.address, half);

      expect(await token.totalSupply()).to.equal(await token.MAX_SUPPLY());
    });
  });

Testing Token Transfers

Don't assume OpenZeppelin handles everything. Test integration with your contract's state:

  describe("Transfers", function () {
    it("user can transfer tokens they own", async function () {
      const { token, minter, user1, user2 } = await loadFixture(deployTokenFixture);
      await token.connect(owner).addMinter(minter.address);
      const amount = ethers.parseEther("500");
      await token.connect(minter).mint(user1.address, amount);

      await expect(token.connect(user1).transfer(user2.address, amount))
        .to.changeTokenBalances(
          token,
          [user1, user2],
          [-amount, amount]
        );
    });

    it("reverts transfer when balance is insufficient", async function () {
      const { token, user1, user2 } = await loadFixture(deployTokenFixture);

      await expect(
        token.connect(user1).transfer(user2.address, 1n)
      ).to.be.revertedWithCustomError(token, "ERC20InsufficientBalance");
    });
  });
});

Running Tests and Measuring Coverage

Run your full suite:

npx hardhat test

For gas reporting (invaluable for optimization):

REPORT_GAS=true npx hardhat test

For coverage with Istanbul:

npx hardhat coverage

Coverage output shows which Solidity lines, branches, and functions were exercised. Aim for 100% branch coverage on access control and numerical boundary conditions.

Using Hardhat's Time Manipulation

Many contracts have time-dependent logic—vesting, locks, governance delays. Hardhat Network lets you manipulate block time:

const { time } = require("@nomicfoundation/hardhat-toolbox/network-helpers");

it("cannot claim before vesting period ends", async function () {
  // fast-forward 30 days
  await time.increase(30 * 24 * 60 * 60);
  // now test the time-gated function
});

Debugging with console.log

Add import "hardhat/console.sol"; to any Solidity file to print during tests:

import "hardhat/console.sol";

function mint(address to, uint256 amount) external onlyMinter {
    console.log("Minting %s tokens to %s", amount, to);
    // ...
}

These logs appear only when running tests—they compile away in production if you remove the import.

Test Organization Best Practices

Use fixtures over beforeEach deploy calls. loadFixture snapshots EVM state after the first run and restores the snapshot for subsequent tests, making your suite significantly faster.

Name tests as behaviors, not implementations. "reverts when minting exceeds MAX_SUPPLY" is better than "test mint boundary".

Test the unhappy path as much as the happy path. For every function call that can revert, write a test that hits that revert. Custom errors introduced in Solidity 0.8 are strongly typed—use revertedWithCustomError instead of revertedWith for string matching.

Separate concerns with nested describe blocks. Group deployment, access control, core logic, and edge cases. When a test fails, you can pinpoint the area immediately.

Continuous Integration

Add this to your GitHub Actions workflow:

# .github/workflows/test.yml
name: Hardhat Tests
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      - run: npm ci
      - run: npx hardhat test
      - run: npx hardhat coverage

Never merge a PR that breaks tests. Smart contracts that hit production with untested paths are liabilities, not features.

What's Next

Hardhat unit testing covers the deterministic layer—given these inputs, assert these outputs. But real contracts interact with other contracts, price oracles, and liquidity pools. The next testing layer is fuzzing, where you throw thousands of random inputs at your contract to find edge cases your unit tests couldn't anticipate. That's covered in the Foundry fuzzing guide linked below.

Unit tests in Hardhat give you speed, JavaScript familiarity, and a tight feedback loop. Keep your suite fast, keep it green, and deploy with confidence.

Read more

Start now free