Getting error while testing transfer function using chai

chaisoliditytestingtruffle

I have a function that transfers the amount from owner to user. I'm getting success in the event emitted message and my test is failing every time.

Here is my code.

function investInMPay(uint256 _amount) public validateInvestor(_amount) {
        Investors[msg.sender] = investor(block.timestamp, _amount);
        transferTokenToInvestor(msg.sender, _amount);
    }

function transferTokenToInvestor(address _to, uint256 _value) public returns (bool success) {
       require(balanceOf[owner] >= _value);
        _transfer(owner, _to, _value);
        return true; 
    }

function _transfer(address _from, address _to, uint256 _value) internal {
        require(_to != address(0));
        balanceOf[_from] -= _value;
        balanceOf[_to] += _value;
        emit Transfer(_from, _to, _value, balanceOf[_to]);
    }

Here is a test that I have written.

it('test token transfer', async () => {
                invest = await Invest.new();
                await invest.investInMPay(ether(1), { from: user })
                let result = await token.balanceOf(user)
                assert.equal(result.toString(),tokens(1).toString());
            })

While running the test I'm getting following error.

Events emitted during test:
---------------------------

    Token.Transfer(
      from: <indexed> 0xf3a429e4FAFf561f5AD75A3F944Bc14432b225ee (type: address),
      to: <indexed> 0x273638fa06e2A6870566D1fbe5F3D37402A95655 (type: address),
      _value: 1000000000000000000 (type: uint256),
      balance: 1000000000000000000 (type: uint256)
    )
<----ERROR---->
    success
          test token transfer:
    
          AssertionError: expected '0' to equal '1000000000000000000'
          + expected - actual
    
          -0
          +1000000000000000000

Best Answer

       await invest.investInMPay(ether(1), { from: user })
       let result = await token.balanceOf(user)

I think this is token.balanceOf not returning updated state. In "invest" contract you already have balanceOf mapping so if you get the result directly from the mapping it should work. if you define the balanceOf inside invest contact

function balanceOf(address _owner) public view override returns (uint256 balance){
        // since name of the func is balanceOf, I named the mapping as tokenBalances
        return tokenBalances[_owner];
    }

so get the result:

   let result = await invest.balanceOf(user)      

It is not clear what token is in your testing function. probably token is another contract you keep the state, but that state is not getting updated and when you write invest.balanceOf(user) you are getting 0 as the default value. In solidity mapping, if the key does not exist, since you probably defined mapping mapping(address=>uint) balanceOf, you are getting a default value of 0 for uint

Related Topic