Events

松露,getPastEvents 同步

  • January 7, 2020

我嘗試檢查我的合約實例總共發出了 4 個事件。下一assert.equal行程式碼將失敗,因為 getPastEvents 將在回調中處理事件,因此斷言將在回調能夠處理(和計數)事件之前執行。

// 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, "");
})

有什麼技巧可以讓assert.equal線路在循環中等待直到滿足條件?

解決了!無需使用回調來計算事件總數。

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, "");
})

改編自:https ://github.com/trufflesuite/truffle/blob/next/packages/truffle-contract/test/events.js#L134-L148

引用自:https://ethereum.stackexchange.com/questions/68391