框架
,主要用于简化和加速以太坊区块链上的智能合约开、测试和部署,提供了许多工具帮助开发人员更轻松地构建和维护智能合约项目,以下是他的一些主要功能:
mkdir 文件名
命令来创建一个新的文件夹cd 文件名
命令转到该目录npm install --save-dev hardhat
命令安装hardhatnpx hardhat init
命令进行初始化Error HH1: You are not inside a Hardhat project.
,表示你当前不在一个hardhat项目中,我这里创建的目录是my-new-project,因此要在该目录下创建文件以及运行
const {
expect } = require("chai");
const {
ethers } = require("hardhat");
describe("Mailbox", async () => {
it("should get mailbox contract", async () => {
const mailboxContract = await ethers.getContractFactory("Mailbox");
});
it("should get total letters in the box", async () => {
const mailboxContract = await ethers.getContractFactory("Mailbox");
const mailbox = await mailboxContract.deploy();
expect(await mailbox.totalLetters()).to.equal(0);
});
it("should increase by one when got new letter", async () => {
const mailboxContract = await ethers.getContractFactory("Mailbox");
const mailbox = await mailboxContract.deploy();
await mailbox.write("Hello");
expect(await mailbox.totalLetters()).to.equal(1);
})
it("should get mail content", async () => {
const mailboxContract = await ethers.getContractFactory("Mailbox");
const mailbox = await mailboxContract.deploy();
await mailbox.write("Hello");
const letters = await mailbox.read();
expect(letters[0].letter).to.equal("Hello");
})
it("should get mail sender", async () => {
const mailboxContract = await ethers.getContractFactory("Mailbox");
const mailbox = await mailboxContract.deploy();
await mailbox.write("Hello");
const letters = await mailbox.read();
//这里记得测试后将0x替换成终端给出的地址
expect(letters[0].sender).to.equal("0x");
})
});
合约代码
pragma solidity 0.8.24;
contract Mailbox {
//这里没有赋初值的话,初始值为0
uint public totalLetters;
struct Letter {
string letter;
address sender;
}
Letter[] private letters;
function write(string memory letter) public {
totalLetters++;
letters.push(Letter(letter, msg.sender));
}
function read() public view returns (Letter[] memory) {
return letters;
}
}
终端界面输入npx hardhat test
命令,当显示全绿表示测试通过
const { expect } = require("chai");
const expect = require("chai")
命令,该命令导入了chai的整个模块,使用解构赋值语法的好处就是只导入模块中真正需要的部分,减少不必要的代码依赖。当模块中有多个导出时可以防止导入的变量名和其它变量名发生冲突。describe("Mailbox", async () => {})
it("should get mail sender", async () => {})
const mailboxContract = await ethers.getContractFactory("Mailbox");
const mailbox = await mailboxContract.deploy();
await mailbox.write("Hello");
const letters = await mailbox.read();
expect(letters[0].sender).to.equal('0x');
更多【智能合约-使用测试驱动开发模式编写智能合约】相关视频教程:www.yxfzedu.com