Truffle测试报reading 'equal' undefined及candidatesCount返回异常排查
Truffle 测试报错与控制台返回undefined修复方案
1. TypeError: Cannot read properties of undefined (reading 'equal') 修复
- 根因:
assert模块导入写法错误。Node.js内置assert模块为默认导出,不存在名为assert的命名导出,原代码中const { assert } = require("assert")获取到的assert变量实际为undefined,调用undefined.equal()时必然抛出类型错误。 - 修复:将导入语句替换为默认导入写法:
const assert = require("assert");
2. 控制台查询candidatesCount返回undefined、.toNumber()用法说明
- 首先排查合约侧配置:
- 确认合约中
candidatesCount为public类型的状态变量,只有public状态变量编译器才会自动生成同名candidatesCount()查询方法。如果是私有变量,外部调用该方法会返回undefined。 - 确认合约构造函数中已经对
candidatesCount做了初始化,比如初始值设为2。
参考正确的合约片段:
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Election { uint public candidatesCount; constructor() { candidatesCount = 2; } } - 确认合约中
.toNumber()用法说明:Truffle封装的合约实例调用uint类型返回值为BigNumber类型(适配Solidity uint256超出JS安全整数范围的场景),必须调用.toNumber()才能转为普通JS数字,这个方法本身没有问题。- 控制台正确调用步骤:
- 执行
migrate --reset重新部署合约,确保部署的是最新修改后的合约代码 - 获取部署实例:
let instance = await Election.deployed() - 查询并转换数值:
let count = (await instance.candidatesCount()).toNumber(),此时拿到的count就是正确的数值2,不会返回undefined
- 执行
修复后完整测试代码
const assert = require("assert"); var Election = artifacts.require("./Election.sol"); contract("Election", function (accounts) { it("initializes with two candidates", async function () { const instance = await Election.deployed(); const count = (await instance.candidatesCount()).toNumber(); assert.equal(count, 2); }); });
备注:测试用例改用async/await写法替代Promise链式调用,可读性更高,也能避免链式调用中返回值遗漏导致的异常。
内容的提问来源于stack exchange,提问作者Ayush
相关产品推荐
相关产品推荐

