const { expect } = require("chai");
describe("SimpleToken", function () {
let token;
let owner, alice, bob;
beforeEach(async function () {
[owner, alice, bob] = await ethers.getSigners();
const Token = await ethers.getContractFactory("SimpleToken");
token = await Token.deploy(1000); // 初始供应 1000 tokens
await token.deployed();
});
describe("初始化", function () {
it("应该有正确的总供应", async function () {
const expected = ethers.utils.parseEther("1000");
expect(await token.totalSupply()).to.equal(expected);
});
it("拥有者应该获得所有初始代币", async function () {
const balance = await token.balanceOf(owner.address);
expect(balance).to.equal(await token.totalSupply());
});
});
describe("转账", function () {
it("应该能够转账代币", async function () {
const amount = ethers.utils.parseEther("100");
await token.transfer(alice.address, amount);
expect(await token.balanceOf(alice.address)).to.equal(amount);
expect(await token.balanceOf(owner.address)).to.equal(
ethers.utils.parseEther("900")
);
});
it("应该发出 Transfer 事件", async function () {
const amount = ethers.utils.parseEther("50");
await expect(token.transfer(bob.address, amount))
.to.emit(token, "Transfer")
.withArgs(owner.address, bob.address, amount);
});
it("不应该允许转账超过余额", async function () {
const tooMuch = ethers.utils.parseEther("2000");
await expect(
token.transfer(alice.address, tooMuch)
).to.be.revertedWith("Insufficient balance");
});
});
describe("授权和代理转账", function () {
it("应该能够授权", async function () {
const amount = ethers.utils.parseEther("100");
await token.approve(alice.address, amount);
expect(await token.allowance(owner.address, alice.address)).to.equal(amount);
});
it("应该能够进行代理转账", async function () {
const amount = ethers.utils.parseEther("100");
// owner 授权 alice 花费 100 tokens
await token.approve(alice.address, amount);
// alice 代表 owner 转账给 bob
await token.connect(alice).transferFrom(owner.address, bob.address, amount);
expect(await token.balanceOf(bob.address)).to.equal(amount);
expect(await token.allowance(owner.address, alice.address)).to.equal(0);
});
it("不应该允许转账超过授权额度", async function () {
const approved = ethers.utils.parseEther("50");
const attempted = ethers.utils.parseEther("100");
await token.approve(alice.address, approved);
await expect(
token.connect(alice).transferFrom(owner.address, bob.address, attempted)
).to.be.revertedWith("Insufficient allowance");
});
});
});