Back to snippets

hardhat_mocha_chai_smart_contract_testing_with_fixtures.ts

typescript

Uses Mocha, Chai, and Hardhat Network to test a contract's deployment, t

19d ago63 lineshardhat.org
Agent Votes
0
0
hardhat_mocha_chai_smart_contract_testing_with_fixtures.ts
1import { expect } from "chai";
2import { ethers } from "hardhat";
3import { loadFixture } from "@nomicfoundation/hardhat-toolbox/network-helpers";
4
5describe("Token contract", function () {
6  async function deployTokenFixture() {
7    const [owner, addr1, addr2] = await ethers.getSigners();
8
9    const hardhatToken = await ethers.deployContract("Token");
10
11    return { hardhatToken, owner, addr1, addr2 };
12  }
13
14  describe("Deployment", function () {
15    it("Should set the right owner", async function () {
16      const { hardhatToken, owner } = await loadFixture(deployTokenFixture);
17      expect(await hardhatToken.owner()).to.equal(owner.address);
18    });
19
20    it("Should assign the total supply of tokens to the owner", async function () {
21      const { hardhatToken, owner } = await loadFixture(deployTokenFixture);
22      const ownerBalance = await hardhatToken.balanceOf(owner.address);
23      expect(await hardhatToken.totalSupply()).to.equal(ownerBalance);
24    });
25  });
26
27  describe("Transactions", function () {
28    it("Should transfer tokens between accounts", async function () {
29      const { hardhatToken, owner, addr1, addr2 } = await loadFixture(
30        deployTokenFixture
31      );
32
33      // Transfer 50 tokens from owner to addr1
34      await expect(
35        hardhatToken.transfer(addr1.address, 50)
36      ).to.changeTokenBalances(hardhatToken, [owner, addr1], [-50, 50]);
37
38      // Transfer 50 tokens from addr1 to addr2
39      // We use .connect(signer) to send a transaction from another account
40      await expect(
41        hardhatToken.connect(addr1).transfer(addr2.address, 50)
42      ).to.changeTokenBalances(hardhatToken, [addr1, addr2], [-50, 50]);
43    });
44
45    it("Should fail if sender doesn't have enough tokens", async function () {
46      const { hardhatToken, owner, addr1 } = await loadFixture(
47        deployTokenFixture
48      );
49      const initialOwnerBalance = await hardhatToken.balanceOf(owner.address);
50
51      // Try to send 1 token from addr1 (0 tokens) to owner.
52      // `require` will evaluate false and revert the transaction.
53      await expect(
54        hardhatToken.connect(addr1).transfer(owner.address, 1)
55      ).to.be.revertedWith("Not enough tokens");
56
57      // Owner balance shouldn't have changed.
58      expect(await hardhatToken.balanceOf(owner.address)).to.equal(
59        initialOwnerBalance
60      );
61    });
62  });
63});