Fix event-emitters not accounting for observers as Object type. (https://github.com/woocommerce/woocommerce-blocks/pull/2010)

* Fix assumption of eventemitters stored in state as an arry.

* update tests to mock expected emitter state
This commit is contained in:
Darren Ethier 2020-03-23 11:32:52 -04:00 committed by GitHub
parent f8e05ef09d
commit 1d210e184b
2 changed files with 8 additions and 4 deletions

View File

@ -15,7 +15,9 @@
* executed. * executed.
*/ */
export const emitEvent = async ( observers, eventType, data ) => { export const emitEvent = async ( observers, eventType, data ) => {
const observersByType = observers[ eventType ] || []; const observersByType = observers[ eventType ]
? Object.values( observers[ eventType ] )
: [];
for ( let i = 0; i < observersByType.length; i++ ) { for ( let i = 0; i < observersByType.length; i++ ) {
try { try {
await Promise.resolve( observersByType[ i ]( data ) ); await Promise.resolve( observersByType[ i ]( data ) );
@ -43,7 +45,9 @@ export const emitEvent = async ( observers, eventType, data ) => {
* return value of the aborted observer. * return value of the aborted observer.
*/ */
export const emitEventWithAbort = async ( observers, eventType, data ) => { export const emitEventWithAbort = async ( observers, eventType, data ) => {
const observersByType = observers[ eventType ] || []; const observersByType = observers[ eventType ]
? Object.values( observers[ eventType ] )
: [];
for ( let i = 0; i < observersByType.length; i++ ) { for ( let i = 0; i < observersByType.length; i++ ) {
try { try {
const response = await Promise.resolve( const response = await Promise.resolve(

View File

@ -18,7 +18,7 @@ describe( 'Testing emitters', () => {
} ); } );
describe( 'Testing emitEvent()', () => { describe( 'Testing emitEvent()', () => {
it( 'invokes all observers', async () => { it( 'invokes all observers', async () => {
const observers = { test: Object.values( observerMocks ) }; const observers = { test: observerMocks };
const response = await emitEvent( observers, 'test', 'foo' ); const response = await emitEvent( observers, 'test', 'foo' );
expect( console ).toHaveErroredWith( 'an error' ); expect( console ).toHaveErroredWith( 'an error' );
expect( observerMocks.observerA ).toHaveBeenCalledTimes( 1 ); expect( observerMocks.observerA ).toHaveBeenCalledTimes( 1 );
@ -31,7 +31,7 @@ describe( 'Testing emitters', () => {
'aborts on non truthy value and does not invoke remaining ' + 'aborts on non truthy value and does not invoke remaining ' +
'observers', 'observers',
async () => { async () => {
const observers = { test: Object.values( observerMocks ) }; const observers = { test: observerMocks };
const response = await emitEventWithAbort( const response = await emitEventWithAbort(
observers, observers,
'test', 'test',