Testing
Writing Unit Tests
npm install --save-dev mocha chaiExample Test Suite: Token Contract
const { expect } = require("chai");
describe("Token Contract", function () {
let Token, token, owner, addr1, addr2;
// Before each test, deploy a new token contract instance
beforeEach(async function () {
[owner, addr1, addr2] = await ethers.getSigners(); // Retrieve test accounts
Token = await ethers.getContractFactory("MyToken");
token = await Token.deploy(); // Deploy the contract
});
describe("Deployment", function () {
it("Should set the correct owner", async function () {
expect(await token.owner()).to.equal(owner.address);
});
it("Should assign the total supply of tokens to the owner", async function () {
const ownerBalance = await token.balanceOf(owner.address);
expect(await token.totalSupply()).to.equal(ownerBalance);
});
});
describe("Transactions", function () {
it("Should transfer tokens between accounts", async function () {
// Transfer 50 tokens from owner to addr1
await token.transfer(addr1.address, 50);
const addr1Balance = await token.balanceOf(addr1.address);
expect(addr1Balance).to.equal(50);
});
it("Should fail if sender doesn’t have enough tokens", async function () {
const initialOwnerBalance = await token.balanceOf(owner.address);
// Attempt to transfer 1 token from addr1 (has 0 tokens) to addr2
await expect(
token.connect(addr1).transfer(addr2.address, 1)
).to.be.revertedWith("Insufficient balance");
// Ensure owner's balance remains unchanged
expect(await token.balanceOf(owner.address)).to.equal(initialOwnerBalance);
});
it("Should update balances after transfers", async function () {
const initialOwnerBalance = await token.balanceOf(owner.address);
// Transfer 100 tokens from owner to addr1
await token.transfer(addr1.address, 100);
// Transfer 50 tokens from addr1 to addr2
await token.connect(addr1).transfer(addr2.address, 50);
const finalOwnerBalance = await token.balanceOf(owner.address);
expect(finalOwnerBalance).to.equal(initialOwnerBalance - 100);
const addr1Balance = await token.balanceOf(addr1.address);
expect(addr1Balance).to.equal(50);
const addr2Balance = await token.balanceOf(addr2.address);
expect(addr2Balance).to.equal(50);
});
});
});Breakdown of the Test Cases:
Running the Tests
Improvements in this Version:
Last updated