I try to check that a total of 4 events have been emitted by my contract instance. Next code will fail in the assert.equal line since getPastEvents will process the events in a callback and so the assert will be executed before the callback being able to process (and count) the events.

// NOTE: Error control removed for clarity.
it("SHOULD FETCH 4 EVENTS", async () => {                                                                     
  const EXPECTED_EVENT_COUNT = 4;                                                                             
  var TOTAL_COUNT = 0;                                                                                              
      { fromBlock: 0, toBlock: 'latest' },
      function(error, result) { 

Is there any trick to make the assert.equal line wait in a loop until a condition is met?

1 Answer 1


Solved! No need to use a callback to count for total number of event.

it("SHOULD FETCH 4 EVENTS", async () => {                                                                     
  const EXPECTED_EVENT_COUNT = 4;                                                                             
  const options = { fromBlock: 0, toBlock: 'latest' }

  const eventList = await 
  assert.equal(eventList.lenght, EXPECTED_EVENT_COUNT, "");

As adapted from: https://github.com/trufflesuite/truffle/blob/next/packages/truffle-contract/test/events.js#L134-L148

  • 3
    Do know though, that on the mainnet fetching from block 0, will bring you much inconsistency and sorrow, so you would prefer to use a much closer blocknumber, for example the contract whose events you are trying to fetch's deployment blocknumber.
    – Adibas03
    Mar 15, 2019 at 14:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.