Commit a10f346ab2d for woocommerce
commit a10f346ab2d5c0d25b7ab22d3c23cab674303bfc
Author: Miguel Gasca <miguel.gasca@automattic.com>
Date: Thu Nov 19 12:07:43 2026 +0100
Fix rejected coupons blocking Place Order in the Checkout block (#68622)
When the Store API rejected a coupon (already applied, invalid, expired),
the coupon form wrote the message to the validation store under a
`coupon` key. Place Order does not submit while that store holds any
entry, so the shopper could not check out until they edited or closed
the coupon field, and the checkout moved focus to the coupon input as if
it were an invalid address field.
`applyCoupon` now rejects with the message the shopper sees. The coupon
form keeps the message in local state and renders it through
`ValidationInputError`, which gains an optional `id` prop. The message
clears when the shopper edits the code, when a later apply succeeds, or
when the checkout is validated, including by a payment method's own
Place Order button calling `validate()`. Editing the code also clears a
`coupon` validation error that an extension may still set.
diff --git a/docs/block-development/extensible-blocks/cart-and-checkout-blocks/checkout-payment-methods/checkout-flow-and-events.md b/docs/block-development/extensible-blocks/cart-and-checkout-blocks/checkout-payment-methods/checkout-flow-and-events.md
index 5bf19a8b75d..1b2955cdf03 100644
--- a/docs/block-development/extensible-blocks/cart-and-checkout-blocks/checkout-payment-methods/checkout-flow-and-events.md
+++ b/docs/block-development/extensible-blocks/cart-and-checkout-blocks/checkout-payment-methods/checkout-flow-and-events.md
@@ -230,7 +230,7 @@ Observers registered to this event emitter will receive nothing as an argument.
- `errorMessage`: This will be added as an error notice on the checkout context.
- `context`: The notice context to show `errorMessage` in, for example `noticeContexts.PAYMENTS`. Defaults to `wc/checkout`.
- `validationErrors`: This will be set as inline validation errors on checkout fields. If your observer wants to trigger validation errors it can use the following shape for the errors:
- - This is an object where keys are the property names the validation error is for (that correspond to a checkout field, eg `country` or `coupon`) and values are the error message describing the validation problem.
+ - This is an object where each key is the validation error id of a checkout field (for example `billing_email` or `shipping_postcode`) and each value is an object with a `message` string and a `hidden` boolean, such as `{ message: 'Enter a valid postcode.', hidden: false }`. If any value has a different shape, the whole `validationErrors` object is ignored. A key that matches no field still blocks Place Order without showing anything, so also return an `errorMessage`.
This event is emitted when the checkout status is `BEFORE_PROCESSING` (which happens at validation time, after the checkout form submission is triggered by the user - or Express Payment methods).
@@ -335,7 +335,7 @@ When an error response is returned by an observer, the payment method context st
- `message`: The string provided here will be set as an error notice.
- `messageContext`: If provided, this will target the given area for the error notice (this is where `noticeContexts` mentioned earlier come in to play). Otherwise, the notice will be added to the `noticeContexts.PAYMENTS` area.
- `validationErrors`: This will be set as inline validation errors on checkout fields. If your observer wants to trigger validation errors it can use the following shape for the errors:
- - This is an object where keys are the property names the validation error is for (that correspond to a checkout field, eg `country` or `coupon`) and values are the error message describing the validation problem.
+ - This is an object where each key is the validation error id of a checkout field (for example `billing_email` or `shipping_postcode`) and each value is an object with a `message` string and a `hidden` boolean, such as `{ message: 'Enter a valid postcode.', hidden: false }`. If any value has a different shape, the whole `validationErrors` object is ignored. A key that matches no field still blocks Place Order without showing anything, so also return a `message`.
If the response object doesn't match any of the above conditions, then the fallback is to set the payment status as `SUCCESS`.
diff --git a/plugins/woocommerce/changelog/fix-42074-coupon-error-blocks-checkout b/plugins/woocommerce/changelog/fix-42074-coupon-error-blocks-checkout
new file mode 100644
index 00000000000..5f6a75278d4
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-42074-coupon-error-blocks-checkout
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+Keep a rejected coupon from blocking Place Order in the Checkout block.
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/totals/coupon/index.tsx b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/totals/coupon/index.tsx
index 6021f0568a3..4aaf95fae28 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/totals/coupon/index.tsx
+++ b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/totals/coupon/index.tsx
@@ -3,18 +3,18 @@
*/
import clsx from 'clsx';
import { __ } from '@wordpress/i18n';
-import { useState, useRef } from '@wordpress/element';
+import { useEffect, useRef, useState } from '@wordpress/element';
import Button from '@woocommerce/base-components/button';
import LoadingMask from '@woocommerce/base-components/loading-mask';
import {
- ValidatedTextInput,
+ TextInput,
ValidationInputError,
- ValidatedTextInputHandle,
Panel,
Spinner,
} from '@woocommerce/blocks-components';
-import { useSelect } from '@wordpress/data';
+import { useDispatch } from '@wordpress/data';
import { validationStore } from '@woocommerce/block-data';
+import { checkoutEvents } from '@woocommerce/blocks-checkout-events';
import type { MouseEvent, MouseEventHandler } from 'react';
/**
@@ -36,9 +36,10 @@ export interface TotalsCouponProps {
*/
displayCouponForm?: boolean;
/**
- * Submit handler
+ * Submit handler. Resolves when the coupon was applied. Rejects with an
+ * Error whose message is shown under the input when it was not.
*/
- onSubmit?: ( couponValue: string ) => Promise< boolean > | undefined;
+ onSubmit?: ( couponValue: string ) => Promise< unknown > | undefined;
}
export const TotalsCoupon = ( {
@@ -48,37 +49,52 @@ export const TotalsCoupon = ( {
displayCouponForm = false,
}: TotalsCouponProps ): JSX.Element => {
const [ couponValue, setCouponValue ] = useState( '' );
+ const [ errorMessage, setErrorMessage ] = useState( '' );
const [ isCouponFormVisible, setIsCouponFormVisible ] =
useState( displayCouponForm );
const textInputId = `wc-block-components-totals-coupon__input-${ instanceId }`;
- const { validationErrorId } = useSelect(
- ( select ) => {
- const store = select( validationStore );
- return {
- validationErrorId: store.getValidationErrorId( instanceId ),
- };
- },
- [ instanceId ]
+ const errorId = `wc-block-components-totals-coupon__error-${ instanceId }`;
+ const inputRef = useRef< HTMLInputElement >( null );
+ const { clearValidationError } = useDispatch( validationStore );
+ const hasError = errorMessage !== '';
+
+ useEffect( () => {
+ if ( isCouponFormVisible ) {
+ inputRef.current?.focus();
+ }
+ }, [ isCouponFormVisible ] );
+
+ // The message only concerns this form. Drop it whenever the checkout is
+ // validated, so a checkout error never reads as a coupon problem and the
+ // scroll to the first error never lands on the coupon input.
+ useEffect(
+ () =>
+ checkoutEvents.onCheckoutValidation( () => {
+ setErrorMessage( '' );
+ return true;
+ } ),
+ []
);
- const inputRef = useRef< ValidatedTextInputHandle >( null );
const handleCouponSubmit: MouseEventHandler< HTMLButtonElement > = (
e: MouseEvent< HTMLButtonElement >
) => {
e.preventDefault();
- if ( typeof onSubmit !== 'undefined' ) {
- void onSubmit( couponValue )?.then( ( result ) => {
- if ( result ) {
- setCouponValue( '' );
- setIsCouponFormVisible( false );
- } else if ( inputRef.current?.focus ) {
- inputRef.current.focus();
- }
- } );
- } else {
+ if ( typeof onSubmit === 'undefined' ) {
setCouponValue( '' );
setIsCouponFormVisible( true );
+ return;
}
+ setErrorMessage( '' );
+ void onSubmit( couponValue )
+ ?.then( () => {
+ setCouponValue( '' );
+ setIsCouponFormVisible( false );
+ } )
+ .catch( ( error: Error ) => {
+ setErrorMessage( error.message );
+ inputRef.current?.focus();
+ } );
};
return (
@@ -100,19 +116,24 @@ export const TotalsCoupon = ( {
className="wc-block-components-totals-coupon__form"
id="wc-block-components-totals-coupon__form"
>
- <ValidatedTextInput
+ <TextInput
id={ textInputId }
- errorId="coupon"
- className="wc-block-components-totals-coupon__input"
+ className={ clsx(
+ 'wc-block-components-totals-coupon__input',
+ { 'has-error': hasError }
+ ) }
label={ __( 'Enter code', 'woocommerce' ) }
value={ couponValue }
- ariaDescribedBy={ validationErrorId || '' }
+ ariaDescribedBy={ hasError ? errorId : undefined }
+ aria-invalid={ hasError }
onChange={ ( newCouponValue ) => {
+ setErrorMessage( '' );
+ // An extension can still set a `coupon` validation error,
+ // which blocks checkout but shows nowhere. Editing the
+ // code clears it, as it did before.
+ void clearValidationError( 'coupon' );
setCouponValue( newCouponValue );
} }
- focusOnMount={ true }
- validateOnMount={ false }
- showError={ false }
ref={ inputRef }
/>
<Button
@@ -131,10 +152,12 @@ export const TotalsCoupon = ( {
{ __( 'Apply', 'woocommerce' ) }
</Button>
</form>
- <ValidationInputError
- propertyName="coupon"
- elementId={ instanceId }
- />
+ { hasError && (
+ <ValidationInputError
+ errorMessage={ errorMessage }
+ id={ errorId }
+ />
+ ) }
</div>
</LoadingMask>
</Panel>
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/totals/coupon/stories/index.stories.tsx b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/totals/coupon/stories/index.stories.tsx
index e57a2bb222c..18098061d65 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/totals/coupon/stories/index.stories.tsx
+++ b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/totals/coupon/stories/index.stories.tsx
@@ -4,8 +4,6 @@
import { useArgs } from 'storybook/preview-api';
import type { StoryFn, Meta } from '@storybook/react-webpack5';
import { INTERACTION_TIMEOUT } from '@woocommerce/storybook-controls';
-import { useDispatch } from '@wordpress/data';
-import { validationStore } from '@woocommerce/block-data';
/**
* Internal dependencies
@@ -20,18 +18,13 @@ export default {
},
} as Meta< TotalsCouponProps >;
-const INVALID_COUPON_ERROR = {
- hidden: false,
- message: 'Invalid coupon code',
-};
-
const Template: StoryFn< TotalsCouponProps > = ( args ) => {
const [ {}, setArgs ] = useArgs();
const onSubmit = ( code: string ) => {
args.onSubmit?.( code );
setArgs( { isLoading: true } );
- return new Promise( ( resolve ) => {
+ return new Promise< boolean >( ( resolve ) => {
setTimeout( () => {
setArgs( { isLoading: false } );
resolve( true );
@@ -50,16 +43,15 @@ LoadingState.args = {
isLoading: true,
};
+// Type a code and click Apply to see the error the server would return.
export const ErrorState: StoryFn< TotalsCouponProps > = ( args ) => {
- const { setValidationErrors } = useDispatch( validationStore );
-
- setValidationErrors( { coupon: INVALID_COUPON_ERROR } );
-
- return <TotalsCoupon { ...args } />;
+ const onSubmit = () => Promise.reject( new Error( 'Invalid coupon code' ) );
+
+ return (
+ <TotalsCoupon
+ { ...args }
+ displayCouponForm={ true }
+ onSubmit={ onSubmit }
+ />
+ );
};
-
-ErrorState.decorators = [
- ( StoryComponent ) => {
- return <StoryComponent />;
- },
-];
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/totals/coupon/test/index.tsx b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/totals/coupon/test/index.tsx
index 944ee5095ae..2d31b347c3d 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/totals/coupon/test/index.tsx
+++ b/plugins/woocommerce/client/blocks/assets/js/base/components/cart-checkout/totals/coupon/test/index.tsx
@@ -3,61 +3,35 @@
*/
import { act, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import { dispatch } from '@wordpress/data';
+import { dispatch, select } from '@wordpress/data';
import { validationStore } from '@woocommerce/block-data';
+import {
+ checkoutEventsEmitter,
+ CHECKOUT_EVENTS,
+} from '@woocommerce/blocks-checkout-events';
/**
* Internal dependencies
*/
import { TotalsCoupon } from '..';
-describe( 'TotalsCoupon', () => {
- beforeEach( () => {
- // Clear validation errors before each test
- const { clearValidationErrors } = dispatch( validationStore );
- act( () => {
- clearValidationErrors();
- } );
- } );
- afterAll( () => {
- // Clear validation errors after all tests to ensure no data store state is leaked.
- const { clearValidationErrors } = dispatch( validationStore );
- act( () => {
- clearValidationErrors();
- } );
- } );
+const ERROR_ID = 'wc-block-components-totals-coupon__error-coupon';
- it( "Shows a validation error when one is in the wc/store/validation data store and doesn't show one when there isn't", async () => {
- const user = userEvent.setup();
- const { rerender } = render( <TotalsCoupon instanceId={ 'coupon' } /> );
-
- const openCouponFormButton = screen.getByText( 'Add coupons' );
- expect( openCouponFormButton ).toBeInTheDocument();
- await act( async () => {
- await user.click( openCouponFormButton );
- } );
- expect(
- screen.queryByText( 'Invalid coupon code' )
- ).not.toBeInTheDocument();
-
- const { setValidationErrors } = dispatch( validationStore );
- act( () => {
- setValidationErrors( {
- coupon: {
- hidden: false,
- message: 'Invalid coupon code',
- },
+describe( 'TotalsCoupon', () => {
+ describe( 'Rejected coupons', () => {
+ afterEach( () => {
+ act( () => {
+ dispatch( validationStore ).clearValidationErrors();
} );
} );
- rerender( <TotalsCoupon instanceId={ 'coupon' } /> );
- expect( screen.getByText( 'Invalid coupon code' ) ).toBeInTheDocument();
- } );
-
- describe( 'API Response Scenarios', () => {
- it( 'handles successful coupon application', async () => {
+ it( 'shows the message from a rejected submit', async () => {
const user = userEvent.setup();
- const mockOnSubmit = jest.fn().mockResolvedValue( true );
+ const message =
+ 'Coupon code "5fixedcheckout" has already been applied.';
+ const mockOnSubmit = jest
+ .fn()
+ .mockRejectedValue( new Error( message ) );
render(
<TotalsCoupon
@@ -67,35 +41,45 @@ describe( 'TotalsCoupon', () => {
/>
);
- // Find the coupon input and apply button
const couponInput = screen.getByLabelText( 'Enter code' );
- const applyButton = screen.getByRole( 'button', { name: 'Apply' } );
- // Enter a coupon code
await act( async () => {
await user.type( couponInput, '5fixedcheckout' );
} );
-
- // Submit the coupon
await act( async () => {
- await user.click( applyButton );
+ await user.click(
+ screen.getByRole( 'button', { name: 'Apply' } )
+ );
} );
- // Verify the API was called with the correct coupon code
expect( mockOnSubmit ).toHaveBeenCalledWith( '5fixedcheckout' );
+ expect( await screen.findByRole( 'alert' ) ).toHaveTextContent(
+ message
+ );
- // Wait for the success flow to complete
- await waitFor( () => {
- // Input should be cleared on success and form should be hidden
- expect(
- screen.queryByLabelText( 'Enter code' )
- ).not.toBeInTheDocument();
- } );
+ // The input points at the message so assistive tech can read it.
+ expect( document.getElementById( ERROR_ID ) ).toHaveTextContent(
+ message
+ );
+ expect( couponInput ).toHaveAttribute( 'aria-invalid', 'true' );
+ expect( couponInput ).toHaveAttribute(
+ 'aria-describedby',
+ ERROR_ID
+ );
+ expect(
+ couponInput.closest( '.wc-block-components-text-input' )
+ ).toHaveClass( 'has-error' );
+
+ // The shopper can correct the code without retyping it.
+ expect( couponInput ).toHaveValue( '5fixedcheckout' );
+ expect( couponInput ).toHaveFocus();
} );
- it( 'handles coupon application failure with focus on input', async () => {
+ it( 'clears the message when the code is edited', async () => {
const user = userEvent.setup();
- const mockOnSubmit = jest.fn().mockResolvedValue( false );
+ const mockOnSubmit = jest
+ .fn()
+ .mockRejectedValue( new Error( 'Invalid coupon code' ) );
render(
<TotalsCoupon
@@ -106,45 +90,57 @@ describe( 'TotalsCoupon', () => {
);
const couponInput = screen.getByLabelText( 'Enter code' );
- const applyButton = screen.getByRole( 'button', { name: 'Apply' } );
- // Enter an invalid coupon code
await act( async () => {
- await user.type( couponInput, 'invalid_coupon' );
+ await user.type( couponInput, 'bad' );
} );
-
- // Submit the coupon
await act( async () => {
- await user.click( applyButton );
+ await user.click(
+ screen.getByRole( 'button', { name: 'Apply' } )
+ );
} );
+ expect( await screen.findByRole( 'alert' ) ).toBeInTheDocument();
- // Verify the API was called
- expect( mockOnSubmit ).toHaveBeenCalledWith( 'invalid_coupon' );
-
- // Wait for the failure flow to complete
- await waitFor( () => {
- // Input should retain its value on failure
- expect( couponInput ).toHaveValue( 'invalid_coupon' );
+ await act( async () => {
+ await user.type( couponInput, '2' );
} );
- // Input should be focused for retry
- expect( couponInput ).toHaveFocus();
+ expect( screen.queryByRole( 'alert' ) ).not.toBeInTheDocument();
+ expect( couponInput ).toHaveAttribute( 'aria-invalid', 'false' );
+ expect( couponInput ).not.toHaveAttribute( 'aria-describedby' );
} );
- it( 'handles onSubmit that returns Promise that rejects', async () => {
+ it( 'clears a coupon validation error set by an extension when the code is edited', async () => {
const user = userEvent.setup();
-
- // Create a proper promise-returning mock that catches the rejection
- const mockOnSubmit = jest.fn().mockImplementation( () => {
- return Promise.reject( {
- code: 'woocommerce_rest_cart_coupon_error',
- message: 'Coupon "expired_coupon" has already expired.',
- } ).catch( () => {
- // Handle the rejection internally to prevent unhandled promise
- return false;
+ act( () => {
+ dispatch( validationStore ).setValidationErrors( {
+ coupon: {
+ message: 'Log in to use this coupon.',
+ hidden: false,
+ },
} );
} );
+ render(
+ <TotalsCoupon instanceId="coupon" displayCouponForm={ true } />
+ );
+
+ await act( async () => {
+ await user.type( screen.getByLabelText( 'Enter code' ), 'a' );
+ } );
+
+ expect(
+ select( validationStore ).getValidationError( 'coupon' )
+ ).toBeUndefined();
+ } );
+
+ it( 'clears the message when a later submit succeeds', async () => {
+ const user = userEvent.setup();
+ const mockOnSubmit = jest
+ .fn()
+ .mockRejectedValueOnce( new Error( 'Invalid coupon code' ) )
+ .mockResolvedValueOnce( true );
+
render(
<TotalsCoupon
instanceId="coupon"
@@ -153,41 +149,35 @@ describe( 'TotalsCoupon', () => {
/>
);
- const couponInput = screen.getByLabelText( 'Enter code' );
- const applyButton = screen.getByRole( 'button', { name: 'Apply' } );
-
- // Enter an expired coupon code
await act( async () => {
- await user.type( couponInput, 'expired_coupon' );
+ await user.type( screen.getByLabelText( 'Enter code' ), 'bad' );
} );
-
- // Submit the coupon
await act( async () => {
- await user.click( applyButton );
+ await user.click(
+ screen.getByRole( 'button', { name: 'Apply' } )
+ );
} );
+ expect( await screen.findByRole( 'alert' ) ).toBeInTheDocument();
- // Verify the API was called
- expect( mockOnSubmit ).toHaveBeenCalledWith( 'expired_coupon' );
+ await act( async () => {
+ await user.click(
+ screen.getByRole( 'button', { name: 'Apply' } )
+ );
+ } );
- // Component should handle the case gracefully
- expect( couponInput ).toHaveValue( 'expired_coupon' );
+ await waitFor( () => {
+ expect(
+ screen.queryByLabelText( 'Enter code' )
+ ).not.toBeInTheDocument();
+ } );
+ expect( screen.queryByRole( 'alert' ) ).not.toBeInTheDocument();
} );
- it( 'handles duplicate coupon application', async () => {
+ it( 'clears the message when the checkout is validated', async () => {
const user = userEvent.setup();
- const mockOnSubmit = jest.fn().mockResolvedValue( false );
-
- // Set up validation error as would happen from the API response
- const { setValidationErrors } = dispatch( validationStore );
- act( () => {
- setValidationErrors( {
- coupon: {
- hidden: false,
- message:
- 'Coupon code "5fixedcheckout" has already been applied.',
- },
- } );
- } );
+ const mockOnSubmit = jest
+ .fn()
+ .mockRejectedValue( new Error( 'Invalid coupon code' ) );
render(
<TotalsCoupon
@@ -197,48 +187,35 @@ describe( 'TotalsCoupon', () => {
/>
);
- // Verify error message is displayed
- expect(
- screen.getByText(
- 'Coupon code "5fixedcheckout" has already been applied.'
- )
- ).toBeInTheDocument();
-
- const couponInput = screen.getByLabelText( 'Enter code' );
- const applyButton = screen.getByRole( 'button', { name: 'Apply' } );
-
- // Try to apply the same coupon again
await act( async () => {
- await user.type( couponInput, '5fixedcheckout' );
+ await user.type( screen.getByLabelText( 'Enter code' ), 'bad' );
} );
-
await act( async () => {
- await user.click( applyButton );
+ await user.click(
+ screen.getByRole( 'button', { name: 'Apply' } )
+ );
} );
+ expect( await screen.findByRole( 'alert' ) ).toBeInTheDocument();
- expect( mockOnSubmit ).toHaveBeenCalledWith( '5fixedcheckout' );
-
- // Input should retain value and stay focused on failure
- await waitFor( () => {
- expect( couponInput ).toHaveValue( '5fixedcheckout' );
+ // Place Order and a payment method's own button both validate the
+ // checkout through this event.
+ let responses: unknown[] = [];
+ await act( async () => {
+ responses = await checkoutEventsEmitter.emit(
+ CHECKOUT_EVENTS.CHECKOUT_VALIDATION
+ );
} );
- expect( couponInput ).toHaveFocus();
- } );
- it( 'handles usage limit exceeded error', async () => {
- const mockOnSubmit = jest.fn().mockResolvedValue( false );
+ expect( screen.queryByRole( 'alert' ) ).not.toBeInTheDocument();
+ // The observer never fails validation.
+ expect( responses ).toEqual( [] );
+ } );
- // Set up validation error for usage limit
- const { setValidationErrors } = dispatch( validationStore );
- act( () => {
- setValidationErrors( {
- coupon: {
- hidden: false,
- message:
- 'Usage limit for coupon "limited_coupon" has been reached.',
- },
- } );
- } );
+ it( 'keeps the message when the panel is closed and opened again', async () => {
+ const user = userEvent.setup();
+ const mockOnSubmit = jest
+ .fn()
+ .mockRejectedValue( new Error( 'Invalid coupon code' ) );
render(
<TotalsCoupon
@@ -248,27 +225,36 @@ describe( 'TotalsCoupon', () => {
/>
);
- // Verify error message is displayed
- expect(
- screen.getByText(
- 'Usage limit for coupon "limited_coupon" has been reached.'
- )
- ).toBeInTheDocument();
- } );
+ await act( async () => {
+ await user.type( screen.getByLabelText( 'Enter code' ), 'bad' );
+ } );
+ await act( async () => {
+ await user.click(
+ screen.getByRole( 'button', { name: 'Apply' } )
+ );
+ } );
+ expect( await screen.findByRole( 'alert' ) ).toBeInTheDocument();
- it( 'handles coupons disabled error', async () => {
- const mockOnSubmit = jest.fn().mockResolvedValue( false );
+ await act( async () => {
+ await user.click( screen.getByText( 'Add coupons' ) );
+ } );
+ expect(
+ screen.queryByLabelText( 'Enter code' )
+ ).not.toBeInTheDocument();
- // Set up validation error for disabled coupons
- const { setValidationErrors } = dispatch( validationStore );
- act( () => {
- setValidationErrors( {
- coupon: {
- hidden: false,
- message: 'Coupons are disabled.',
- },
- } );
+ await act( async () => {
+ await user.click( screen.getByText( 'Add coupons' ) );
} );
+ expect( await screen.findByRole( 'alert' ) ).toHaveTextContent(
+ 'Invalid coupon code'
+ );
+ } );
+ } );
+
+ describe( 'API Response Scenarios', () => {
+ it( 'handles successful coupon application', async () => {
+ const user = userEvent.setup();
+ const mockOnSubmit = jest.fn().mockResolvedValue( true );
render(
<TotalsCoupon
@@ -278,10 +264,24 @@ describe( 'TotalsCoupon', () => {
/>
);
- // Verify error message is displayed
- expect(
- screen.getByText( 'Coupons are disabled.' )
- ).toBeInTheDocument();
+ const couponInput = screen.getByLabelText( 'Enter code' );
+ const applyButton = screen.getByRole( 'button', { name: 'Apply' } );
+
+ await act( async () => {
+ await user.type( couponInput, '5fixedcheckout' );
+ } );
+
+ await act( async () => {
+ await user.click( applyButton );
+ } );
+
+ expect( mockOnSubmit ).toHaveBeenCalledWith( '5fixedcheckout' );
+
+ await waitFor( () => {
+ expect(
+ screen.queryByLabelText( 'Enter code' )
+ ).not.toBeInTheDocument();
+ } );
} );
} );
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/context/hooks/cart/test/use-store-cart-coupons.tsx b/plugins/woocommerce/client/blocks/assets/js/base/context/hooks/cart/test/use-store-cart-coupons.tsx
index 3fbbc471ecc..198c70dc016 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/context/hooks/cart/test/use-store-cart-coupons.tsx
+++ b/plugins/woocommerce/client/blocks/assets/js/base/context/hooks/cart/test/use-store-cart-coupons.tsx
@@ -2,6 +2,9 @@
* External dependencies
*/
import { renderHook, act } from '@testing-library/react';
+import { select } from '@wordpress/data';
+import apiFetch from '@wordpress/api-fetch';
+import { validationStore } from '@woocommerce/block-data';
import { server, http, HttpResponse } from '@woocommerce/test-utils/msw';
/**
@@ -34,6 +37,12 @@ describe( 'useStoreCartCoupons hook API integration', () => {
beforeEach( () => {
// Reset any request handlers that were added in individual tests
server.resetHandlers();
+ // The middleware that adds these to apiFetch is not loaded under Jest,
+ // and processHeadersOnFetch logs console.error when they are missing.
+ // @ts-expect-error setNonce exists but is not typed
+ apiFetch.setNonce = jest.fn();
+ // @ts-expect-error setCartHash exists but is not typed
+ apiFetch.setCartHash = jest.fn();
} );
describe( 'applyCoupon API calls', () => {
@@ -77,6 +86,7 @@ describe( 'useStoreCartCoupons hook API integration', () => {
shipping_address: {},
billing_address: {},
},
+ headers: {},
},
],
} );
@@ -135,7 +145,9 @@ describe( 'useStoreCartCoupons hook API integration', () => {
capturedRequests.push( requestData );
return HttpResponse.json( {
- responses: [ { status: 200, body: {} } ],
+ responses: [
+ { status: 200, body: {}, headers: {} },
+ ],
} );
}
)
@@ -184,7 +196,7 @@ describe( 'useStoreCartCoupons hook API integration', () => {
} );
} );
- it( 'handles API errors correctly without breaking', async () => {
+ it( 'rejects with the server message and leaves the validation store empty', async () => {
// Track the request details
let capturedRequest: CapturedRequest = {
url: '',
@@ -224,11 +236,15 @@ describe( 'useStoreCartCoupons hook API integration', () => {
useStoreCartCoupons( 'wc/checkout' )
);
- // Apply invalid coupon - should not throw error
+ // The failure is reported to the caller, not to the validation store.
await act( async () => {
- const success = await result.current.applyCoupon( 'INVALID' );
- expect( success ).toBe( false );
+ await expect(
+ result.current.applyCoupon( 'INVALID' )
+ ).rejects.toThrow( 'Coupon "INVALID" does not exist!' );
} );
+ expect( select( validationStore ).hasValidationErrors() ).toBe(
+ false
+ );
// Verify the API call was still made
expect( capturedRequest ).not.toBeNull();
@@ -261,7 +277,9 @@ describe( 'useStoreCartCoupons hook API integration', () => {
};
return HttpResponse.json( {
- responses: [ { status: 200, body: {} } ],
+ responses: [
+ { status: 200, body: {}, headers: {} },
+ ],
} );
}
)
@@ -305,7 +323,9 @@ describe( 'useStoreCartCoupons hook API integration', () => {
};
return HttpResponse.json( {
- responses: [ { status: 200, body: {} } ],
+ responses: [
+ { status: 200, body: {}, headers: {} },
+ ],
} );
}
)
@@ -356,7 +376,9 @@ describe( 'useStoreCartCoupons hook API integration', () => {
};
return HttpResponse.json( {
- responses: [ { status: 200, body: {} } ],
+ responses: [
+ { status: 200, body: {}, headers: {} },
+ ],
} );
}
)
@@ -403,7 +425,9 @@ describe( 'useStoreCartCoupons hook API integration', () => {
};
return HttpResponse.json( {
- responses: [ { status: 200, body: {} } ],
+ responses: [
+ { status: 200, body: {}, headers: {} },
+ ],
} );
}
)
@@ -444,7 +468,9 @@ describe( 'useStoreCartCoupons hook API integration', () => {
capturedRequests.push( requestData );
return HttpResponse.json( {
- responses: [ { status: 200, body: {} } ],
+ responses: [
+ { status: 200, body: {}, headers: {} },
+ ],
} );
}
)
@@ -504,7 +530,9 @@ describe( 'useStoreCartCoupons hook API integration', () => {
};
return HttpResponse.json( {
- responses: [ { status: 200, body: {} } ],
+ responses: [
+ { status: 200, body: {}, headers: {} },
+ ],
} );
}
)
@@ -543,7 +571,9 @@ describe( 'useStoreCartCoupons hook API integration', () => {
};
return HttpResponse.json( {
- responses: [ { status: 200, body: {} } ],
+ responses: [
+ { status: 200, body: {}, headers: {} },
+ ],
} );
}
)
@@ -590,12 +620,17 @@ describe( 'useStoreCartCoupons hook API integration', () => {
useStoreCartCoupons( 'wc/checkout' )
);
- // Should not throw error even on network failure
+ // A network failure is reported the same way as a rejected coupon.
await act( async () => {
- const success =
- await result.current.applyCoupon( 'NETWORK_FAIL' );
- expect( success ).toBe( false );
+ await expect(
+ result.current.applyCoupon( 'NETWORK_FAIL' )
+ ).rejects.toThrow(
+ 'Could not get a valid response from the server.'
+ );
} );
+ expect( select( validationStore ).hasValidationErrors() ).toBe(
+ false
+ );
expect( capturedRequest ).not.toBeNull();
expect( capturedRequest.url ).toContain( '/wc/store/v1/batch' );
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/context/hooks/cart/use-store-cart-coupons.ts b/plugins/woocommerce/client/blocks/assets/js/base/context/hooks/cart/use-store-cart-coupons.ts
index 82cc3fda4c4..8fa7de16376 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/context/hooks/cart/use-store-cart-coupons.ts
+++ b/plugins/woocommerce/client/blocks/assets/js/base/context/hooks/cart/use-store-cart-coupons.ts
@@ -4,11 +4,7 @@
import { __, sprintf } from '@wordpress/i18n';
import { dispatch, useDispatch, useSelect } from '@wordpress/data';
import { useCallback } from '@wordpress/element';
-import {
- cartStore,
- validationStore,
- checkoutStore,
-} from '@woocommerce/block-data';
+import { cartStore, checkoutStore } from '@woocommerce/block-data';
import { decodeEntities } from '@wordpress/html-entities';
import type {
StoreCartCoupon,
@@ -24,6 +20,12 @@ import { useStoreCart } from './use-store-cart';
/**
* This is a custom hook for loading the Store API /cart/coupons endpoint and an
* action for adding a coupon _to_ the cart.
+ *
+ * applyCoupon resolves true once the coupon is applied. When the Store API
+ * rejects the coupon it rejects with an Error whose message is ready to show to
+ * the shopper. The failure is feedback for the coupon form only, so it is never
+ * written to the validation store, which would block checkout.
+ *
* See also: https://github.com/woocommerce/woocommerce-gutenberg-products-block/tree/trunk/src/RestApi/StoreApi
*/
export const useStoreCartCoupons = ( context = '' ): StoreCartCoupon => {
@@ -79,17 +81,12 @@ export const useStoreCartCoupons = ( context = '' ): StoreCartCoupon => {
}
);
}
- return Promise.resolve( true );
+ return true as const;
} )
.catch( ( error ) => {
- const errorMessage = getCouponErrorMessage( error );
- dispatch( validationStore ).setValidationErrors( {
- coupon: {
- message: decodeEntities( errorMessage ),
- hidden: false,
- },
- } );
- return Promise.resolve( false );
+ throw new Error(
+ decodeEntities( getCouponErrorMessage( error ) )
+ );
} );
},
[ applyCoupon, getCouponErrorMessage, context ]
diff --git a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/test/block.tsx b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/test/block.tsx
index a0dc068c150..201412cf9f7 100644
--- a/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/test/block.tsx
+++ b/plugins/woocommerce/client/blocks/assets/js/blocks/checkout/test/block.tsx
@@ -13,6 +13,7 @@ import {
import { allSettings } from '@woocommerce/settings';
import { registerPaymentMethod } from '@woocommerce/blocks-registry';
import { server, http, HttpResponse } from '@woocommerce/test-utils/msw';
+import apiFetch from '@wordpress/api-fetch';
/**
* Internal dependencies
@@ -134,6 +135,13 @@ const CheckoutBlock = () => {
describe( 'Testing Checkout', () => {
beforeEach( () => {
+ // Store API batch responses call these; stub so success mocks do not
+ // trip @wordpress/jest-console's console.error assertion.
+ // @ts-expect-error setNonce exists but is not typed
+ apiFetch.setNonce = jest.fn();
+ // @ts-expect-error setCartHash exists but is not typed
+ apiFetch.setCartHash = jest.fn();
+
// Set up MSW handlers for cart API
server.use(
http.get( '/wc/store/v1/cart', () => {
@@ -144,6 +152,9 @@ describe( 'Testing Checkout', () => {
// need to clear the store resolution state between tests.
dispatch( cartStore ).invalidateResolutionForStore();
dispatch( cartStore ).receiveCart( defaultCartState.cartData );
+ dispatch( checkoutStore ).__internalSetIdle();
+ dispatch( checkoutStore ).__internalSetHasError( false );
+ dispatch( validationStore ).clearValidationErrors();
} );
act( () => {
@@ -578,4 +589,144 @@ describe( 'Testing Checkout', () => {
// Given we're checking for invisible errors here, reaching to the data store is a good option.
expect( select( validationStore ).hasValidationErrors() ).toBe( false );
}, 10000 );
+
+ it( 'Places the order after a coupon fails to apply', async () => {
+ const user = userEvent.setup();
+ const couponError =
+ 'Coupon code "5fixedcheckout" has already been applied.';
+ let checkoutRequests = 0;
+
+ // Reject apply-coupon only. Other batch calls (update-customer after
+ // address edits) must succeed, or Place Order stays disabled while
+ // checkout isCalculating.
+ server.use(
+ http.post(
+ '/wc/store/v1/batch',
+ async ( { request }: { request: Request } ) => {
+ const rawBody = await request.text();
+ const body = JSON.parse( rawBody ) as {
+ requests?: unknown[];
+ };
+ const requests = body.requests ?? [];
+
+ if ( rawBody.includes( 'apply-coupon' ) ) {
+ return HttpResponse.json(
+ {
+ code: 'woocommerce_rest_cart_coupon_error',
+ message: couponError,
+ data: {
+ status: 400,
+ details: { cart: couponError },
+ },
+ },
+ { status: 400 }
+ );
+ }
+
+ return HttpResponse.json( {
+ responses: requests.map( () => ( {
+ status: 200,
+ body: previewCart,
+ headers: {},
+ } ) ),
+ } );
+ }
+ ),
+ http.post( '/wc/store/v1/checkout', () => {
+ checkoutRequests++;
+ return HttpResponse.json(
+ {
+ code: 'woocommerce_rest_checkout_test_stop',
+ message: 'Stop here.',
+ data: { status: 400 },
+ },
+ { status: 400 }
+ );
+ } )
+ );
+
+ render( <CheckoutBlock /> );
+
+ await waitFor( () =>
+ expect( screen.getByText( /Place Order/i ) ).toBeVisible()
+ );
+
+ // Apply a coupon the server rejects.
+ await act( async () => {
+ await user.click( screen.getByText( 'Add coupons' ) );
+ } );
+ await act( async () => {
+ await user.type(
+ screen.getByLabelText( 'Enter code' ),
+ '5fixedcheckout'
+ );
+ } );
+ await act( async () => {
+ await user.click( screen.getByRole( 'button', { name: 'Apply' } ) );
+ } );
+ expect( await screen.findByText( couponError ) ).toBeVisible();
+
+ // Fill the rest of the form.
+ const shippingForm = screen.getByRole( 'group', {
+ name: /shipping address/i,
+ } );
+ await act( async () => {
+ await user.selectOptions(
+ within( shippingForm ).getByLabelText( /Country\/Region/i ),
+ 'Spain'
+ );
+ } );
+ await act( async () => {
+ await user.type(
+ screen.getByLabelText( /Email address/i ),
+ 'test@test.com'
+ );
+ await user.type(
+ within( shippingForm ).getByLabelText( /First name/i ),
+ 'John'
+ );
+ await user.type(
+ within( shippingForm ).getByLabelText( /Last name/i ),
+ 'Doe'
+ );
+ await user.type(
+ within( shippingForm ).getByLabelText( 'Address' ),
+ '123 Main St'
+ );
+ await user.type(
+ within( shippingForm ).getByLabelText( /City/i ),
+ 'BCN'
+ );
+ await user.selectOptions(
+ within( shippingForm ).getByLabelText( /Province/i ),
+ 'Barcelona'
+ );
+ await user.click(
+ screen.getByRole( 'checkbox', {
+ name: /terms and conditions/i,
+ } )
+ );
+ } );
+
+ // Address edits debounce a Store API update (~1.5s). Wait until Place
+ // Order is clickable so slower CI runners do not race isCalculating.
+ const placeOrderButton = screen.getByRole( 'button', {
+ name: /Place order/i,
+ } );
+ await waitFor( () => expect( placeOrderButton ).toBeEnabled(), {
+ timeout: 5000,
+ } );
+
+ await act( async () => {
+ await user.click( placeOrderButton );
+ } );
+
+ // The coupon failure must not stop the order from being sent.
+ await waitFor( () => expect( checkoutRequests ).toBe( 1 ), {
+ timeout: 3000,
+ } );
+ expect( select( validationStore ).hasValidationErrors() ).toBe( false );
+ // Placing the order drops the stale coupon message.
+ expect( screen.queryByText( couponError ) ).not.toBeInTheDocument();
+ }, 15000 );
} );
diff --git a/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/validation-input-error/index.tsx b/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/validation-input-error/index.tsx
index 676797c1974..8f99c5b44a6 100644
--- a/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/validation-input-error/index.tsx
+++ b/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/validation-input-error/index.tsx
@@ -14,12 +14,18 @@ export interface ValidationInputErrorProps {
errorMessage?: string;
propertyName?: string;
elementId?: string;
+ /**
+ * Id for the message element. Use it when errorMessage does not come from
+ * the validation store, so an input can still reference the message.
+ */
+ id?: string;
}
export const ValidationInputError = ( {
errorMessage = '',
propertyName = '',
elementId = '',
+ id = '',
}: ValidationInputErrorProps ): JSX.Element | null => {
const { validationError, validationErrorId } = useSelect(
( select ) => {
@@ -43,7 +49,7 @@ export const ValidationInputError = ( {
return (
<div className="wc-block-components-validation-error" role="alert">
- <p id={ validationErrorId }>
+ <p id={ id || validationErrorId }>
<Icon icon={ cautionFilled } />
<span>{ errorMessage }</span>
</p>
diff --git a/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/validation-input-error/stories/index.stories.tsx b/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/validation-input-error/stories/index.stories.tsx
index bd85c2773bf..5de2a44bee8 100644
--- a/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/validation-input-error/stories/index.stories.tsx
+++ b/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/validation-input-error/stories/index.stories.tsx
@@ -14,9 +14,9 @@ export default {
component: ValidationInputError,
argTypes: {
elementId: {
- control: 'null',
+ control: false,
description:
- 'The id of this `ValidationInputError` component. The ID is generated by the `wc/store/validation` data store. [See `getValidationErrorId`](https://github.com/woocommerce/woocommerce-blocks/blob/trunk/docs/third-party-developers/extensibility/data-store/validation.md#getvalidationerrorid-errorid-)',
+ 'The field id used to look up the store-derived message element id. Unused when `id` is set. [See `getValidationErrorId`](https://github.com/woocommerce/woocommerce-blocks/blob/trunk/docs/third-party-developers/extensibility/data-store/validation.md#getvalidationerrorid-errorid-)',
table: {
type: {
summary: 'string',
@@ -30,8 +30,18 @@ export default {
type: { summary: 'string' },
},
},
+ id: {
+ control: 'text',
+ description:
+ 'Id for the message element. Use it when `errorMessage` does not come from the validation store, so an input can still reference the message.',
+ table: {
+ type: {
+ summary: 'string',
+ },
+ },
+ },
propertyName: {
- control: 'null',
+ control: false,
description:
'The name of the entry in the `wc/store/validation` data store to show in this component.',
table: {
diff --git a/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/validation-input-error/test/index.tsx b/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/validation-input-error/test/index.tsx
new file mode 100644
index 00000000000..d2a1dcf6d5f
--- /dev/null
+++ b/plugins/woocommerce/client/blocks/packages/public-api/blocks-components/validation-input-error/test/index.tsx
@@ -0,0 +1,59 @@
+/**
+ * External dependencies
+ */
+import { act, render, screen } from '@testing-library/react';
+import { dispatch } from '@wordpress/data';
+import { validationStore } from '@woocommerce/block-data';
+
+/**
+ * Internal dependencies
+ */
+import { ValidationInputError } from '..';
+
+describe( 'ValidationInputError', () => {
+ afterEach( () => {
+ act( () => {
+ dispatch( validationStore ).clearValidationErrors();
+ } );
+ } );
+
+ it( 'uses the given id for a message passed directly', () => {
+ render(
+ <ValidationInputError
+ errorMessage="Coupon rejected"
+ id="coupon-error"
+ />
+ );
+
+ expect( screen.getByRole( 'alert' ) ).toHaveTextContent(
+ 'Coupon rejected'
+ );
+ expect( document.getElementById( 'coupon-error' ) ).toHaveTextContent(
+ 'Coupon rejected'
+ );
+ } );
+
+ it( 'keeps the store-derived id when no id is given', () => {
+ act( () => {
+ dispatch( validationStore ).setValidationErrors( {
+ email: { message: 'Enter a valid email', hidden: false },
+ } );
+ } );
+
+ render(
+ <ValidationInputError propertyName="email" elementId="email" />
+ );
+
+ expect(
+ document.getElementById( 'validate-error-email' )
+ ).toHaveTextContent( 'Enter a valid email' );
+ } );
+
+ it( 'renders nothing without a message', () => {
+ const { container } = render(
+ <ValidationInputError propertyName="missing" />
+ );
+
+ expect( container ).toBeEmptyDOMElement();
+ } );
+} );
diff --git a/plugins/woocommerce/client/blocks/packages/public-api/types/type-defs/hooks.js b/plugins/woocommerce/client/blocks/packages/public-api/types/type-defs/hooks.js
index 72fc71ff0c1..61a703c2e78 100644
--- a/plugins/woocommerce/client/blocks/packages/public-api/types/type-defs/hooks.js
+++ b/plugins/woocommerce/client/blocks/packages/public-api/types/type-defs/hooks.js
@@ -52,6 +52,9 @@
* API.
* @property {boolean} isLoading True when coupon data is being loaded.
* @property {Function} applyCoupon Callback for applying a coupon by code.
+ * Resolves true once applied; rejects
+ * with an Error whose message can be
+ * shown to the shopper otherwise.
* @property {Function} removeCoupon Callback for removing a coupon by code.
* @property {boolean} isApplyingCoupon True when a coupon is being applied.
* @property {boolean} isRemovingCoupon True when a coupon is being removed.
diff --git a/plugins/woocommerce/client/blocks/packages/public-api/types/type-defs/hooks.ts b/plugins/woocommerce/client/blocks/packages/public-api/types/type-defs/hooks.ts
index 2b999e7b055..6f859402bc5 100644
--- a/plugins/woocommerce/client/blocks/packages/public-api/types/type-defs/hooks.ts
+++ b/plugins/woocommerce/client/blocks/packages/public-api/types/type-defs/hooks.ts
@@ -31,7 +31,11 @@ export interface StoreCartItemQuantity {
export interface StoreCartCoupon {
appliedCoupons: CartResponseCouponItem[];
isLoading: boolean;
- applyCoupon: ( coupon: string ) => Promise< boolean >;
+ /**
+ * Resolves `true` once the coupon is applied. Rejects with an `Error` whose
+ * message can be shown to the shopper when the coupon is not applied.
+ */
+ applyCoupon: ( coupon: string ) => Promise< true >;
removeCoupon: ( coupon: string ) => Promise< boolean >;
isApplyingCoupon: boolean;
isRemovingCoupon: boolean;