javascript - Truffle JS 测试不起作用

标签 javascript ethereum solidity truffle

我在 Truffle 框架中有一个 Solidity 合约,但我不明白为什么我的 JS 测试不起作用。

我正在尝试测试“setPlayers”函数,合约有效并且测试正在运行,但我不明白如何在测试中调用该函数:

pragma solidity ^0.4.23;

contract Swindle {
    string  public eventName;
    uint public entryFee;
    string[] public players;
    string public winner;
    uint public winnings;

    function comp(string _eventName, uint _entryFee) public {
        eventName = _eventName;
        entryFee = _entryFee;
    }

    function addPlayers(string _player) public {
        players.push(_player);
    }

    function winner(string _player) public returns (string, uint) {
        winner = _player;
        winnings = (players.length * entryFee);
        return (winner, winnings);
    } 
}

测试文件:

var Swindle = artifacts.require("Swindle");

contract('Swindle', function(accounts) {

    it('sets player to stuart', function(){
        return Swindle.deployed().then(function(instance) {
            swindle = instance;
            return swindle.addPlayers.call("stuart");
        }).then(function(swindle) {
            assert.equal(swindle.players[0], "stuart", "sets the total supply");
        })
    })
})

错误:

0 passing (302ms)
  1 failing

  1) Contract: Swindle
       sets player to stuart:
     TypeError: Cannot read property '0' of undefined
      at test/test-swindle.js:10:32
      at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:118:7)

最佳答案

正如您在测试中提到的那样,合约中没有 setPlayers 方法。

<小时/>

您无法在 JavaScript 中直接访问合约数组。首先,您需要调用 players 作为方法。

it('sets player to stuart', function(){
        return Swindle.deployed().then(function(instance) {
            swindle = instance;
            return swindle.addPlayers.call("stuart");
        }).then(function(swindle) {
            return swindle.players();
        }).then(function(players) {
            assert.equal(players[0], "stuart", "sets the total supply");
        })
    })
<小时/>

您可以async/await以获得更好的测试可读性。

it('sets player to stuart', async () => {
    let swindle = await Swindle.deployed();
    await swindle.addPlayers.call("stuart");
    let players = await swindle.players.call();
    assert.equal(players[0], "stuart", "sets the total supply");
});

关于javascript - Truffle JS 测试不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50630871/

相关文章:

ethereum - key 错误 : 'mainnet-fork' when using brownie console --network mainnet-fork

javascript - JS 不会将导入和声明的变量读取到 console.log 中

javascript - 如果输入在模糊时为空,请取消选中行复选框?

javascript - Node.js 库依赖对象键顺序是否可以接受?

solidity - 通过 javascript 计算 uniswap 对地址

ethereum - 存储兼容性 : Solidity upgradable smart contract using "proxy" design pattern and changing the mapping type

javascript - Truffle - 有什么方法可以自动生成测试用例吗?

javascript - 从 ACF 中继器字段传递单个 PHP 值

python - 如何创建以太钱包?

blockchain - 为什么我们不能通过智能合约将以太币发送到以太坊地址 0x1