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

Hardhat合约测试中使用数组解构获取Signers时触发TypeError: Cannot read properties of undefined (reading 'equal')的问题求助

问题排查与解决:Hardhat Token测试中TypeError: Cannot read properties of undefined (reading 'equal')

我一眼就发现了导致测试失败的问题——你的第二个测试用例里的expect语句存在语法错误,让我给你详细拆解一下:

错误原因分析

你在第二个测试里的断言语句错误地将.to.equal()嵌套在了await的括号范围内:

// 错误写法:把.to.equal()放在了await的括号里
expect(await hardhatToken.balanceOf(addr1.address).to.equal(10));

hardhatToken.balanceOf()返回的是一个Promise对象,你需要先通过await获取它的实际数值,再用expect去断言这个数值。上面的写法相当于试图在Promise对象上调用.to.equal(),但Promise并没有这个方法,所以会抛出TypeError: Cannot read properties of undefined (reading 'equal')(因为Promise.to是undefined,访问它的equal属性就会报错)。

而你第一个测试用例的写法是完全正确的:

// 正确写法:先await拿到结果,再调用.to.equal()
expect(await hardhatToken.totalSupply()).to.equal(ownerBalance);

修正后的完整测试代码

只需要调整第二个测试里的两个expect语句的括号位置,同时补上遗漏的分号即可:

const { expect } = require('chai'); 
// const { ethers } = require('hardhat'); 
describe('Token contract', function () { 
  //1st TEST 
  it('Deployment should assign the total supply of the tokens to the owner', async function () { 
    const [owner] = await ethers.getSigners(); 
    const Token = await ethers.getContractFactory('Token'); 
    const hardhatToken = await Token.deploy(); 
    const ownerBalance = await hardhatToken.balanceOf(owner.address); 
    expect(await hardhatToken.totalSupply()).to.equal(ownerBalance); 
  }); 
  //2nd TEST 
  it('Should Transfer Tokens between accounts', async function () { 
    const [owner,addr1,addr2] = await ethers.getSigners(); 
    const Token = await ethers.getContractFactory('Token'); 
    const hardhatToken = await Token.deploy(); 
    //Transfer 10 tokens from Owner to addr1 
    await hardhatToken.transfer(addr1.address,10); 
    // 修正:把.to.equal()移到await括号外面
    expect(await hardhatToken.balanceOf(addr1.address)).to.equal(10); 
    //Transfer 5 tokens from addr1 to addr2 
    await hardhatToken.connect(addr1).transfer(addr2.address,5); 
    // 修正:调整括号位置 + 补充分号
    expect(await hardhatToken.balanceOf(addr2.address)).to.equal(5); 
  }); 
});

额外说明

你使用const [owner,addr1,addr2] = await ethers.getSigners();获取多个签名者的写法是完全符合Hardhat规范的,这个部分没有问题,报错的根源就是断言语句的语法错误。

现在重新运行测试,应该就能正常通过啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 19:54:07