'How to test smart contract with cross-contract invoke using truffle?

I have two contract, I write in in one file, named Sum.sol. The sum contract invoke Add contract. I just want to test cross-contract invoking. If I didn't put the two contract in one file, The compile of Sum using truffle would fail. But when I do the test, the result is so weird. I don't know how this happened.

pragma solidity ^0.4.6;
contract Add{
  function sum(uint x, uint y) returns(uint){
    return x+y;
  }
}
contract Sum{
  function func(uint x, uint y) returns(uint){
    Add add = new Add();
    uint re = add.sum(x,y);
    return re;
  }
}

then I write a test for it In truffle

contract('Sum', function(accounts) {
  it("should return 5 when add 2 and 3", function() {
    var sum = Sum.deployed();

    return sum.func.call(2,3).then(function(res){
      assert.equal(res.valueOf(), 5, "add result is 5");

    });
  });
});

And test it using truffle, then, the results is:

Compiling Sum.sol...


  Contract: Sum
    1) should return 5 when add 2 and 3
    > No events were emitted


  0 passing (455ms)
  1 failing

  1) Contract: Sum should return 5 when add 2 and 3:
     AssertionError: add result is 5: expected   '9.1735649321334958107552852973512799782292704141468709142420585807991067901952e+76' to equal 5
      at /Users/maiffany/testcoverage/test/add.js:6:14
      at process._tickDomainCallback         (internal/process/next_tick.js:129:7)


Solution 1:[1]

I'm not sure why your test wasn't working 3 months ago because both testrpc and truffle have changed a lot since then. In its current state, your test would fail because Sum.deployed() is going to return a promise (which you can't call functions on directly).

I got your test passing with the following code:

var Sum = artifacts.require("./Sum.sol");

contract('Sum', function(accounts) {
  it("should return 5 when add 2 and 3", function() {
    Sum.deployed().then(function(instance){
      instance.func.call(2,3).then(function(res){
        assert.equal(res.valueOf(), 5, "add result is 5");
      });
    });
  });
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pang