So I have this setup : truffle
and ganache-cli
I'm sending some ether to my contract, here is the related part of my contract:
mapping(address => uint256) public balanceOf;
function () payable public {
uint amount = msg.value;
balanceOf[msg.sender] += amount;
}
In truffle this is how I send the ether.
it("Test if can be payed", function(){
return web3.eth.sendTransaction({
from:fromAddr,
to:MyContract.address,
value:amountToSend
}).then(function(res){
expect(res).to.not.be.an("error"); // test passed
});
});
it("Test if contract received ether", function(){
return web3.eth.getBalance(MyContract.address,
function(err, res){
expect(parseInt(res)).to.be.at.least(1000000000000000000); // test passed
});
});
it("Catch if balanceOf "+fromAddr, function(){
return sale.balanceOf.call(fromAddr).then(function(res){
expect(parseInt(res)).to.be.at.least(1); // fails the test
});
});
Am I doing it right? What could be the reason for failed test? truffle test output :
AssertionError: expected 0 to be at least 1
+ expected - actual
-0
+1
I can provide more info if needed.
parseInt(res)
returns 1000000000000000000 may possibly fail, since Javascript's max safe integer (Number.MAX_SAFE_INTEGER
) is much smaller (2 ^ 53 - 1
to be accurate).parseInt
onres
. If I'm not mistaken, thenres
is aBigNumber
(or aBN
in later versions of web3.js). This class has all the functionality that you need, for example,greaterThan
,equals
, etc. If I'm wrong andres
is a string, then convert it to aBigNumber
.expect(parseInt(res)).to.be.at.least(1000000000000000000)
withassert(res.greaterThanOrEqualTo("1000000000000000000"))
, andexpect(parseInt(res)).to.be.at.least(1)
withassert(res.greaterThanOrEqualTo("1"))
.it
,before
,after
, etc). Web3 is a protocol for communicating with an Ethereum node (Ganache in your case). Withsale.balanceOf.call
, you are not "doing it with Truffle". The call is eventually translated into a web3 message to Ganache. If you want to send ether in a "normal" function call (i.e., withoutweb3.eth.sendTransaction
), then just give a name to your fallback function (currently declared asfunction () payable public
), and call it the same way you call functionbalanceOf
.