Testing addPlayer()

Moving on, it’s time to define our first test. We will check whether the addPlayer() function operates properly. Put the following code inside the first contract function in your test file:

it("..should ADD players", async () => {
let Cp = await Cplayer.new();
for (let i = 0; i < 3; i++) {
await Cp.addPlayer("player" + i, 123, { from: accounts[i] });
const P = await Cp.players.call(accounts[i]);
assert.equal(P[2], accounts[i], "player not added");
}
});

As you can see, the test adopts Mocha's it syntax. If you’re not familiar with the Mocha framework, know that it is a function that is actually a test itself, which takes two arguments. The first is a message using natural language to describe our expectation for the test, and the second is a function that holds the body of the test.

In the preceding test, we create a new Cplayer contract and then add three players using the addPlayer() method. As you can see, we use await as we are dealing with an asynchronous call.

The test ends with an assertion test using assert.equal(<current>, <expected>, <message>);.

Obviously, as its name indicates, this function tests whether two values are equal. If this wasn't the case, it would cause an assertion failure and communicate the message you defined (optionally) as the third argument.

Now, run this first test using truffle test --network my_ganache.

Alternatively, you can specify a path to a specific file you want to run, for example, truffle test ./path/fileName.js --network my_ganache.

Each time you run the test, Truffle will automatically compile and migrate your contract for you. The test script should compile without any errors. Henceforth, you can continue using Truffle for testing each it block we define, or leave it until the end.

Great! Let’s move on and add the next test.

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

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