Hardhat Unit Testing for Solidity: A Practical Deep Dive
Smart contract bugs cost real money. The DAO hack lost $60 million. The Parity wallet freeze locked $150 million permanently. These weren't theoretical vulnerabilities — they were code that nobody tested thoroughly enough. If you're building on Ethereum or any EVM-compatible chain, unit testing isn't optional. It's the difference between shipping a product and shipping a liability.
Hardhat is the de facto standard for Solidity development and testing. This guide walks through everything you need to write production-quality unit tests: environment setup, ethers.js integration, ERC-20 token testing, constructor validation, event assertions, access control checks, and revert testing.
Setting Up the Hardhat Test Environment
Start with a fresh project or add Hardhat to an existing one:
mkdir my-contract && cd my-contract
npm init -y
npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox
npx hardhat initChoose "Create a JavaScript project" or "Create a TypeScript project". The toolbox package bundles everything you need: ethers.js v6, Chai assertions, Hardhat Network Helpers, and the coverage plugin.
Your hardhat.config.js should look like this:
require("@nomicfoundation/hardhat-toolbox");
module.exports = {
solidity: {
version: "0.8.24",
settings: {
optimizer: {
enabled: true,
runs: 200,
},
},
},
networks: {
hardhat: {
chainId: 31337,
},
},
};Tests live in the test/ directory. Run them with:
npx hardhat test
npx hardhat test --grep "ERC20" # filter by name
npx hardhat coverage # with coverage reportThe Contract Under Test: A Simple ERC-20 Token
Let's build tests for a standard ERC-20 token with some additions — minting controlled by an owner, a burn function, and an event for large transfers.
// contracts/MyToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract MyToken is ERC20, Ownable {
uint256 public constant MAX_SUPPLY = 1_000_000 * 10**18;
uint256 public constant LARGE_TRANSFER_THRESHOLD = 10_000 * 10**18;
event LargeTransfer(address indexed from, address indexed to, uint256 amount);
constructor(
string memory name,
string memory symbol,
uint256 initialSupply,
address initialOwner
) ERC20(name, symbol) Ownable(initialOwner) {
require(initialSupply <= MAX_SUPPLY, "Exceeds max supply");
_mint(initialOwner, initialSupply);
}
function mint(address to, uint256 amount) external onlyOwner {
require(totalSupply() + amount <= MAX_SUPPLY, "Exceeds max supply");
_mint(to, amount);
}
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
function _update(
address from,
address to,
uint256 value
) internal override {
super._update(from, to, value);
if (value >= LARGE_TRANSFER_THRESHOLD && from != address(0)) {
emit LargeTransfer(from, to, value);
}
}
}Install OpenZeppelin:
npm install @openzeppelin/contractsWriting Unit Tests: Structure and Setup
Each test file imports the contract factory and test helpers. The loadFixture pattern is critical — it snapshots the blockchain state after deployment so each test starts clean without redeploying:
// test/MyToken.test.js
const { expect } = require("chai");
const { ethers } = require("hardhat");
const { loadFixture } = require("@nomicfoundation/hardhat-toolbox/network-helpers");
describe("MyToken", function () {
async function deployTokenFixture() {
const [owner, addr1, addr2] = await ethers.getSigners();
const initialSupply = ethers.parseEther("500000"); // 500,000 tokens
const MyToken = await ethers.getContractFactory("MyToken");
const token = await MyToken.deploy(
"My Token",
"MTK",
initialSupply,
owner.address
);
return { token, owner, addr1, addr2, initialSupply };
}
// Tests go here...
});ethers.parseEther("500000") converts to the correct 18-decimal representation. Always use this — never hardcode raw wei values in tests.
Testing Constructor Parameters
Constructor tests verify your contract initializes correctly. Test the happy path and every require condition:
describe("Deployment", function () {
it("Should set the correct name and symbol", async function () {
const { token } = await loadFixture(deployTokenFixture);
expect(await token.name()).to.equal("My Token");
expect(await token.symbol()).to.equal("MTK");
});
it("Should assign initial supply to the owner", async function () {
const { token, owner, initialSupply } = await loadFixture(deployTokenFixture);
expect(await token.balanceOf(owner.address)).to.equal(initialSupply);
expect(await token.totalSupply()).to.equal(initialSupply);
});
it("Should set the correct owner", async function () {
const { token, owner } = await loadFixture(deployTokenFixture);
expect(await token.owner()).to.equal(owner.address);
});
it("Should revert when initial supply exceeds MAX_SUPPLY", async function () {
const [owner] = await ethers.getSigners();
const tooMuch = ethers.parseEther("1000001"); // 1 token over max
const MyToken = await ethers.getContractFactory("MyToken");
await expect(
MyToken.deploy("My Token", "MTK", tooMuch, owner.address)
).to.be.revertedWith("Exceeds max supply");
});
it("Should allow deployment with exactly MAX_SUPPLY", async function () {
const [owner] = await ethers.getSigners();
const maxSupply = ethers.parseEther("1000000");
const MyToken = await ethers.getContractFactory("MyToken");
const token = await MyToken.deploy("My Token", "MTK", maxSupply, owner.address);
expect(await token.totalSupply()).to.equal(maxSupply);
});
});The boundary test — deploying with exactly MAX_SUPPLY — is the kind of edge case that catches off-by-one bugs in require conditions.
Testing ERC-20 Transfer Behavior
Standard ERC-20 operations need coverage for approvals, allowances, and edge cases:
describe("Transfers", function () {
it("Should transfer tokens between accounts", async function () {
const { token, owner, addr1 } = await loadFixture(deployTokenFixture);
const amount = ethers.parseEther("1000");
await token.transfer(addr1.address, amount);
expect(await token.balanceOf(addr1.address)).to.equal(amount);
expect(await token.balanceOf(owner.address)).to.equal(
ethers.parseEther("499000")
);
});
it("Should fail when sender has insufficient balance", async function () {
const { token, addr1, addr2 } = await loadFixture(deployTokenFixture);
// addr1 has zero tokens
await expect(
token.connect(addr1).transfer(addr2.address, ethers.parseEther("1"))
).to.be.revertedWithCustomError(token, "ERC20InsufficientBalance");
});
it("Should update allowances correctly", async function () {
const { token, owner, addr1, addr2 } = await loadFixture(deployTokenFixture);
const allowance = ethers.parseEther("5000");
await token.approve(addr1.address, allowance);
expect(await token.allowance(owner.address, addr1.address)).to.equal(allowance);
const transferAmount = ethers.parseEther("3000");
await token.connect(addr1).transferFrom(owner.address, addr2.address, transferAmount);
expect(await token.allowance(owner.address, addr1.address)).to.equal(
ethers.parseEther("2000")
);
});
});Note the difference: revertedWith for string errors, revertedWithCustomError for OpenZeppelin's custom errors. Using the wrong one causes tests to fail even when the contract behavior is correct.
Testing Events with emit
Events are the primary communication channel between contracts and off-chain systems. Test them explicitly:
describe("Events", function () {
it("Should emit Transfer event on transfer", async function () {
const { token, owner, addr1 } = await loadFixture(deployTokenFixture);
const amount = ethers.parseEther("1000");
await expect(token.transfer(addr1.address, amount))
.to.emit(token, "Transfer")
.withArgs(owner.address, addr1.address, amount);
});
it("Should emit LargeTransfer for transfers above threshold", async function () {
const { token, owner, addr1 } = await loadFixture(deployTokenFixture);
const largeAmount = ethers.parseEther("15000"); // above 10,000 threshold
await expect(token.transfer(addr1.address, largeAmount))
.to.emit(token, "LargeTransfer")
.withArgs(owner.address, addr1.address, largeAmount);
});
it("Should NOT emit LargeTransfer for small transfers", async function () {
const { token, owner, addr1 } = await loadFixture(deployTokenFixture);
const smallAmount = ethers.parseEther("500"); // below threshold
await expect(token.transfer(addr1.address, smallAmount))
.to.not.emit(token, "LargeTransfer");
});
it("Should emit Transfer event on mint (from zero address)", async function () {
const { token, owner, addr1 } = await loadFixture(deployTokenFixture);
const mintAmount = ethers.parseEther("1000");
await expect(token.mint(addr1.address, mintAmount))
.to.emit(token, "Transfer")
.withArgs(ethers.ZeroAddress, addr1.address, mintAmount);
});
});The .to.not.emit() assertion is underused but critical. If your business logic gates on a threshold, you need to verify both sides of that gate.
Testing Access Control (onlyOwner)
Access control failures are a major attack surface. Test every restricted function from both authorized and unauthorized callers:
describe("Access Control", function () {
it("Should allow owner to mint tokens", async function () {
const { token, owner, addr1 } = await loadFixture(deployTokenFixture);
const mintAmount = ethers.parseEther("10000");
await token.mint(addr1.address, mintAmount);
expect(await token.balanceOf(addr1.address)).to.equal(mintAmount);
});
it("Should revert when non-owner tries to mint", async function () {
const { token, addr1, addr2 } = await loadFixture(deployTokenFixture);
await expect(
token.connect(addr1).mint(addr2.address, ethers.parseEther("1000"))
).to.be.revertedWithCustomError(token, "OwnableUnauthorizedAccount")
.withArgs(addr1.address);
});
it("Should allow owner to transfer ownership", async function () {
const { token, owner, addr1 } = await loadFixture(deployTokenFixture);
await token.transferOwnership(addr1.address);
expect(await token.owner()).to.equal(addr1.address);
});
it("Should prevent old owner from minting after ownership transfer", async function () {
const { token, owner, addr1 } = await loadFixture(deployTokenFixture);
await token.transferOwnership(addr1.address);
await expect(
token.connect(owner).mint(owner.address, ethers.parseEther("1000"))
).to.be.revertedWithCustomError(token, "OwnableUnauthorizedAccount");
});
it("Should allow new owner to mint after transfer", async function () {
const { token, owner, addr1 } = await loadFixture(deployTokenFixture);
await token.transferOwnership(addr1.address);
const mintAmount = ethers.parseEther("5000");
await token.connect(addr1).mint(addr1.address, mintAmount);
expect(await token.balanceOf(addr1.address)).to.equal(mintAmount);
});
});The ownership transfer chain test is important — it verifies both that access is correctly revoked from the old owner and granted to the new one.
Testing Revert Conditions with revertedWith
Testing every revert path is non-negotiable. Untested reverts mean untested protection:
describe("Revert Conditions", function () {
it("Should revert mint when total supply would exceed MAX_SUPPLY", async function () {
const [owner] = await ethers.getSigners();
const maxSupply = ethers.parseEther("1000000");
const MyToken = await ethers.getContractFactory("MyToken");
// Deploy with max supply
const token = await MyToken.deploy("My Token", "MTK", maxSupply, owner.address);
// Try to mint even 1 more token
await expect(
token.mint(owner.address, 1n)
).to.be.revertedWith("Exceeds max supply");
});
it("Should revert burn when balance is insufficient", async function () {
const { token, addr1 } = await loadFixture(deployTokenFixture);
// addr1 has no tokens
await expect(
token.connect(addr1).burn(ethers.parseEther("1"))
).to.be.revertedWithCustomError(token, "ERC20InsufficientBalance");
});
it("Should allow burning the exact balance", async function () {
const { token, owner, addr1 } = await loadFixture(deployTokenFixture);
const amount = ethers.parseEther("1000");
await token.transfer(addr1.address, amount);
await token.connect(addr1).burn(amount);
expect(await token.balanceOf(addr1.address)).to.equal(0n);
});
it("Should revert transferFrom without approval", async function () {
const { token, owner, addr1, addr2 } = await loadFixture(deployTokenFixture);
await expect(
token.connect(addr1).transferFrom(
owner.address,
addr2.address,
ethers.parseEther("100")
)
).to.be.revertedWithCustomError(token, "ERC20InsufficientAllowance");
});
});Running the Full Test Suite
npx hardhat test
# Output:
# MyToken
# Deployment
# ✓ Should set the correct name and symbol (123ms)
# ✓ Should assign initial supply to the owner
# ✓ Should set the correct owner
# ✓ Should revert when initial supply exceeds MAX_SUPPLY
# ✓ Should allow deployment with exactly MAX_SUPPLY
# Transfers
# ...
#
# 23 passing (2s)For coverage:
npx hardhat coverage
# Coverage report shows line/branch/function/statement coverage
# Aim for 100% branch coverage on security-critical codeGas Testing
Hardhat can assert gas usage to catch unexpected gas regressions:
it("Should use less than 60000 gas for a standard transfer", async function () {
const { token, owner, addr1 } = await loadFixture(deployTokenFixture);
const tx = await token.transfer(addr1.address, ethers.parseEther("100"));
const receipt = await tx.wait();
expect(receipt.gasUsed).to.be.lessThan(60000n);
});This prevents "optimization" changes from accidentally making transfers expensive.
What to Test Next
With unit tests in place, the next layer is integration testing — deploying your contract in a forked mainnet environment and testing interactions with real DeFi protocols. But that's only possible once your unit tests pass completely. A forked network test that fails is harder to debug precisely because there's more moving pieces.
Start here. Get every unit test green. Then expand outward.
The cost of a bug in production is measured in ETH. The cost of a test is measured in minutes. There's no better ROI in smart contract development.