1- const defaultMatcher = function ( event ) { return true } ;
1+ const _ = require ( 'lodash' ) ;
2+
23module . exports = {
3- expectEvent : function ( contract , filter ) {
4- const emitterWitness = jest . fn ( ) ;
5- const eventPromise = new Promise ( ( resolve , reject ) => {
6- contract . on ( filter , function ( ) {
7- const event = arguments [ arguments . length - 1 ] ;
8- emitterWitness ( ) ;
9- resolve ( event ) ;
10- } ) ;
11-
12- // After 10s, we throw a timeout error
13- setTimeout ( ( ) => {
14- reject ( new Error ( 'timeout while waiting for event' ) ) ;
15- } , 10000 ) ;
16- } ) ;
17-
18- return { emitterWitness, eventPromise } ;
4+ expectEvent : async function ( txOrTxResult , expectedEventName , expectedEventArgs = { } ) {
5+ // Usage:
6+ // Pass a transaction result, in which case await is unnecessary
7+ // expectEvent(txResult, 'EventName', { argName: value })
8+ // OR
9+ // pass a transaction object
10+ // await expectEvent(await someContract.someFunction(), 'EventName', { argName: value })
11+
12+ let txResult = txOrTxResult
13+ if ( txOrTxResult . wait ) {
14+ // in this case, we were passed the result of `await someContract.someFunction(args)`,
15+ // which is the transasction got sent off, but hasn't yet been confirmed.
16+ txResult = await txOrTxResult . wait ( ) ;
17+ }
18+ const events = txResult . events ;
19+ const matchingEvents = events . filter ( event => {
20+ return event . event === expectedEventName && _ . isMatch ( event . args , expectedEventArgs )
21+ } )
22+ expect ( matchingEvents . length ) . toBeGreaterThan ( 0 ) ;
1923 }
2024}
0 commit comments