You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hardhat测试中accounts变量undefined问题排查与解决

Hardhat测试中TypeError: Cannot read properties of undefined (reading '0')问题解决

在使用Hardhat进行以太坊测试时,出现TypeError: Cannot read properties of undefined (reading '0')错误,accounts变量始终显示为undefined。

原错误测试代码

const { ethers } = require("hardhat");

describe("deploy", () => {
  let accounts;
  beforeEach(async () => {
    accounts = await ethers.getSigners();
  })
  console.log(accounts[0].address)
})

项目devDependencies配置

"devDependencies": {
    "@nomicfoundation/hardhat-chai-matchers": "^2.0.0",
    "@nomicfoundation/hardhat-ethers": "^3.0.0",
    "@nomicfoundation/hardhat-network-helpers": "^1.0.0",
    "@nomicfoundation/hardhat-toolbox": "^3.0.0",
    "@nomicfoundation/hardhat-verify": "^1.0.0",
    "@typechain/ethers-v6": "^0.4.0",
    "@typechain/hardhat": "^8.0.0",
    "chai": "^4.2.0",
    "ethers": "^6.4.0",
    "hardhat": "^2.14.0",
    "hardhat-gas-reporter": "^1.0.8",
    "solidity-coverage": "^0.8.0",
    "typechain": "^8.1.0"
  },

问题根源与解决方法

问题出在代码执行顺序上:console.log直接写在describe块的顶级作用域,此时beforeEach钩子还未执行,accounts变量未被赋值,自然是undefined。将accounts = await ethers.getSigners()移至it测试块内,确保代码在测试执行时才触发赋值操作,即可解决问题。

修改后的正确代码

describe("deploy", () => {
    let accounts;
    it("test accounts", async () => {
        accounts = await ethers.getSigners();
        console.log(accounts[0].address);
    })
})

内容的提问来源于stack exchange,提问作者Clint Oka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 17:30:25