乐闻世界logo
搜索文章和话题

How to write smart contract tests in Hardhat?

2月21日 15:59

Hardhat provides a powerful testing framework based on Mocha and Chai. Here are the core points for writing tests:

Test File Structure:

javascript
const { expect } = require("chai"); const { ethers } = require("hardhat"); describe("MyContract", function () { beforeEach(async function () { const MyContract = await ethers.getContractFactory("MyContract"); this.contract = await MyContract.deploy(); await this.contract.deployed(); }); it("should return the correct value", async function () { expect(await this.contract.getValue()).to.equal(42); }); });

Core Features:

  1. Contract Deployment
javascript
const Contract = await ethers.getContractFactory("ContractName"); const contract = await Contract.deploy(); await contract.deployed();
  1. Function Calls and Assertions
javascript
const tx = await contract.someFunction(param1, param2); await tx.wait(); // Wait for transaction confirmation expect(await contract.someViewFunction()).to.equal(expectedValue);
  1. Event Listening
javascript
await expect(contract.someFunction()) .to.emit(contract, "EventName") .withArgs(arg1, arg2);
  1. Transaction Revert Testing
javascript
await expect(contract.failingFunction()) .to.be.revertedWith("Error message");
  1. Snapshot Functionality
javascript
const snapshot = await ethers.provider.send("evm_snapshot", []); // Perform some operations await ethers.provider.send("evm_revert", [snapshot]);
  1. Time Manipulation
javascript
await ethers.provider.send("evm_increaseTime", [3600]); // Increase by 1 hour await ethers.provider.send("evm_mine"); // Mine new block

Best Practices:

  • Use beforeEach and afterEach to manage test state
  • Provide clear descriptions for each test case
  • Test both normal and exception paths
  • Use meaningful test data
  • Maintain test independence and reproducibility
标签:Hardhat