0

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;                                                                                              
  myContractInstance.getPastEvents(
      'MyTestedEvent',
      { fromBlock: 0, toBlock: 'latest' },
      function(error, result) { 
        TOTAL_COUNT++; 
      }
  );
  assert.equal(TOTAL_COUNT, EXPECTED_EVENT_COUNT, "");
})

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

0

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 
     myContractInstance.getPastEvents('MyTestedEvent',options);
  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

1
  • 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 '19 at 14:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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