Replies: 1 comment
-
|
BigNumber comparison in Hardhat tests has gotten much easier now that ethers v6 uses native With ethers v6 / Hardhat + ethers v6: // Native bigint — just use ===, >, < directly
const balance = await token.balanceOf(user.address);
expect(balance).to.equal(parseUnits("100", 18)); // Direct comparison
expect(balance > 0n).to.be.true;
expect(balance).to.be.greaterThan(0n);
// Chai matchers work with bigint:
const { expect } = require("chai");
import "@nomicfoundation/hardhat-chai-matchers"; // Extends chai for ethers
expect(await token.totalSupply()).to.equal(1000n * 10n ** 18n);With ethers v5 (BigNumber era): // The painful old way
expect(balance.eq(expectedBalance)).to.be.true;
expect(balance.gte(minAmount)).to.be.true;
// Better with chai-bignumber or hardhat-chai-matchers:
expect(balance).to.equal(expectedBalance); // Still works via .toString() comparison
// Or cast to string for readability:
expect(balance.toString()).to.equal("1000000000000000000");The cleanest modern pattern (ethers v6 + hardhat-chai-matchers): import { loadFixture } from "@nomicfoundation/hardhat-toolbox/network-helpers";
import { expect } from "chai";
it("should have correct balance", async () => {
const { token, owner } = await loadFixture(deployFixture);
const balance = await token.balanceOf(owner.address);
const expected = parseUnits("1000", 18);
// All of these work cleanly:
expect(balance).to.equal(expected);
expect(balance).to.be.greaterThanOrEqual(expected);
expect(balance).to.changeEtherBalance(owner, -expected);
});If you're still on ethers v5, the migration to v6 is worth it mostly for the BigNumber → bigint change — testing becomes dramatically cleaner. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
So, bigNumber is a common way to represent values from solidity smart contracts. However it's not easy to make comparsions between big number using
expectouassertin hardhat tests.I would like to be able to do something like:
I opened an issue about this, but there is no straight forward way to do it. I thought that maybe using
chai-bignumberbut it does not work.I opened this discussion to find ideas on how to do it. How do you guys handle comparing bigNumber in tests? Is it possible to do something as I described?
Beta Was this translation helpful? Give feedback.
All reactions