From cde01ccab48039dad117fa95de8a6bb383452e7b Mon Sep 17 00:00:00 2001 From: Thomas Roberts <5656702+opr@users.noreply.github.com> Date: Wed, 12 Oct 2022 15:29:04 +0100 Subject: [PATCH] Check that the callback for filtering payment methods is available and is a function before trying to run it (#7377) * Check callback for payment method is available before trying to run it * Check if callback is a function before trying to run it * Update tests to ensure callbacks only run if they are registered --- .../payment-methods/payment-method-config-helper.ts | 6 ++++++ .../test/payment-method-config-helper.ts | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/assets/js/blocks-registry/payment-methods/payment-method-config-helper.ts b/assets/js/blocks-registry/payment-methods/payment-method-config-helper.ts index 3f0868f124d..df56325b76a 100644 --- a/assets/js/blocks-registry/payment-methods/payment-method-config-helper.ts +++ b/assets/js/blocks-registry/payment-methods/payment-method-config-helper.ts @@ -50,6 +50,12 @@ export const canMakePaymentWithExtensions = Object.entries( extensionsCallbacks ).forEach( ( [ namespace, callbacks ] ) => { + if ( + ! ( paymentMethodName in callbacks ) || + typeof callbacks[ paymentMethodName ] !== 'function' + ) { + return; + } namespacedCallbacks[ namespace ] = callbacks[ paymentMethodName ]; } diff --git a/assets/js/blocks-registry/payment-methods/test/payment-method-config-helper.ts b/assets/js/blocks-registry/payment-methods/test/payment-method-config-helper.ts index 2951725c3d7..4f75083d891 100644 --- a/assets/js/blocks-registry/payment-methods/test/payment-method-config-helper.ts +++ b/assets/js/blocks-registry/payment-methods/test/payment-method-config-helper.ts @@ -88,6 +88,9 @@ describe( 'payment-method-config-helper', () => { woopay: trueCallback, // testpay: one callback errors, one returns true testpay: throwsCallback, + // Used to check that only valid callbacks run in each namespace. It is not present in + // 'other-woocommerce-marketplace-extension'. + blocks_pay: trueCallback, } ); registerPaymentMethodExtensionCallbacks( @@ -202,5 +205,14 @@ describe( 'payment-method-config-helper', () => { expect( throwsCallback ).toHaveBeenCalledTimes( 1 ); expect( trueCallback ).toHaveBeenCalledTimes( 1 ); } ); + + it( 'Does not error when a callback for a payment method is in one namespace but not another', () => { + helpers.canMakePaymentWithExtensions( + () => true, + canMakePaymentExtensionsCallbacks, + 'blocks_pay' + )( canMakePaymentArgument ); + expect( console ).not.toHaveErrored(); + } ); } ); } );