Hardhat测试报错:TypeError: (0 , ethers_1.getAddress) is not a function 求助
看起来你遇到了Hardhat和Ethers版本不兼容的典型问题,我来帮你拆解一下原因和解决办法:
问题根源
你当前使用的@nomicfoundation/hardhat-toolbox@3.0.0是官方为Ethers v6量身打造的工具链,但你手动安装了Ethers v5.7.2,还额外引入了@nomiclabs/hardhat-ethers(实际是hardhat-deploy-ethers的别名)。这种混合配置造成了依赖冲突:
Hardhat工具链内部会调用Ethers v6的API(比如ethers.getAddress),但你的项目实际加载的是Ethers v5——而Ethers v5中这个函数是放在ethers.utils.getAddress路径下的,自然会报“不是函数”的错误。
两种解决方案
方案一:统一使用Ethers v6(推荐,官方最新支持版本)
这个方案能彻底解决版本冲突问题,也能享受Ethers v6的新特性:
调整package.json依赖
移除多余的Ethers和第三方Hardhat Ethers插件,因为hardhat-toolbox@3.x已经内置了适配好的Ethers v6和官方插件:{ "name": "how-to-unit-test-a-smart-contract", "version": "1.0.0", "main": "index.js", "scripts": { "test": "npx hardhat test --network sepolia" }, "keywords": [], "author": "", "license": "ISC", "description": "", "devDependencies": { "@nomicfoundation/hardhat-toolbox": "^3.0.0", "hardhat": "^2.22.16" }, "dependencies": { "chai": "^4.3.7", "dotenv": "^16.4.5", "web3modal": "^1.9.12" } }修改测试代码适配Ethers v6 API
Ethers v6的API有一些变化,比如Provider、Wallet的创建方式,调整你的faucetTests.js:const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers'); const { expect } = require('chai'); const { ethers } = require('hardhat'); require('dotenv').config(); describe('Faucet', function () { async function deployContractAndSetVariables() { const url = process.env.RPC_URL; const privateKey = process.env.PRIVATE_KEY; // Ethers v6 中JsonRpcProvider的创建方式 const provider = new ethers.JsonRpcProvider(url); // Ethers v6 中Wallet的创建方式 const wallet = new ethers.Wallet(privateKey, provider); console.log('Signer 1 address: ', wallet.address); // 用指定钱包部署合约 const Faucet = await ethers.getContractFactory('Faucet'); const faucet = await Faucet.connect(wallet).deploy(); await faucet.waitForDeployment(); // 替代v5中的deployed()方法 return { wallet, faucet }; } it('should deploy and set the owner correctly', async function () { const { wallet, faucet } = await loadFixture(deployContractAndSetVariables); expect(await faucet.owner()).to.equal(wallet.address); }); });重新安装依赖并测试
先删除旧依赖文件,再执行:rm -rf node_modules package-lock.json npm install # 运行Sepolia网络下的测试 npx hardhat test --network sepolia
方案二:降级Hardhat Toolbox适配Ethers v5
如果你坚持要使用Ethers v5,可以把工具链降级到适配v5的版本:
调整package.json依赖
将@nomicfoundation/hardhat-toolbox降级到v2.x(专为Ethers v5设计):"devDependencies": { "@nomicfoundation/hardhat-toolbox": "^2.0.0", "ethers": "^5.7.2", "hardhat": "^2.22.16" }重新安装依赖
执行下面的命令后,你原来的测试代码就能正常运行:rm -rf node_modules package-lock.json npm install npx hardhat test --network sepolia
备注:内容来源于stack exchange,提问作者Goalyan

