使用JavaScript测试Solidity代码遇TypeError:无法读取undefined的address属性
解决Hardhat测试中"Cannot read properties of undefined (reading 'address')"错误
问题原因
错误的核心是变量作用域冲突:你在before块内重新声明了const swapExamples,这会覆盖外层已经声明的let swapExamples变量,导致测试用例中的swapExamples始终处于undefined状态,访问其address属性时自然抛出错误。
修复方案
去掉before块中声明合约实例时的const关键字,直接赋值给外层已定义的swapExamples变量:
修改后的完整测试代码
const { expect } = require("chai"); const { ethers } = require("hardhat"); const DAI = "0x6B175474E89094C44Da98b954EedeAC495271d0F"; const WETH9 = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"; describe("SwapExamples", function () { let swapExamples; let accounts; let weth; let dai; before(async () => { accounts = await ethers.getSigners(); weth = await ethers.getContractAt("IWETH", WETH9); dai = await ethers.getContractAt("IERC20", DAI); const SwapExamples = await ethers.getContractFactory("SwapExamples"); // 移除const,直接赋值给外层变量 swapExamples = await SwapExamples.deploy(); await swapExamples.deployed(); }) it("swapExactInputSingle", async function () { const amountIn = 10n ** 18n; await weth.connect(accounts[0]).deposit({ value: amountIn }); await weth.connect(accounts[0]).approve(swapExamples.address, amountIn); await swapExamples.swapExactInputSingle(amountIn); console.log("DAI balance", await dai.balanceOf(accounts[0].address)); }); it("swapExactOutputSingle", async function () { const wethAmountInMax = 10n ** 18n; const daiAmountOut = 100n * 10n ** 18n; await weth.connect(accounts[0]).deposit({ value: wethAmountInMax }); await weth.connect(accounts[0]).approve(swapExamples.address, wethAmountInMax); await swapExamples.swapExactOutputSingle(daiAmountOut, wethAmountInMax); console.log("DAI balance", await dai.balanceOf(accounts[0].address)); }); });
额外注意事项
确保你的Hardhat环境配置了主网fork模式,因为测试中使用了主网的DAI和WETH合约地址,否则会出现合约不存在的异常。
内容的提问来源于stack exchange,提问作者Mav
相关产品推荐
相关产品推荐

