diff --git a/assets/js/base/context/providers/cart-checkout/cart-events/test/index.tsx b/assets/js/base/context/providers/cart-checkout/cart-events/test/index.tsx new file mode 100644 index 00000000000..cd74494123c --- /dev/null +++ b/assets/js/base/context/providers/cart-checkout/cart-events/test/index.tsx @@ -0,0 +1,45 @@ +/** + * External dependencies + */ +import { useCartEventsContext } from '@woocommerce/base-context'; +import { useEffect } from '@wordpress/element'; +import { render, screen, waitFor } from '@testing-library/react'; + +/** + * Internal dependencies + */ +import { CartEventsProvider } from '../index'; +import Block from '../../../../../../blocks/cart/inner-blocks/proceed-to-checkout-block/block'; + +describe( 'CartEventsProvider', () => { + it( 'allows observers to unsubscribe', async () => { + const mockObserver = jest.fn(); + const MockObserverComponent = () => { + const { onProceedToCheckout } = useCartEventsContext(); + useEffect( () => { + const unsubscribe = onProceedToCheckout( () => { + mockObserver(); + unsubscribe(); + } ); + }, [ onProceedToCheckout ] ); + return
Mock observer
; + }; + + render( + +
+ + +
+
+ ); + expect( screen.getByText( 'Mock observer' ) ).toBeInTheDocument(); + const button = screen.getByText( 'Proceed to Checkout' ); + // Click twice. The observer should unsubscribe after the first click. + button.click(); + button.click(); + await waitFor( () => { + expect( mockObserver ).toHaveBeenCalledTimes( 1 ); + } ); + } ); +} );