Testing a payable function

The first function to test in Ctontine will be join(), which is payable. We therefore need to check whether a player registered in Cplayer is able to deposit ether and join the active players list:

it(".. should enable players to join the game", async () => {
await Ct.join({ from: firstAccount, value: 1 * Ether });
let P1 = await Ct.active_players(0);
assert.equal(P1[0], "player0", "Player hasn’t joined the game");
let CtBalance = await getBalance(Ct.address);
assert.equal(CtBalance, 1 * Ether, "Contract hasn't received the deposit");
});

As you know, by default, the amount sent in a transaction is specified in wei, so if you only put 1 in the value field, it will be considered as 1 wei, which doesn't fulfill the requirement. In addition to this, Truffle doesn't recognise ether as a unit, therefore as a solution, we need to define a global constant at the top of our test file: const Ether = 10 * 18. By using this constant, we will be able to express values directly in ether.

After calling the join() method, we assert whether the player has been added to the active player list by comparing the player’s name stored in the active player list with the name used in the test: assert.equal(P1[0], "player0", "Player hasn’t joined the game");.

We also assert that funds have been successfully deposited by comparing the deposited amount to the contract balance. If the player has successfully joined the game, the contract balance should be 1 ether.

In Truffle’s tests, to get the contract’s balance, we had to use the web3.js method, getBalance(address). In this example, I have encapsulated the getBalance() method in a separate module, defined in a new getBalance.js file:

module.exports.getBalance = function getBalance(address) {
return web3.eth.getBalance(address);
};

This is then imported into the test file using const { getBalance } = require("./getBalance");.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset