Hardhat测试中before、beforeEach执行异常:silentAuction未定义问题求助
问题原因与修复方案
核心问题:变量作用域限制
你遇到的ReferenceError: silentAuction is not defined完全是变量作用域导致的:
before块里用const声明的SilentAuction,仅在before函数内部有效,beforeEach块无法访问beforeEach块里用const声明的silentAuction,仅在beforeEach函数内部有效,所有it测试块都无法访问
修复步骤
- 在顶层
describe块的作用域内声明两个let变量,让所有嵌套的before/beforeEach/it都能访问到 - 去掉
before和beforeEach里的const,直接给顶层变量赋值
修改后的完整代码
const { BigNumber } = require("ethers"); const { ethers } = require("hardhat"); describe("SilentAuction", function () { // 声明在顶层describe作用域,让所有内部块都能访问 let SilentAuction; let silentAuction; before(async function () { // 直接给顶层变量赋值,不用const SilentAuction = await ethers.getContractFactory("SilentAuction"); }) beforeEach(async function () { // 同样给顶层变量赋值 silentAuction = await SilentAuction.deploy(); await silentAuction.deployed(); }) describe("- setItem function tests", function (){ it("Owner should be able to set an item for bid", async function () { await silentAuction.setItem("SAMPLE", 100, 300); expect((await silentAuction.items(0)).name).to.be.equal("SAMPLE"); expect((await silentAuction.items(0)).highestPrice.toString()).to.be.equal('100'); expect((await silentAuction.items(0)).successLimit.toString()).to.be.equal('300'); }); it("Not owner cannot call function", async function () { const [owner, addr1] = await ethers.getSigners(); await expect(silentAuction.connect(addr1).setItem("SAMPLE", 100, 300)).to.be.reverted; }); }); describe("- bid function tests", function (){ it("Everyone should place a bid", async function () { const [owner, addr1] = await ethers.getSigners(); await silentAuction.connect(owner).setItem("SAMPLE", 100, 300); await silentAuction.connect(addr1).bid(200); expect((await silentAuction.items(0)).highestPrice.toString()).to.be.equal('200'); }) it("Should not replace smaller bids than the recent highest", async function () { const [owner, addr1] = await ethers.getSigners(); await silentAuction.connect(owner).setItem("SAMPLE", 100, 300); await silentAuction.connect(addr1).bid(50); expect((await silentAuction.items(0)).highestPrice.toString()).to.be.equal('100'); }) }) });
额外说明
before块只在所有测试执行前运行一次,适合初始化合约工厂(因为工厂不需要每次测试都重新创建)beforeEach块会在每个it测试前运行一次,确保每次测试都使用全新的合约实例,避免测试间的状态污染
内容的提问来源于stack exchange,提问作者0xGlitch
相关产品推荐
相关产品推荐

