松露和Ganache-cli测试用例失败

时间:2018-12-21 07:42:11

标签: solidity web3 truffle ganache

所以我有以下设置:truffleganache-cli

我正在向合同发送一些以太币,这是合同的相关部分:

    mapping(address => uint256) public balanceOf;

    function () payable public {
              uint amount = msg.value;
              balanceOf[msg.sender] += amount;
        }

在松露中,这就是我发送以太币的方式。

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
               });
});

我做对了吗?测试失败的原因可能是什么? 松露测试输出:

AssertionError: expected 0 to be at least 1
      + expected - actual

      -0
      +1

如果需要,我可以提供更多信息。

更新: 明确说明sale是全局变量。

   it("Test if MyContract is deployed", function(){
            return MyContract.deployed().then(function(instance){
                   sale = instance;
            });
   });

1 个答案:

答案 0 :(得分:1)

我认为这就是您想要的:

文件路径: test / vault.js

FormControl

您可以看到完整的项目here。请注意,我正在使用Truffle v5Ganache v2。请参阅该GitLab存储库中的README文件。

回到您的问题,有2个错误:

  1. const Vault = artifacts.require("Vault"); contract("Vault test", async accounts => { // Rely on one instance for all tests. let vault; let fromAccount = accounts[0]; let oneEtherInWei = web3.utils.toWei('1', 'ether'); // Runs before all tests. // https://mochajs.org/#hooks before(async () => { vault = await Vault.deployed(); }); // The `receipt` will return boolean. // https://web3js.readthedocs.io/en/1.0/web3-eth.html#gettransactionreceipt it("Test if 1 ether can be paid", async () => { let receipt = await web3.eth.sendTransaction({ from: fromAccount, to: vault.address, value: oneEtherInWei }); expect(receipt.status).to.equal(true); }); it("Test if contract received 1 ether", async () => { let balance = await web3.eth.getBalance(vault.address); expect(balance).to.equal(oneEtherInWei); }); // In Web3JS v1.0, `fromWei` will return string. // In order to use `at.least`, string needs to be parsed to integer. it("Test if balanceOf fromAccount is at least 1 ether in the contract", async () => { let balanceOf = await vault.balanceOf.call(fromAccount); let balanceOfInt = parseInt(web3.utils.fromWei(balanceOf, 'ether')); expect(balanceOfInt).to.be.at.least(1); }); }); 未定义。我觉得您实际上是在指sale

  2. 为了在ChaiJS中使用least方法,您需要确保传递整数。 MyContract调用返回balanceOfBigNumber对象,您不能将其与BN方法一起使用。

仅供参考,Truffle v5现在默认使用.least(以前是BN)。进一步了解here

让我知道这是否有帮助。