Smart Contract Testing (Hardhat) — Web3

Hardhat is a development environment to compile, deploy, test and debug contracts on a local chain. Hardhat 3.19.0 recommends node:test + viem…

Before he screen-prints 100 Coffee Edition Shirt shirts, Raka always does a trial print on a scrap of fabric first, then checks the colour, the position and the spelling. The scrap may be wrong and goes in the bin; a printed shirt can't be edited. A contract is the same: once deployed, its code can't change, so every mistake has to be found on the "scrap", which is Hardhat's local chain. Testing a smart contract means exactly that: running it on a local blockchain that is thrown away after the test, and checking automatically that every function does what it promises.

Hardhat 3 and your test options

Hardhat is a development environment for Ethereum smart contracts: compile, deploy, test and debug, with a local blockchain running inside the process (Hardhat Network). This lesson uses Hardhat 3.19.0 (October 2026). npx hardhat --init offers two TypeScript templates:

Template Test runner Library Assertions
hardhat-toolbox-viem (the one Hardhat's docs recommend) Node.js's built-in node:test viem viem.assertions.*
hardhat-toolbox-mocha-ethers Mocha ethers Chai: expect(...).to.be.revertedWith(...)

Both also run Solidity tests (*.t.sol, forge-std style). This lesson uses the viem template, with the ERC-20 RakaPoints and CoffeeEditionShirt from earlier lessons in contracts/, and the tests in test/.

A first test and a fixture

// test/RakaPoints.ts
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { network } from "hardhat";
import { getAddress, parseUnits } from "viem";

describe("RakaPoints", async function () {
  const { viem, networkHelpers } = await network.create();

  // Fixture: deploy once, then every test starts from the same snapshot
  async function deployPoints() {
    const [raka, dinda, yoga] = await viem.getWalletClients();
    const points = await viem.deployContract("RakaPoints");
    return { points, raka, dinda, yoga };
  }

  it("earn gives 1 PTS per $1", async function () {
    const { points, dinda } = await networkHelpers.loadFixture(deployPoints);
    await points.write.earn([dinda.account.address, 16_000n]);
    assert.equal(await points.read.balanceOf([dinda.account.address]), parseUnits("160", 18));
  });
});

Testing reverts and events

it("only Raka may earn", async function () {
  const { points, dinda } = await networkHelpers.loadFixture(deployPoints);
  await viem.assertions.revertWithCustomErrorWithArgs(
    points.write.earn([dinda.account.address, 100_000n], { account: dinda.account }),
    points, "OwnableUnauthorizedAccount", [getAddress(dinda.account.address)],
  );
});

it("earn emits Earned(Dinda, 160 PTS)", async function () {
  const { points, dinda } = await networkHelpers.loadFixture(deployPoints);
  await viem.assertions.emitWithArgs(
    points.write.earn([dinda.account.address, 16_000n]),
    points, "Earned", [getAddress(dinda.account.address), parseUnits("160", 18)],
  );
});

Running the tests

$ npx hardhat test
Running Solidity tests

  contracts/RakaPoints.t.sol:RakaPointsTest
    ✔ test_EarnDinda160()
    ✔ testFuzz_PointsFor(uint256) (runs: 256)

Running node:test tests

  CoffeeEditionShirt
    ✔ mint #1 for Dinda emits Transfer from the zero address
    ...
  RakaPoints
    ✔ earn gives 1 PTS per $1
    ✔ earn emits Earned(Dinda, 160 PTS)
    ✔ only Raka may earn
    ✔ redeem 100 of 160 leaves 60
    ✔ redeem over the balance is refused with ERC20InsufficientBalance
  ...
11 passing (2 solidity, 9 nodejs)

If Raka forgets the _burn in redeem, two tests turn red at once, and the message points at the line:

  1) RakaPoints
       redeem 100 of 160 leaves 60:
   AssertionError: Expected values to be strictly equal
   - 60000000000000000000n
   + 160000000000000000000n
       at TestContext.<anonymous> (test/RakaPoints.ts:46:12)

Why every test needs a fixture

Raka tries removing loadFixture and sharing one contract across all tests. The test "redeem 100 of 160 leaves 60" suddenly fails: + 380000000000000000000n. The two tests before it had already given Dinda 160 + 160 PTS, then this test adds 160 and redeems 100, leaving 380. Tests that hand state to each other pass or fail depending on their order. A fixture keeps every test on its own.

100% coverage isn't safety

npx hardhat test --coverage counts the contract lines the tests run:

║ contracts/RakaPoints.sol         │ 100.00 │ 100.00      │ -               ║
║ contracts/CoffeeEditionShirt.sol │ 100.00 │ 100.00      │ -               ║

Remove the redeem tests and RakaPoints's lines 20-21 (_burn and emit Redeemed) show up under Uncovered Lines and the figure drops to 66.67%. But run doesn't mean checked. With the bug emit Redeemed(msg.sender, balanceOf(msg.sender)), all nine tests stay green: 9 passing. No test reads the Redeemed event. As soon as Raka adds an emitWithArgs test for Redeemed(Dinda, 100 PTS), the bug shows:

   AssertionError: The event arguments do not match the expected ones.
   -   100000000000000000000n,
   +   60000000000000000000n,

Solidity tests and fuzzing

// contracts/RakaPoints.t.sol
import {Test} from "forge-std/Test.sol";
import {RakaPoints} from "./RakaPoints.sol";

contract RakaPointsTest is Test {
    RakaPoints points;

    function setUp() public {
        points = new RakaPoints();
    }

    function testFuzz_PointsFor(uint256 cents) public view {
        cents = bound(cents, 0, 1e30); // a purchase above 10^30 cents makes no sense
        assertEq(points.pointsFor(cents), (cents / 100) * 1e18);
    }
}

A function whose name starts with testFuzz_ and takes parameters runs 256 times with random values (fuzzing). Before the bound line existed, the fuzzer found a number that makes pointsFor revert: panic code 0x11 (Arithmetic operation overflowed ...) with cents around 3.133 × 10^76. The revert is safe (Solidity 0.8 checks overflow), and a purchase that big is impossible, so Raka bounds the input. A popular alternative for this style is Foundry (v1.8.5, October 2026): forge test runs the same .t.sol tests without Node.js.

📌 Time travel and gas reports

RakaPoints and COFFEE don't depend on time yet, but if a promo someday ends in 7 days, the test doesn't have to wait 7 days:

await networkHelpers.time.increase(7 * 24 * 60 * 60); // the next block is 604,800 seconds later

npx hardhat test --gas-stats prints gas per function from every call in the tests: earn 73,204, redeem 35,679, mint 62,359 to 96,559, deploying RakaPoints 1,229,240.

⚠️ Green tests that catch nothing

TL;DR: Hardhat is a development environment to compile, deploy, test and debug contracts on a local chain. Hardhat 3.19.0 recommends node:test + viem (hardhat-toolbox-viem); Mocha + ethers with Chai matchers is also there, and both run Solidity tests. Use loadFixture so every test starts from the same snapshot. Test reverts with viem.assertions.revertWithCustomErrorWithArgs (or await expect(tx).to.be.revertedWith("...") with ethers) and events with emitWithArgs. npx hardhat test runs everything; --coverage shows lines no test ran, --gas-stats shows gas per function, time.increase moves the chain clock forward, and fuzzing in .t.sol (or forge test in Foundry 1.8.5) tries hundreds of random inputs. 100% coverage isn't safety: what catches bugs is an assert that checks the result.

⚡ Hardhat: the place to try a contract

Meaning: Hardhat is a development environment to compile, deploy, test and debug Ethereum smart contracts, with a local blockchain that's thrown away after the tests.

⚡ Test what must fail

Write:

await viem.assertions.revertWithCustomErrorWithArgs(
  points.write.earn([dinda.account.address, 100_000n], { account: dinda.account }),
  points, "OwnableUnauthorizedAccount", [getAddress(dinda.account.address)],
);

Meaning: { account: dinda.account } sends the transaction from Dinda. The test passes only if the revert is that custom error and its arguments match.

⚡ Every test needs a fixture

Guess first: loadFixture is removed and every test shares one contract. What does the test "redeem 100 of 160 leaves 60" get now?

It gets 380. The two tests before it already gave Dinda 160 + 160 PTS, then this test adds 160 and redeems 100.

Meaning: loadFixture rolls the chain back to the same snapshot, so every test stands on its own.

⚡ 100% coverage isn't safety

Meaning: With a bug in the Redeemed event, all nine tests stay green because none of them reads the event. What catches bugs is an assert that checks the result, such as emitWithArgs.

What you will learn