Question:

Truffle test javascript

Isabella: 24 May 2022

I have a .sol contract:

contract HelloWorld {
    string name="TEST";
    uint number;

    function HelloWorld() {

    }

    function getName() returns (string) {
        return name;
    }

    function getNumber() returns (uint) {
        return number;
    }

    function setNumber(uint _number) {
        number = _number;
    }
}

And I'm trying to write a test in javascript to call the function setNumber. My test.js looks like this:

var HelloWorld = artifacts.require('./HelloWorld.sol');

contract("HelloWorld:getName", function(accounts) {
  it("should assert true", async function() {
    const contract = await HelloWorld.deployed();
    await contract.setNumber(54);
    await contract.getNumber();
    const result = await contract.getNumber.call();
    assert.isTrue(result === 54);


  });
});

But I am getting the following error:

Contract: HelloWorld:getName
    1) should assert true
    > No events were emitted


  0 passing (241ms)
  1 failing

  1) Contract: HelloWorld:getName should assert true:
     AssertionError: expected false to be true

Can someone help me with the syntax? Or point me in the direction for learning?

Thanks in advance..

Answer:
Evelyn: 24 May 2022

The identity (===) operator behaves identically to the equality (==) operator except no type conversion is done, and the types must be the same to be considered equal.

And since the type of result is BigNumber, the expression result === 54 evaluates to false.

So you need to change this:

assert(result === 54);

Either to this:

assert(result == 54);

Or to this:

assert(result.equals(54));

Personally I prefer the latter, because I "trust" the implicit conversion inside the BigNumber.equals function better than whatever is implemented in the == operator (since there are several ways to handle the two arguments passed to ==, but there is only one plausible way to handle the argument passed to BigNumber.equals).

See here (https://mikemcl.github.io/bignumber.js/) for all you need to know about BigNumber...