woocommerce/plugins/woocommerce-blocks/assets/js/data/payment-methods/test/selectors.js

334 lines
8.6 KiB
JavaScript
Raw Normal View History

/**
* External dependencies
*/
import { render, screen, waitFor, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { previewCart } from '@woocommerce/resource-previews';
Refactor registration of payment methods and update unit tests for payment data store (https://github.com/woocommerce/woocommerce-blocks/pull/6669) * Mock getCartTotals * Change test to use data store instead of context * Move payment method context test to data store selectors * Change description of test suite * Bump commit to trigger tests * Fix path in test * update package lock * Set correct state payment method reducer tests/use correct actions * Get saved payment methods from store not context * Mock stores and update tests to allow switching payment methods * Update tests to get onSubmit from checkoutEventsContext * Remove cartTotalsLoaded check from payment method initialize check * Make PaymentMethods test wait until payments initialized * initialize payment method data store when cart is loaded * Remove unneeded actions and add initializePaymentMethodDataStore * Remove check for cart totals loaded in checkPaymentMethods * Remove updateAvilablePaymentMethods from registry * Remove unneeded mock * Remove unused import * Rename imports to fix eslint errors * Remove unused imports * Remove return false from checkPaymentMethods * Remove unnecessary setPaymentMethodsInitialized call * Add todo comment to track refactoring opportunity * Remove savedpayment methods from payment method context and rename it * Rename payment method data context to payment method events context * Add tests for setDefaultPaymentMethods * Optimize the availablePaymentMethods state data Store only the "name" attribute for now. * Get list of payment methods from the registry instead of the store We are using this hook to get some React elements in the payment method object. So, we are getting the raw data directly from the registry instead of the store. * Fix payment state not loading on the Checkout edit page * Handle checkout edit page case * Fix infinite loop error on C&C Blocks * Include @wordpress/redux-routine in transformIgnorePatterns jest config Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
2022-08-22 13:56:44 +00:00
import * as wpDataFunctions from '@wordpress/data';
import {
CART_STORE_KEY as storeKey,
PAYMENT_METHOD_DATA_STORE_KEY,
} from '@woocommerce/block-data';
import {
registerPaymentMethod,
registerExpressPaymentMethod,
__experimentalDeRegisterPaymentMethod,
__experimentalDeRegisterExpressPaymentMethod,
} from '@woocommerce/blocks-registry';
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
import { default as fetchMock } from 'jest-fetch-mock';
/**
* Internal dependencies
*/
import {
CheckoutExpressPayment,
SavedPaymentMethodOptions,
Refactor registration of payment methods and update unit tests for payment data store (https://github.com/woocommerce/woocommerce-blocks/pull/6669) * Mock getCartTotals * Change test to use data store instead of context * Move payment method context test to data store selectors * Change description of test suite * Bump commit to trigger tests * Fix path in test * update package lock * Set correct state payment method reducer tests/use correct actions * Get saved payment methods from store not context * Mock stores and update tests to allow switching payment methods * Update tests to get onSubmit from checkoutEventsContext * Remove cartTotalsLoaded check from payment method initialize check * Make PaymentMethods test wait until payments initialized * initialize payment method data store when cart is loaded * Remove unneeded actions and add initializePaymentMethodDataStore * Remove check for cart totals loaded in checkPaymentMethods * Remove updateAvilablePaymentMethods from registry * Remove unneeded mock * Remove unused import * Rename imports to fix eslint errors * Remove unused imports * Remove return false from checkPaymentMethods * Remove unnecessary setPaymentMethodsInitialized call * Add todo comment to track refactoring opportunity * Remove savedpayment methods from payment method context and rename it * Rename payment method data context to payment method events context * Add tests for setDefaultPaymentMethods * Optimize the availablePaymentMethods state data Store only the "name" attribute for now. * Get list of payment methods from the registry instead of the store We are using this hook to get some React elements in the payment method object. So, we are getting the raw data directly from the registry instead of the store. * Fix payment state not loading on the Checkout edit page * Handle checkout edit page case * Fix infinite loop error on C&C Blocks * Include @wordpress/redux-routine in transformIgnorePatterns jest config Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
2022-08-22 13:56:44 +00:00
} from '../../../blocks/cart-checkout-shared/payment-methods';
import { checkPaymentMethodsCanPay } from '../../payment-methods/check-payment-methods';
import { defaultCartState } from '../../cart/default-state';
Refactor registration of payment methods and update unit tests for payment data store (https://github.com/woocommerce/woocommerce-blocks/pull/6669) * Mock getCartTotals * Change test to use data store instead of context * Move payment method context test to data store selectors * Change description of test suite * Bump commit to trigger tests * Fix path in test * update package lock * Set correct state payment method reducer tests/use correct actions * Get saved payment methods from store not context * Mock stores and update tests to allow switching payment methods * Update tests to get onSubmit from checkoutEventsContext * Remove cartTotalsLoaded check from payment method initialize check * Make PaymentMethods test wait until payments initialized * initialize payment method data store when cart is loaded * Remove unneeded actions and add initializePaymentMethodDataStore * Remove check for cart totals loaded in checkPaymentMethods * Remove updateAvilablePaymentMethods from registry * Remove unneeded mock * Remove unused import * Rename imports to fix eslint errors * Remove unused imports * Remove return false from checkPaymentMethods * Remove unnecessary setPaymentMethodsInitialized call * Add todo comment to track refactoring opportunity * Remove savedpayment methods from payment method context and rename it * Rename payment method data context to payment method events context * Add tests for setDefaultPaymentMethods * Optimize the availablePaymentMethods state data Store only the "name" attribute for now. * Get list of payment methods from the registry instead of the store We are using this hook to get some React elements in the payment method object. So, we are getting the raw data directly from the registry instead of the store. * Fix payment state not loading on the Checkout edit page * Handle checkout edit page case * Fix infinite loop error on C&C Blocks * Include @wordpress/redux-routine in transformIgnorePatterns jest config Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
2022-08-22 13:56:44 +00:00
const originalSelect = jest.requireActual( '@wordpress/data' ).select;
jest.spyOn( wpDataFunctions, 'select' ).mockImplementation( ( storeName ) => {
const originalStore = originalSelect( storeName );
if ( storeName === storeKey ) {
return {
...originalStore,
hasFinishedResolution: jest
.fn()
.mockImplementation( ( selectorName ) => {
if ( selectorName === 'getCartTotals' ) {
return true;
}
return originalStore.hasFinishedResolution( selectorName );
} ),
};
}
return originalStore;
} );
jest.mock( '@woocommerce/settings', () => {
const originalModule = jest.requireActual( '@woocommerce/settings' );
return {
// @ts-ignore We know @woocommerce/settings is an object.
...originalModule,
getSetting: ( setting, ...rest ) => {
if ( setting === 'customerPaymentMethods' ) {
return {
cc: [
{
method: {
gateway: 'credit-card',
last4: '4242',
brand: 'Visa',
},
expires: '12/22',
is_default: true,
tokenId: 1,
},
],
};
}
return originalModule.getSetting( setting, ...rest );
},
};
} );
const registerMockPaymentMethods = ( savedCards = true ) => {
[ 'cheque', 'bacs' ].forEach( ( name ) => {
registerPaymentMethod( {
name,
label: name,
content: <div>A payment method</div>,
edit: <div>A payment method</div>,
icons: null,
canMakePayment: () => true,
supports: {
features: [ 'products' ],
},
ariaLabel: name,
} );
} );
[ 'credit-card' ].forEach( ( name ) => {
registerPaymentMethod( {
name,
label: name,
content: <div>A payment method</div>,
edit: <div>A payment method</div>,
icons: null,
canMakePayment: () => true,
supports: {
showSavedCards: savedCards,
Change payment processing for subscriptions (https://github.com/woocommerce/woocommerce-blocks/pull/3686) * Remove savePaymentInfo check when displaying payment methods This is because the savePaymentInfo is derived from whether the save payment method checkbox shows. This check doesn't make sense to do because it's not a good indicator of whether the payment method is enabled. Subscriptions for example hides the checkbox because it is implied that the method will be saved. We should instead rely on the server-side to only send permitted saved payment methods. * Add safely_get_request_payment_method This will allow us to try to get the payment method if it was passed in the request, but will default to an empty string if not. This is different to get_request_payment_method because it doesn't throw any errors. We need it to be different because get_request_payment_method is used when the order definitely needs payment (so a normal checkout scenario, vs. a £0 subscription checkout) * Add action to update order meta when checking out This is needed because some extensions rely on this action to add their information to the metadata of order items. * Remove safely_get_request_payment_method This is no longer needed. * Remove @since from experimental hook * Add PHPDoc for new update_order_meta hook * Document use of experimental hook * Reinstate the check for allowing saved cards * Add method to Stripe integration to determine if saved_cards is enabled * Add new field to get_payment_method_data This adds displaySavePaymentMethodCheckbox which will be used to determine if the checkbox to save payment methods should display. * Add displaySavePaymentMethodCheckbox option to client This will determine whether the "Save payment information" checkbox will be displayed. * Add requiresSaving option to Stripe payment method data This is informed by the saved_cards option and the result of the wc_stripe_display_save_payment_method_checkbox filter. * Rename displaySavePaymentMethodCheckbox to requiresSaving & fix logic * Revert negation on display_save_payment method_checkbox filter & rename We are going to rename the properties we use to determine whether saved cards are shown, or whether the save payment method checkbox is shown, so that their names are more descriptive of what they are for. * Rename allowSavedCards and requiresSaving in Stripe integration * Rename savePaymentInfo&requiresSaving to showSavedCards & showSaveOption This is so we can hide the checkbox independently of hiding the saved payment methods. * Show deprecated message if payment methods use savePaymentInfo This is because we are leaving it in to enable backward compatibility but payment methods registering using this should be informed of the change in case it gets removed. * Update Stripe typedefs and keys of supports object * Show customer payment methods if showSavedCards is true on the method * Make PaymentMethodTab accept showSaveOption prop This will allow us to show the save checkbox only if the payment method says it should be shown. * Update tests to use new keys in supports when reg'ing payment methods * Add optional chaining when validating payment method config This makes the code a little tidier :) * Update assets/js/blocks-registry/payment-methods/payment-method-config.js Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com> * Add more information to deprecated call in payment method config * Fix lint error * Fix prop types for PaymentMethodTab * Add information about supports on payment methods to docs Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
2021-01-24 13:59:13 +00:00
showSaveOption: true,
features: [ 'products' ],
},
ariaLabel: name,
} );
} );
[ 'express-payment' ].forEach( ( name ) => {
const Content = ( {
onClose = () => void null,
onClick = () => void null,
} ) => {
return (
<>
<button onClick={ onClick }>
{ name + ' express payment method' }
</button>
<button onClick={ onClose }>
{ name + ' express payment method close' }
</button>
</>
);
};
registerExpressPaymentMethod( {
name,
content: <Content />,
edit: <div>An express payment method</div>,
canMakePayment: () => true,
paymentMethodId: name,
supports: {
features: [ 'products' ],
},
} );
} );
checkPaymentMethodsCanPay();
checkPaymentMethodsCanPay( true );
};
const resetMockPaymentMethods = () => {
[ 'cheque', 'bacs', 'credit-card' ].forEach( ( name ) => {
__experimentalDeRegisterPaymentMethod( name );
} );
[ 'express-payment' ].forEach( ( name ) => {
__experimentalDeRegisterExpressPaymentMethod( name );
} );
};
Refactor registration of payment methods and update unit tests for payment data store (https://github.com/woocommerce/woocommerce-blocks/pull/6669) * Mock getCartTotals * Change test to use data store instead of context * Move payment method context test to data store selectors * Change description of test suite * Bump commit to trigger tests * Fix path in test * update package lock * Set correct state payment method reducer tests/use correct actions * Get saved payment methods from store not context * Mock stores and update tests to allow switching payment methods * Update tests to get onSubmit from checkoutEventsContext * Remove cartTotalsLoaded check from payment method initialize check * Make PaymentMethods test wait until payments initialized * initialize payment method data store when cart is loaded * Remove unneeded actions and add initializePaymentMethodDataStore * Remove check for cart totals loaded in checkPaymentMethods * Remove updateAvilablePaymentMethods from registry * Remove unneeded mock * Remove unused import * Rename imports to fix eslint errors * Remove unused imports * Remove return false from checkPaymentMethods * Remove unnecessary setPaymentMethodsInitialized call * Add todo comment to track refactoring opportunity * Remove savedpayment methods from payment method context and rename it * Rename payment method data context to payment method events context * Add tests for setDefaultPaymentMethods * Optimize the availablePaymentMethods state data Store only the "name" attribute for now. * Get list of payment methods from the registry instead of the store We are using this hook to get some React elements in the payment method object. So, we are getting the raw data directly from the registry instead of the store. * Fix payment state not loading on the Checkout edit page * Handle checkout edit page case * Fix infinite loop error on C&C Blocks * Include @wordpress/redux-routine in transformIgnorePatterns jest config Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
2022-08-22 13:56:44 +00:00
describe( 'Payment method data store selectors/thunks', () => {
beforeEach( () => {
act( () => {
registerMockPaymentMethods( false );
fetchMock.mockResponse( ( req ) => {
if ( req.url.match( /wc\/store\/v1\/cart/ ) ) {
return Promise.resolve( JSON.stringify( previewCart ) );
}
return Promise.resolve( '' );
} );
// need to clear the store resolution state between tests.
Refactor registration of payment methods and update unit tests for payment data store (https://github.com/woocommerce/woocommerce-blocks/pull/6669) * Mock getCartTotals * Change test to use data store instead of context * Move payment method context test to data store selectors * Change description of test suite * Bump commit to trigger tests * Fix path in test * update package lock * Set correct state payment method reducer tests/use correct actions * Get saved payment methods from store not context * Mock stores and update tests to allow switching payment methods * Update tests to get onSubmit from checkoutEventsContext * Remove cartTotalsLoaded check from payment method initialize check * Make PaymentMethods test wait until payments initialized * initialize payment method data store when cart is loaded * Remove unneeded actions and add initializePaymentMethodDataStore * Remove check for cart totals loaded in checkPaymentMethods * Remove updateAvilablePaymentMethods from registry * Remove unneeded mock * Remove unused import * Rename imports to fix eslint errors * Remove unused imports * Remove return false from checkPaymentMethods * Remove unnecessary setPaymentMethodsInitialized call * Add todo comment to track refactoring opportunity * Remove savedpayment methods from payment method context and rename it * Rename payment method data context to payment method events context * Add tests for setDefaultPaymentMethods * Optimize the availablePaymentMethods state data Store only the "name" attribute for now. * Get list of payment methods from the registry instead of the store We are using this hook to get some React elements in the payment method object. So, we are getting the raw data directly from the registry instead of the store. * Fix payment state not loading on the Checkout edit page * Handle checkout edit page case * Fix infinite loop error on C&C Blocks * Include @wordpress/redux-routine in transformIgnorePatterns jest config Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
2022-08-22 13:56:44 +00:00
wpDataFunctions.dispatch( storeKey ).invalidateResolutionForStore();
wpDataFunctions
.dispatch( storeKey )
.receiveCart( defaultCartState.cartData );
} );
} );
afterEach( async () => {
act( () => {
resetMockPaymentMethods();
fetchMock.resetMocks();
} );
} );
it( 'toggles active payment method correctly for express payment activation and close', async () => {
const TriggerActiveExpressPaymentMethod = () => {
Refactor registration of payment methods and update unit tests for payment data store (https://github.com/woocommerce/woocommerce-blocks/pull/6669) * Mock getCartTotals * Change test to use data store instead of context * Move payment method context test to data store selectors * Change description of test suite * Bump commit to trigger tests * Fix path in test * update package lock * Set correct state payment method reducer tests/use correct actions * Get saved payment methods from store not context * Mock stores and update tests to allow switching payment methods * Update tests to get onSubmit from checkoutEventsContext * Remove cartTotalsLoaded check from payment method initialize check * Make PaymentMethods test wait until payments initialized * initialize payment method data store when cart is loaded * Remove unneeded actions and add initializePaymentMethodDataStore * Remove check for cart totals loaded in checkPaymentMethods * Remove updateAvilablePaymentMethods from registry * Remove unneeded mock * Remove unused import * Rename imports to fix eslint errors * Remove unused imports * Remove return false from checkPaymentMethods * Remove unnecessary setPaymentMethodsInitialized call * Add todo comment to track refactoring opportunity * Remove savedpayment methods from payment method context and rename it * Rename payment method data context to payment method events context * Add tests for setDefaultPaymentMethods * Optimize the availablePaymentMethods state data Store only the "name" attribute for now. * Get list of payment methods from the registry instead of the store We are using this hook to get some React elements in the payment method object. So, we are getting the raw data directly from the registry instead of the store. * Fix payment state not loading on the Checkout edit page * Handle checkout edit page case * Fix infinite loop error on C&C Blocks * Include @wordpress/redux-routine in transformIgnorePatterns jest config Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
2022-08-22 13:56:44 +00:00
const activePaymentMethod = wpDataFunctions.useSelect(
( select ) => {
return select(
PAYMENT_METHOD_DATA_STORE_KEY
).getActivePaymentMethod();
}
);
return (
<>
<CheckoutExpressPayment />
{ 'Active Payment Method: ' + activePaymentMethod }
</>
);
};
const TestComponent = () => {
Refactor registration of payment methods and update unit tests for payment data store (https://github.com/woocommerce/woocommerce-blocks/pull/6669) * Mock getCartTotals * Change test to use data store instead of context * Move payment method context test to data store selectors * Change description of test suite * Bump commit to trigger tests * Fix path in test * update package lock * Set correct state payment method reducer tests/use correct actions * Get saved payment methods from store not context * Mock stores and update tests to allow switching payment methods * Update tests to get onSubmit from checkoutEventsContext * Remove cartTotalsLoaded check from payment method initialize check * Make PaymentMethods test wait until payments initialized * initialize payment method data store when cart is loaded * Remove unneeded actions and add initializePaymentMethodDataStore * Remove check for cart totals loaded in checkPaymentMethods * Remove updateAvilablePaymentMethods from registry * Remove unneeded mock * Remove unused import * Rename imports to fix eslint errors * Remove unused imports * Remove return false from checkPaymentMethods * Remove unnecessary setPaymentMethodsInitialized call * Add todo comment to track refactoring opportunity * Remove savedpayment methods from payment method context and rename it * Rename payment method data context to payment method events context * Add tests for setDefaultPaymentMethods * Optimize the availablePaymentMethods state data Store only the "name" attribute for now. * Get list of payment methods from the registry instead of the store We are using this hook to get some React elements in the payment method object. So, we are getting the raw data directly from the registry instead of the store. * Fix payment state not loading on the Checkout edit page * Handle checkout edit page case * Fix infinite loop error on C&C Blocks * Include @wordpress/redux-routine in transformIgnorePatterns jest config Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
2022-08-22 13:56:44 +00:00
return <TriggerActiveExpressPaymentMethod />;
};
render( <TestComponent /> );
// should initialize by default the first payment method.
await waitFor( () => {
const activePaymentMethod = screen.queryByText(
Refactor registration of payment methods and update unit tests for payment data store (https://github.com/woocommerce/woocommerce-blocks/pull/6669) * Mock getCartTotals * Change test to use data store instead of context * Move payment method context test to data store selectors * Change description of test suite * Bump commit to trigger tests * Fix path in test * update package lock * Set correct state payment method reducer tests/use correct actions * Get saved payment methods from store not context * Mock stores and update tests to allow switching payment methods * Update tests to get onSubmit from checkoutEventsContext * Remove cartTotalsLoaded check from payment method initialize check * Make PaymentMethods test wait until payments initialized * initialize payment method data store when cart is loaded * Remove unneeded actions and add initializePaymentMethodDataStore * Remove check for cart totals loaded in checkPaymentMethods * Remove updateAvilablePaymentMethods from registry * Remove unneeded mock * Remove unused import * Rename imports to fix eslint errors * Remove unused imports * Remove return false from checkPaymentMethods * Remove unnecessary setPaymentMethodsInitialized call * Add todo comment to track refactoring opportunity * Remove savedpayment methods from payment method context and rename it * Rename payment method data context to payment method events context * Add tests for setDefaultPaymentMethods * Optimize the availablePaymentMethods state data Store only the "name" attribute for now. * Get list of payment methods from the registry instead of the store We are using this hook to get some React elements in the payment method object. So, we are getting the raw data directly from the registry instead of the store. * Fix payment state not loading on the Checkout edit page * Handle checkout edit page case * Fix infinite loop error on C&C Blocks * Include @wordpress/redux-routine in transformIgnorePatterns jest config Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
2022-08-22 13:56:44 +00:00
/Active Payment Method: credit-card/
);
expect( activePaymentMethod ).not.toBeNull();
} );
// Express payment method clicked.
userEvent.click(
screen.getByText( 'express-payment express payment method' )
);
await waitFor( () => {
const activePaymentMethod = screen.queryByText(
/Active Payment Method: express-payment/
);
expect( activePaymentMethod ).not.toBeNull();
} );
// Express payment method closed.
userEvent.click(
screen.getByText( 'express-payment express payment method close' )
);
await waitFor( () => {
const activePaymentMethod = screen.queryByText(
Refactor registration of payment methods and update unit tests for payment data store (https://github.com/woocommerce/woocommerce-blocks/pull/6669) * Mock getCartTotals * Change test to use data store instead of context * Move payment method context test to data store selectors * Change description of test suite * Bump commit to trigger tests * Fix path in test * update package lock * Set correct state payment method reducer tests/use correct actions * Get saved payment methods from store not context * Mock stores and update tests to allow switching payment methods * Update tests to get onSubmit from checkoutEventsContext * Remove cartTotalsLoaded check from payment method initialize check * Make PaymentMethods test wait until payments initialized * initialize payment method data store when cart is loaded * Remove unneeded actions and add initializePaymentMethodDataStore * Remove check for cart totals loaded in checkPaymentMethods * Remove updateAvilablePaymentMethods from registry * Remove unneeded mock * Remove unused import * Rename imports to fix eslint errors * Remove unused imports * Remove return false from checkPaymentMethods * Remove unnecessary setPaymentMethodsInitialized call * Add todo comment to track refactoring opportunity * Remove savedpayment methods from payment method context and rename it * Rename payment method data context to payment method events context * Add tests for setDefaultPaymentMethods * Optimize the availablePaymentMethods state data Store only the "name" attribute for now. * Get list of payment methods from the registry instead of the store We are using this hook to get some React elements in the payment method object. So, we are getting the raw data directly from the registry instead of the store. * Fix payment state not loading on the Checkout edit page * Handle checkout edit page case * Fix infinite loop error on C&C Blocks * Include @wordpress/redux-routine in transformIgnorePatterns jest config Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
2022-08-22 13:56:44 +00:00
/Active Payment Method: credit-card/
);
expect( activePaymentMethod ).not.toBeNull();
} );
} );
} );
Refactor registration of payment methods and update unit tests for payment data store (https://github.com/woocommerce/woocommerce-blocks/pull/6669) * Mock getCartTotals * Change test to use data store instead of context * Move payment method context test to data store selectors * Change description of test suite * Bump commit to trigger tests * Fix path in test * update package lock * Set correct state payment method reducer tests/use correct actions * Get saved payment methods from store not context * Mock stores and update tests to allow switching payment methods * Update tests to get onSubmit from checkoutEventsContext * Remove cartTotalsLoaded check from payment method initialize check * Make PaymentMethods test wait until payments initialized * initialize payment method data store when cart is loaded * Remove unneeded actions and add initializePaymentMethodDataStore * Remove check for cart totals loaded in checkPaymentMethods * Remove updateAvilablePaymentMethods from registry * Remove unneeded mock * Remove unused import * Rename imports to fix eslint errors * Remove unused imports * Remove return false from checkPaymentMethods * Remove unnecessary setPaymentMethodsInitialized call * Add todo comment to track refactoring opportunity * Remove savedpayment methods from payment method context and rename it * Rename payment method data context to payment method events context * Add tests for setDefaultPaymentMethods * Optimize the availablePaymentMethods state data Store only the "name" attribute for now. * Get list of payment methods from the registry instead of the store We are using this hook to get some React elements in the payment method object. So, we are getting the raw data directly from the registry instead of the store. * Fix payment state not loading on the Checkout edit page * Handle checkout edit page case * Fix infinite loop error on C&C Blocks * Include @wordpress/redux-routine in transformIgnorePatterns jest config Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
2022-08-22 13:56:44 +00:00
describe( 'Testing Payment Methods work correctly with saved cards turned on', () => {
beforeEach( () => {
act( () => {
registerMockPaymentMethods( true );
fetchMock.mockResponse( ( req ) => {
if ( req.url.match( /wc\/store\/v1\/cart/ ) ) {
return Promise.resolve( JSON.stringify( previewCart ) );
}
return Promise.resolve( '' );
} );
// need to clear the store resolution state between tests.
Refactor registration of payment methods and update unit tests for payment data store (https://github.com/woocommerce/woocommerce-blocks/pull/6669) * Mock getCartTotals * Change test to use data store instead of context * Move payment method context test to data store selectors * Change description of test suite * Bump commit to trigger tests * Fix path in test * update package lock * Set correct state payment method reducer tests/use correct actions * Get saved payment methods from store not context * Mock stores and update tests to allow switching payment methods * Update tests to get onSubmit from checkoutEventsContext * Remove cartTotalsLoaded check from payment method initialize check * Make PaymentMethods test wait until payments initialized * initialize payment method data store when cart is loaded * Remove unneeded actions and add initializePaymentMethodDataStore * Remove check for cart totals loaded in checkPaymentMethods * Remove updateAvilablePaymentMethods from registry * Remove unneeded mock * Remove unused import * Rename imports to fix eslint errors * Remove unused imports * Remove return false from checkPaymentMethods * Remove unnecessary setPaymentMethodsInitialized call * Add todo comment to track refactoring opportunity * Remove savedpayment methods from payment method context and rename it * Rename payment method data context to payment method events context * Add tests for setDefaultPaymentMethods * Optimize the availablePaymentMethods state data Store only the "name" attribute for now. * Get list of payment methods from the registry instead of the store We are using this hook to get some React elements in the payment method object. So, we are getting the raw data directly from the registry instead of the store. * Fix payment state not loading on the Checkout edit page * Handle checkout edit page case * Fix infinite loop error on C&C Blocks * Include @wordpress/redux-routine in transformIgnorePatterns jest config Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
2022-08-22 13:56:44 +00:00
wpDataFunctions.dispatch( storeKey ).invalidateResolutionForStore();
wpDataFunctions
.dispatch( storeKey )
.receiveCart( defaultCartState.cartData );
} );
} );
afterEach( async () => {
act( () => {
resetMockPaymentMethods();
fetchMock.resetMocks();
} );
} );
it( 'resets saved payment method data after starting and closing an express payment method', async () => {
const TriggerActiveExpressPaymentMethod = () => {
const { activePaymentMethod, paymentMethodData } =
Refactor registration of payment methods and update unit tests for payment data store (https://github.com/woocommerce/woocommerce-blocks/pull/6669) * Mock getCartTotals * Change test to use data store instead of context * Move payment method context test to data store selectors * Change description of test suite * Bump commit to trigger tests * Fix path in test * update package lock * Set correct state payment method reducer tests/use correct actions * Get saved payment methods from store not context * Mock stores and update tests to allow switching payment methods * Update tests to get onSubmit from checkoutEventsContext * Remove cartTotalsLoaded check from payment method initialize check * Make PaymentMethods test wait until payments initialized * initialize payment method data store when cart is loaded * Remove unneeded actions and add initializePaymentMethodDataStore * Remove check for cart totals loaded in checkPaymentMethods * Remove updateAvilablePaymentMethods from registry * Remove unneeded mock * Remove unused import * Rename imports to fix eslint errors * Remove unused imports * Remove return false from checkPaymentMethods * Remove unnecessary setPaymentMethodsInitialized call * Add todo comment to track refactoring opportunity * Remove savedpayment methods from payment method context and rename it * Rename payment method data context to payment method events context * Add tests for setDefaultPaymentMethods * Optimize the availablePaymentMethods state data Store only the "name" attribute for now. * Get list of payment methods from the registry instead of the store We are using this hook to get some React elements in the payment method object. So, we are getting the raw data directly from the registry instead of the store. * Fix payment state not loading on the Checkout edit page * Handle checkout edit page case * Fix infinite loop error on C&C Blocks * Include @wordpress/redux-routine in transformIgnorePatterns jest config Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
2022-08-22 13:56:44 +00:00
wpDataFunctions.useSelect( ( select ) => {
const store = select( PAYMENT_METHOD_DATA_STORE_KEY );
return {
activePaymentMethod: store.getActivePaymentMethod(),
paymentMethodData: store.getPaymentMethodData(),
};
} );
return (
<>
<CheckoutExpressPayment />
<SavedPaymentMethodOptions onChange={ () => void null } />
{ 'Active Payment Method: ' + activePaymentMethod }
{ paymentMethodData[ 'wc-credit-card-payment-token' ] && (
<span>credit-card token</span>
) }
</>
);
};
const TestComponent = () => {
Refactor registration of payment methods and update unit tests for payment data store (https://github.com/woocommerce/woocommerce-blocks/pull/6669) * Mock getCartTotals * Change test to use data store instead of context * Move payment method context test to data store selectors * Change description of test suite * Bump commit to trigger tests * Fix path in test * update package lock * Set correct state payment method reducer tests/use correct actions * Get saved payment methods from store not context * Mock stores and update tests to allow switching payment methods * Update tests to get onSubmit from checkoutEventsContext * Remove cartTotalsLoaded check from payment method initialize check * Make PaymentMethods test wait until payments initialized * initialize payment method data store when cart is loaded * Remove unneeded actions and add initializePaymentMethodDataStore * Remove check for cart totals loaded in checkPaymentMethods * Remove updateAvilablePaymentMethods from registry * Remove unneeded mock * Remove unused import * Rename imports to fix eslint errors * Remove unused imports * Remove return false from checkPaymentMethods * Remove unnecessary setPaymentMethodsInitialized call * Add todo comment to track refactoring opportunity * Remove savedpayment methods from payment method context and rename it * Rename payment method data context to payment method events context * Add tests for setDefaultPaymentMethods * Optimize the availablePaymentMethods state data Store only the "name" attribute for now. * Get list of payment methods from the registry instead of the store We are using this hook to get some React elements in the payment method object. So, we are getting the raw data directly from the registry instead of the store. * Fix payment state not loading on the Checkout edit page * Handle checkout edit page case * Fix infinite loop error on C&C Blocks * Include @wordpress/redux-routine in transformIgnorePatterns jest config Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
2022-08-22 13:56:44 +00:00
return <TriggerActiveExpressPaymentMethod />;
};
render( <TestComponent /> );
// Should initialize by default the default saved payment method.
await waitFor( () => {
const activePaymentMethod = screen.queryByText(
/Active Payment Method: credit-card/
);
expect( activePaymentMethod ).not.toBeNull();
} );
await waitFor( () => {
const creditCardToken = screen.queryByText( /credit-card token/ );
expect( creditCardToken ).not.toBeNull();
} );
// Express payment method clicked.
userEvent.click(
screen.getByText( 'express-payment express payment method' )
);
await waitFor( () => {
const activePaymentMethod = screen.queryByText(
/Active Payment Method: express-payment/
);
expect( activePaymentMethod ).not.toBeNull();
} );
await waitFor( () => {
const creditCardToken = screen.queryByText( /credit-card token/ );
expect( creditCardToken ).toBeNull();
} );
// Express payment method closed.
userEvent.click(
screen.getByText( 'express-payment express payment method close' )
);
await waitFor( () => {
const activePaymentMethod = screen.queryByText(
/Active Payment Method: credit-card/
);
expect( activePaymentMethod ).not.toBeNull();
} );
await waitFor( () => {
const creditCardToken = screen.queryByText( /credit-card token/ );
expect( creditCardToken ).not.toBeNull();
} );
} );
} );