1

I'm having a method inside my contract which return a variable having value is 100 ether for example. E.g:

uint256 private baseline

constructor() {
    baseline = 100 ether;
}

function getBaseline() external view returns (uint256) {
    return (baseline);
}

I've tried to write a test function:

const Contract = artifacts.require("MyContract");

contract("MyContract", (accounts) => {
  it("test", async () => {
    const instance = await QuickPunk.deployed();
    const baseline = await instance.getBaseline();

    console.log(baseline);
    expect(baseline).to.equal(100);
  });
});

But it doesn't work, and here are the logs:

BN {
  negative: 0,
  words: [ 25821184, 13721111, 22, <1 empty item> ],
  length: 3,
  red: null
}

and having this error: AssertionError: expected <BN: 16345785d8a0000> to equal 100

I wonder is there anyway I can assert baseline value with Truffle & Mocha? Have tried to search around but seems like there is not much document about this on truffle website.

1
  • The problem is that javascript's numbers don't support the precision required by Ethereum so web3 uses a library bn.js. Now chai doen't known anything about bn.js objects. You could use a library like chai-bn.
    – Ismael
    Sep 8 '21 at 1:04
0

I've used web3 API inside of the test file to convert the value into the value that I was expected.

web3 API already embedded globally inside of truffle test file. I just need to utilize web3.utils.toWei to convert 100 ether into Wei, and then convert Wei into BN by using web3.utils.toBN, then perform the assertion.

it("test", async () => {
    const instance = await QuickPunk.deployed();
    const baseline = await instance.getBaseline();

    const expectedBaseline = web3.utils.toBN(web3.utils.toWei("100", "ether));

    expect(baseline).to.deep.equal(expectedBaseline);
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.