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

Chai断言错误:值相同的BigNumber判定不相等问题排查

解决Hardhat测试中BigNumber断言相等失败的问题

问题根源

你遇到的报错是因为BigNumber是对象类型,即便两个对象的value属性数值完全一致,它们的内存引用地址不同,直接用原生Chai的equal断言会比较对象引用而非实际数值,因此触发断言失败。

解决方法

1. 使用Hardhat内置的Chai BigNumber匹配器(推荐)

Hardhat默认集成了@nomicfoundation/hardhat-chai-matchers插件,它扩展了Chai的断言能力,支持直接比较BigNumber对象。

首先确保hardhat.config.js中已启用该插件:

require("@nomicfoundation/hardhat-chai-matchers");

之后在测试代码中直接使用to.equal断言:

expect(ownerBalance).to.equal(totalSupply);

2. 手动提取数值比较

如果不想依赖插件,可以将BigNumber转换为字符串或安全范围内的数字进行比较:

// 转字符串(无数值范围限制)
expect(ownerBalance.toString()).to.equal(totalSupply.toString());

// 转数字(仅适用于数值小于2^53-1的场景)
expect(ownerBalance.toNumber()).to.equal(totalSupply.toNumber());

3. 调用BigNumber自身的比较方法

利用BigNumber内置的eq方法判断数值是否相等,再断言结果为true:

expect(ownerBalance.eq(totalSupply)).to.be.true;

示例测试代码

const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("Token", function () {
  it("Should assign total supply to owner", async function () {
    const [owner] = await ethers.getSigners();
    const Token = await ethers.getContractFactory("Token");
    const token = await Token.deploy();
    
    const totalSupply = await token.totalSupply();
    const ownerBalance = await token.balanceOf(owner.address);
    
    // 推荐用法:使用hardhat-chai-matchers的equal断言
    expect(ownerBalance).to.equal(totalSupply);
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:12:20