Comparing ethers BigNumber does not work

bignumberchaiethers.jstesting

I'm testing the value of a BigNumber returned from a function call to a contract and its not working as expected.

I have this

const { BigNumber } = require('ethers');
...
const totalSupply = await token.totalSupply();
expect(totalSupply).to.equal(BigNumber.from("4"));

This test fails with this error:

AssertionError: expected BigNumber { value: "4" } to equal BigNumber { value: "4" }
      + expected - actual

But looking at the error message it appears the expected and actual are the same. Why does this test fail?

Best Answer

Try like this :

expect(totalSupply.eq(BigNumber.from("4")).to.equal(true);

This is because to.equal internally uses the strict equality check === which on Objects only returns true if the two references are pointing to the same object.

Alternatively, you could also use .deep.equal which checks for deep equality between Objects but not as strictly as ensuring that the references point to the same instance :

expect(totalSupply).to.deep.equal(ethers.BigNumber.from("4"))

I hope this answers your question.

Related Topic