Testing events

As you know, events are very useful for the functioning of DApps. Thus, we need to test whether our contract emits them properly. Here's an example of testing the NewActivePlayerEv event:

it(".. should emit 'NewActivePlayerEv' event  when a player joins the game", async function() {
let NewActivePlayerEvtListener = Ct.NewActivePlayerEv();
await Ct.join({ from: firstAccount, value:1 * Ether });
let proposalAddedLog = await new Promise((resolve, reject) =>
NewActivePlayerEvtListener.get((error, log) => error ? reject(error) : resolve(log)));
assert.equal(proposalAddedLog.length, 1, " event not emitted");
let eventArgs = proposalAddedLog[0].args;
assert.equal(eventArgs._address, firstAccount);
let time = await Ct.ping_time.call(firstAccount);
assert.equal(eventArgs.time, time.toNumber(), "ping time");
});

The important part in the preceding code snippet is the following line:

let proposalAddedLog = await new Promise( (resolve, reject) => 
NewActivePlayerEvtListener.get((error, log) => error ? reject(error) : resolve(log)));

Here, we create a new Promise to check whether the event was stored in the contract log. The proposalAddedLog object is expected to be an array containing one entry per event, representing the result of get(), which reads all the log entries .

Then we use assert.equal(proposalAddedLog.length, 1); to check whether a new event was stored (log array isn’t empty).

Once we have ensured that an event has been emitted, we assert that the address and timestamp returned by the event match the player's address and pinging time.

If you’re wondering why we use a toNumber() method, it ensures the result, which is a BigNumber, is converted into an integer.

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

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