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

Hardhat调用ethers.utils.parseUnits报错:Cannot read properties of undefined

问题原因与解决办法

核心原因

你用的是Hardhat导出的ethers对象,这个是Hardhat Ethers插件的实例,和直接从ethers包导入的对象结构不一样。而且在describe的顶级作用域里,Hardhat的ethers还没完成初始化,导致ethers.utils是undefined,所以调用parseUnits会报错。

两种解决办法

办法1:直接从ethers包导入工具函数

不用依赖Hardhat导出的ethers,单独从ethers包导入utils或者具体的函数:

const { deployments, ethers, getNamedAccounts } = require("hardhat")
const { assert, expect } = require("chai")
// 直接导入ethers的utils模块
const { utils } = require("ethers")

describe("FundMe", async function () {
    let fundMe
    let deployer
    const sendValue = utils.parseUnits("1", "ether")
    // 嫌麻烦也可以直接导入单个函数
    // const { parseUnits } = require("ethers/lib/utils")
    // const sendValue = parseUnits("1", "ether")
})

办法2:把调用放到测试钩子里面

如果非要用Hardhat的ethers,就把parseUnits的调用移到beforeEach这类测试钩子里面,此时Hardhat已经完成初始化,ethers.utils就能正常用了:

const { deployments, ethers, getNamedAccounts } = require("hardhat")
const { assert, expect } = require("chai")

describe("FundMe", async function () {
    let fundMe
    let deployer
    let sendValue

    beforeEach(async function () {
        // 这里Hardhat的ethers已经初始化好
        sendValue = ethers.utils.parseUnits("1", "ether")
        deployer = (await getNamedAccounts()).deployer
        await deployments.fixture(["all"])
        fundMe = await ethers.getContract("FundMe", deployer)
    })

    // 后续写测试用例即可
})

额外说明

Hardhat v2+默认集成ethers v5,和官方文档API一致,但要区分开Hardhat导出的ethers对象和直接导入的ethers包,两者不是同一个东西。parseEther("1")是parseUnits("1", "ether")的简写,解决方式完全一样。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:38:30