Menulis Test dengan Mocha/Chai + Hardhat Chai Matchers
Penjelasan
Berbeda dari Foundry yang test-nya ditulis dalam Solidity, Hardhat memakai framework testing JavaScript standar: Mocha sebagai test runner (`describe`, `it`) dan Chai sebagai assertion library (`expect`). Plugin `@nomicfoundation/hardhat-chai-matchers` menambahkan matcher khusus blockchain seperti `.to.be.revertedWith()`, `.to.emit()`, dan `.to.changeEtherBalance()`. Setiap test biasanya diawali dengan deploy contract baru di dalam `beforeEach` atau langsung di dalam `it`, menggunakan `ethers.getContractFactory()` untuk mendapatkan factory contract lalu `.deploy()` untuk men-deploy instance baru ke Hardhat Network.
Contoh Konsep
const { expect } = require("chai");
const { ethers } = require("hardhat");
describe("Counter", function () {
let counter;
beforeEach(async function () {
const Counter = await ethers.getContractFactory("Counter");
counter = await Counter.deploy();
});
it("harus bertambah 1 setelah increment()", async function () {
await counter.increment();
expect(await counter.number()).to.equal(1);
});
it("harus revert jika bukan owner memanggil reset()", async function () {
const [, other] = await ethers.getSigners();
await expect(
counter.connect(other).reset()
).to.be.revertedWith("Not owner");
});
});
Praktikum
Tulis test yang mendeploy contract Counter, memanggil increment() sebanyak 3 kali, lalu memastikan number() bernilai 3 memakai expect dari Chai.
Ketik/edit bebas di sini untuk latihan — kode ini tidak dijalankan.
Tips
Gunakan `describe` bertingkat untuk mengelompokkan test berdasarkan fungsi atau skenario — memudahkan membaca laporan hasil test yang panjang.