Writing Unit Tests
This lesson walks through writing unit tests in Hardhat with Mocha, Chai and ethers.js: deploying contracts, using several signers, and asserting return values, state, events, reverts and balance changes. It ends with the equivalent Solidity test.
Learning outcomes
After completing this lesson, you will be able to:
- Describe the structure of a Hardhat Mocha test.
- Choose Chai matchers for events, reverts and balance changes.
- Describe how access control is tested.
- Describe the structure of a Solidity test.
Structure of a Hardhat test
A Mocha test file connects to a network, groups tests with describe and writes each case with it. The following test checks a simple bank contract.
import { expect } from "chai";
import { network } from "hardhat";
const { ethers, networkHelpers } = await network.create();
describe("Bank", function () {
async function deployBank() {
const [owner, alice, bob] = await ethers.getSigners();
const bank = await ethers.deployContract("Bank");
return { bank, owner, alice, bob };
}
it("records deposits", async function () {
const { bank, alice } = await networkHelpers.loadFixture(deployBank);
await bank.connect(alice).deposit({ value: ethers.parseEther("1") });
expect(await bank.balances(alice.address)).to.equal(ethers.parseEther("1"));
});
});network.create() creates a fresh simulated network for this file. ethers.getSigners() returns funded accounts, and bank.connect(alice) sends the next transaction from Alice. Values from ethers.js are BigInt, so comparisons use BigInt values, such as ethers.parseEther("1") or literals like 10n.
Reading a Hardhat test
Assertions for events, reverts and balances
The Hardhat Chai matchers extend expect with assertions about transactions. The following table lists the most used ones.
| Matcher | Checks |
|---|---|
.to.emit(contract, "Event").withArgs(...) | The transaction emitted the event with these arguments |
.to.be.revertedWithCustomError(contract, "Error") | It reverted with the custom error (optionally .withArgs) |
.to.be.revertedWith("message") | It reverted with this reason string |
.to.be.revertedWithPanic(code) | It failed with a panic, such as 0x11 for overflow |
.to.revert(ethers) | It reverted for any reason (replaces the deprecated .reverted) |
.to.changeEtherBalances(ethers, [a, b], [x, y]) | Ether balances changed by these amounts |
.to.changeTokenBalances(ethers, token, [a, b], [x, y]) | Token balances changed by these amounts |
it("rejects withdrawals larger than the balance", async function () {
const { bank, alice } = await networkHelpers.loadFixture(deployBank);
await expect(bank.connect(alice).withdraw(1n))
.to.be.revertedWithCustomError(bank, "InsufficientBalance")
.withArgs(0n, 1n);
});
it("pays out and emits Withdrawn", async function () {
const { bank, alice } = await networkHelpers.loadFixture(deployBank);
const one = ethers.parseEther("1");
await bank.connect(alice).deposit({ value: one });
const tx = bank.connect(alice).withdraw(one);
await expect(tx).to.emit(bank, "Withdrawn").withArgs(alice.address, one);
await expect(tx).to.changeEtherBalances(ethers, [bank, alice], [-one, one]);
});Transaction matchers take the transaction promise and must be awaited; forgetting await makes a test pass without checking anything. changeEtherBalances excludes the gas fee paid by the sender by default, so the expected change is the transferred amount.
A test that checks too little
Testing access control
Every privileged function needs a test that calls it from an unauthorised account.
it("only the owner can pause", async function () {
const { bank, owner, alice } = await networkHelpers.loadFixture(deployBank);
await expect(bank.connect(alice).pause())
.to.be.revertedWithCustomError(bank, "OwnableUnauthorizedAccount")
.withArgs(alice.address);
await expect(bank.connect(owner).pause()).to.emit(bank, "Paused");
});Testing who may call
The same test in Solidity
Hardhat 3 also runs Solidity tests, which suit testing contract-to-contract behaviour and fuzzing. A test contract deploys the contract under test in setUp(), and each test-prefixed function is one test case.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Bank} from "./Bank.sol";
contract BankTest {
Bank bank;
function setUp() public {
bank = new Bank();
}
function test_DepositRecordsBalance() public {
bank.deposit{value: 1 ether}();
require(bank.balances(address(this)) == 1 ether, "balance not recorded");
}
}With the forge-std library, tests use helpers such as assertEq and cheatcodes such as vm.prank(alice) and vm.expectRevert().
A test that always passes
A test reads expect(bank.connect(alice).withdraw(5n)).to.revert(ethers); and passes even after the developer removes the balance check from withdraw. Why?
The assertion is not awaited. .revert(ethers) returns a promise; without await, the test finishes before the promise settles, so a failure is never reported. The line must be await expect(...).to.revert(ethers);, and preferably a specific revertedWithCustomError so that a revert for the wrong reason also fails the test.
Proving a transfer
How can one test confirm that a token transfer of 100 units from Alice to Bob moves exactly 100 units, emits the right event and leaves the total supply unchanged?
Send the transaction once and assert on it three ways: await expect(tx).to.changeTokenBalances(ethers, token, [alice, bob], [-100n, 100n]), await expect(tx).to.emit(token, "Transfer").withArgs(alice.address, bob.address, 100n), and then expect(await token.totalSupply()).to.equal(initialSupply).
Which matcher checks that a transaction reverts with the custom error NotOwner?
Show answer
await expect(tx).to.be.revertedWithCustomError(contract, "NotOwner"), optionally followed by .withArgs(...) to check the error's arguments.
Exam Tips
Remember for the exam
- Use connect(signer) to send transactions from different accounts.
- Always await transaction matchers; an unawaited assertion checks nothing.
- Assert specific custom errors with revertedWithCustomError(...).withArgs(...).
- changeEtherBalances and changeTokenBalances verify the full effect of a transfer.
- Solidity tests use setUp() and test-prefixed functions.