Reputation: 1035
I have a solidity contract in the Truffle framework and I cannot figure out why my JS test doesn't work.
I'm trying to test the 'setPlayers' function, the contract works and the tests are running but I can't understand how to call the function in the test:
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);
}
}
Test file:
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");
})
})
})
Error:
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)
Upvotes: 0
Views: 1454
Reputation: 5637
There is no setPlayers
method in the contract as you had mentioned in the test.
You can not directly access the array of a contract in your javascript. First you need to call the players
as method.
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");
})
})
You could async/await
for better readability of your tests.
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");
});
Upvotes: 1