Skip to content

Reliably wait for cart requests to finish before adding new items to the cart #59373

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 11, 2025

Conversation

straku
Copy link
Contributor

@straku straku commented Jul 2, 2025

Submission Review Guidelines:

Changes proposed in this Pull Request:

Follow up to #58947.

I noticed that the above PR will wait for 5s before and after adding to a cart if there are no pending cart requests. I've changed the util to be more explicit in tracking pending requests. We start tracking them before adding items to cart, and then wait for all requests to finish before moving outside the addToCart util.

Total time before (locally): 19.1s
Total time after (locally): 9.9s

Before After
Screenshot 2025-07-02 at 16 43 07 Screenshot 2025-07-02 at 16 43 37

How to test the changes in this Pull Request:

Code review and green CI 🙏

Testing that has already taken place:

Changelog entry

  • Automatically create a changelog entry from the details below.
  • This Pull Request does not require a changelog entry. (Comment required below)
Changelog Entry Details

Significance

  • Patch
  • Minor
  • Major

Type

  • Fix - Fixes an existing bug
  • Add - Adds functionality
  • Update - Update existing functionality
  • Dev - Development related task
  • Tweak - A minor adjustment to the codebase
  • Performance - Address performance issues
  • Enhancement - Improvement to existing functionality

Message

Changelog Entry Comment

Comment

E2E test tooling change

@straku straku marked this pull request as ready for review July 2, 2025 14:47
@github-actions github-actions bot added focus: e2e tests Issues related to e2e tests plugin: woocommerce Issues related to the WooCommerce Core plugin. labels Jul 2, 2025
@woocommercebot woocommercebot requested review from a team and ralucaStan and removed request for a team July 2, 2025 14:47
Copy link
Contributor

github-actions bot commented Jul 2, 2025

Testing Guidelines

Hi @ralucaStan @woocommerce/rubik,

Apart from reviewing the code changes, please make sure to review the testing instructions (Guide) and verify that relevant tests (E2E, Unit, Integration, etc.) have been added or updated as needed.

Reminder: PR reviewers are required to document testing performed. This includes:

  • 🖼️ Screenshots or screen recordings.
  • 📝 List of functionality tested / steps followed.
  • 🌐 Site details (environment attributes such as hosting type, plugins, theme, store size, store age, and relevant settings).
  • 🔍 Any analysis performed, such as assessing potential impacts on environment attributes and other plugins, conducting performance profiling, or using LLM/AI-based analysis.

⚠️ Within the testing details you provide, please ensure that no sensitive information (such as API keys, passwords, user data, etc.) is included in this public issue.

Copy link
Contributor

coderabbitai bot commented Jul 2, 2025

📝 Walkthrough

Walkthrough

The code refactors the mechanism for waiting on cart-related network requests in Playwright-based end-to-end tests. It replaces a method that awaited a single cart response with a new approach that tracks multiple concurrent cart requests using event listeners and a custom polling utility, updating related methods for improved handling of asynchronous cart actions.

Changes

File(s) Change Summary
plugins/woocommerce/client/blocks/tests/e2e/utils/frontend/frontend-utils.page.ts Replaced single-response cart request waiting with event-driven tracking of multiple concurrent cart requests; added a custom wait function; updated method signatures and logic accordingly.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Code
    participant Utils as FrontendUtils
    participant Page as Playwright Page

    Test->>Utils: addToCart()
    Utils->>Page: Start tracking cart-related requests (event listeners)
    Utils->>Page: Trigger add-to-cart action
    Page-->>Utils: Emit request/response events for /cart, /add_to_cart, /batch
    Utils->>Utils: Track pending cart requests
    Utils->>Utils: waitForCartRequests() (polls until all pending requests complete)
    Utils->>Page: Remove event listeners
    Utils-->>Test: addToCart() completes after all cart requests finish
Loading

Possibly related PRs


📜 Recent review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e2071c0 and f6ff89c.

📒 Files selected for processing (1)
  • plugins/woocommerce/client/blocks/tests/e2e/utils/frontend/frontend-utils.page.ts (3 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ralucaStan
PR: woocommerce/woocommerce#58782
File: plugins/woocommerce/client/blocks/assets/js/base/utils/render-frontend.tsx:0-0
Timestamp: 2025-06-16T16:12:12.148Z
Learning: For WooCommerce checkout blocks, lazy loading was removed in favor of direct imports to prevent sequential "popping" effects during component loading. This approach prioritizes user experience over code splitting, with minimal bundle size impact and improved performance (1.7s to 1.1s speed score improvement). The checkout flow benefits from having all components load together rather than incrementally.
Learnt from: CR
PR: woocommerce/woocommerce#0
File: .cursor/rules/generate-pr-description.mdc:0-0
Timestamp: 2025-06-30T09:26:55.352Z
Learning: Provide clear, step-by-step instructions for how to test the changes in the PR description.
Learnt from: mikejolley
PR: woocommerce/woocommerce#57961
File: plugins/woocommerce/includes/class-wc-session-handler.php:302-333
Timestamp: 2025-06-19T11:58:57.484Z
Learning: In WooCommerce's session handler, the cart merging behavior was revised to always merge guest and user carts when both contain items, rather than having the guest cart take precedence. The migrate_cart_data() method in class-wc-session-handler.php implements this by using array_merge() to combine both carts when neither is empty.
Learnt from: gigitux
PR: woocommerce/woocommerce#58899
File: plugins/woocommerce/tests/e2e-pw/tests/customize-store/assembler/font-picker.spec.js:250-265
Timestamp: 2025-06-17T08:14:15.688Z
Learning: In Playwright E2E tests, page.waitForResponse() should be initialized BEFORE the triggering action (like clicks) to ensure the response is not missed. This is the recommended pattern per Playwright documentation: 
```javascript
const responsePromise = page.waitForResponse('**/api/endpoint');
await triggerAction();
await responsePromise;
```
This pattern prevents missing rapid responses and is the standard approach for reliable E2E tests.
Learnt from: gigitux
PR: woocommerce/woocommerce#58899
File: plugins/woocommerce/tests/e2e-pw/tests/customize-store/assembler/font-picker.spec.js:250-265
Timestamp: 2025-06-17T08:14:15.688Z
Learning: In Playwright E2E tests, page.waitForResponse() should be called BEFORE the triggering action (like clicks) to ensure the response is not missed. This is the recommended pattern per Playwright documentation: const responsePromise = page.waitForResponse(...); await triggerAction(); await responsePromise;
Learnt from: vladolaru
PR: woocommerce/woocommerce#59160
File: plugins/woocommerce/client/admin/client/settings-payments/onboarding/providers/woopayments/steps/payment-methods-selection/index.tsx:0-0
Timestamp: 2025-06-26T14:56:54.917Z
Learning: In WooCommerce payments onboarding components (like plugins/woocommerce/client/admin/client/settings-payments/onboarding/providers/woopayments/steps/payment-methods-selection/index.tsx), when updating local React state based on API calls, the local state should only be updated after the API call succeeds to prevent inconsistent state if the save operation fails. The pattern is to move setPaymentMethodsState calls inside the .then() callback of the API promise.
Learnt from: samueljseay
PR: woocommerce/woocommerce#59051
File: plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/mini-cart-contents/inner-blocks/mini-cart-footer-block/index.tsx:66-70
Timestamp: 2025-06-23T05:47:52.696Z
Learning: For WooCommerce mini-cart blocks in plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/, the standardized conditional pattern for experimental features should be `if ( isExperimentalMiniCartEnabled() ) { blockSettings.save = () => <InnerBlocks.Content />; }` - defaulting to the traditional Save component and only overriding when the experimental feature is enabled.
Learnt from: vladolaru
PR: woocommerce/woocommerce#58784
File: plugins/woocommerce/client/admin/client/settings-payments/onboarding/components/stepper/index.tsx:57-67
Timestamp: 2025-06-20T13:08:44.017Z
Learning: For WooCommerce Payments onboarding step tracking in useEffect hooks, only include the active step in the dependency array, not the context object. The sessionEntryPoint is static throughout the onboarding session and tracking should only fire on actual step navigation, not context changes.
plugins/woocommerce/client/blocks/tests/e2e/utils/frontend/frontend-utils.page.ts (7)
Learnt from: gigitux
PR: woocommerce/woocommerce#58899
File: plugins/woocommerce/tests/e2e-pw/tests/customize-store/assembler/font-picker.spec.js:250-265
Timestamp: 2025-06-17T08:14:15.688Z
Learning: In Playwright E2E tests, page.waitForResponse() should be initialized BEFORE the triggering action (like clicks) to ensure the response is not missed. This is the recommended pattern per Playwright documentation: 
```javascript
const responsePromise = page.waitForResponse('**/api/endpoint');
await triggerAction();
await responsePromise;
```
This pattern prevents missing rapid responses and is the standard approach for reliable E2E tests.
Learnt from: ralucaStan
PR: woocommerce/woocommerce#58782
File: plugins/woocommerce/client/blocks/assets/js/base/utils/render-frontend.tsx:0-0
Timestamp: 2025-06-16T16:12:12.148Z
Learning: For WooCommerce checkout blocks, lazy loading was removed in favor of direct imports to prevent sequential "popping" effects during component loading. This approach prioritizes user experience over code splitting, with minimal bundle size impact and improved performance (1.7s to 1.1s speed score improvement). The checkout flow benefits from having all components load together rather than incrementally.
Learnt from: gigitux
PR: woocommerce/woocommerce#58899
File: plugins/woocommerce/tests/e2e-pw/tests/customize-store/assembler/font-picker.spec.js:250-265
Timestamp: 2025-06-17T08:14:15.688Z
Learning: In Playwright E2E tests, page.waitForResponse() should be called BEFORE the triggering action (like clicks) to ensure the response is not missed. This is the recommended pattern per Playwright documentation: const responsePromise = page.waitForResponse(...); await triggerAction(); await responsePromise;
Learnt from: vladolaru
PR: woocommerce/woocommerce#58784
File: plugins/woocommerce/client/admin/client/settings-payments/onboarding/components/stepper/index.tsx:57-67
Timestamp: 2025-06-20T13:08:44.017Z
Learning: For WooCommerce Payments onboarding step tracking in useEffect hooks, only include the active step in the dependency array, not the context object. The sessionEntryPoint is static throughout the onboarding session and tracking should only fire on actual step navigation, not context changes.
Learnt from: samueljseay
PR: woocommerce/woocommerce#59051
File: plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/mini-cart-contents/inner-blocks/mini-cart-footer-block/index.tsx:66-70
Timestamp: 2025-06-23T05:47:52.696Z
Learning: For WooCommerce mini-cart blocks in plugins/woocommerce/client/blocks/assets/js/blocks/mini-cart/, the standardized conditional pattern for experimental features should be `if ( isExperimentalMiniCartEnabled() ) { blockSettings.save = () => <InnerBlocks.Content />; }` - defaulting to the traditional Save component and only overriding when the experimental feature is enabled.
Learnt from: vladolaru
PR: woocommerce/woocommerce#59160
File: plugins/woocommerce/client/admin/client/settings-payments/onboarding/providers/woopayments/steps/payment-methods-selection/index.tsx:0-0
Timestamp: 2025-06-26T14:56:54.917Z
Learning: In WooCommerce payments onboarding components (like plugins/woocommerce/client/admin/client/settings-payments/onboarding/providers/woopayments/steps/payment-methods-selection/index.tsx), when updating local React state based on API calls, the local state should only be updated after the API call succeeds to prevent inconsistent state if the save operation fails. The pattern is to move setPaymentMethodsState calls inside the .then() callback of the API promise.
Learnt from: vladolaru
PR: woocommerce/woocommerce#58784
File: plugins/woocommerce/client/admin/client/settings-payments/components/other-payment-gateways/other-payment-gateways.tsx:43-50
Timestamp: 2025-06-18T07:56:06.961Z
Learning: In plugins/woocommerce/client/admin/client/settings-payments/components/other-payment-gateways/other-payment-gateways.tsx, the user vladolaru prefers to keep the current setUpPlugin function signature with optional positional context parameter rather than refactoring to an options object or making context required.
⏰ Context from checks skipped due to timeout of 90000ms (18)
  • GitHub Check: Blocks e2e tests 6/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 9/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 3/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 4/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 7/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 5/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 1/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 10/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 5/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 8/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 2/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 3/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Metrics - @woocommerce/plugin-woocommerce [performance]
  • GitHub Check: Core e2e tests 2/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 4/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 1/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 6/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Lint - @woocommerce/block-library
🔇 Additional comments (5)
plugins/woocommerce/client/blocks/tests/e2e/utils/frontend/frontend-utils.page.ts (5)

4-4: LGTM! Import additions support the new request tracking functionality.

The added Request and Response types from Playwright are correctly imported and used in the new tracking implementation.


7-8: LGTM! Simple and effective utility function.

The wait function provides a clean Promise-based delay mechanism used by the polling logic.


10-34: Excellent implementation of Node.js context waitForFunction.

The custom implementation correctly addresses the serialization limitations of Playwright's built-in page.waitForFunction() by running in Node.js context. The polling approach with configurable timeout and interval is well-implemented.

The ESLint disable comment is appropriately used here since startTime is indeed used in the while condition despite the linter's false positive.


56-90: Robust request tracking implementation with proper cleanup.

The new trackCartRequests method provides comprehensive tracking of cart-related requests with several improvements:

  • Tracks multiple request types (/cart, /add_to_cart, /batch) for better coverage
  • Uses a Set for efficient request tracking
  • Properly removes event listeners in the finally block to prevent memory leaks
  • Returns a clean interface for waiting on completion

This approach aligns well with the performance improvements mentioned in the PR objectives (19.1s → 9.9s reduction).


92-109: Perfect implementation following Playwright best practices.

The updated addToCart method correctly implements the pattern from retrieved learnings by starting request tracking BEFORE the triggering action. This ensures no requests are missed and provides reliable synchronization.

The approach properly:

  • Initializes tracking before the click action
  • Waits for all related requests to complete
  • Follows the established pattern for reliable E2E test synchronization
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@straku straku requested a review from a team July 2, 2025 16:31
Copy link
Contributor

@ralucaStan ralucaStan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great effort to make the utility more efficient. I added some comments after observing your changes on the order-confirmation.block_theme.spec.ts test. Let me know what you think.

};

const responseHandler = ( response: Response ) => {
pendingRequests.delete( response.url() );
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This calls delete for any response that comes in; it should only call it for cart related URLs:

if (
				url.includes( '/cart' ) ||
				url.includes( '/add_to_cart' ) ||
				url.includes( '/batch' )
			) {
pendingRequests.delete( response.url() );
			}

we could store the URLs for cart calls in a constant for reusability.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's fine since it won't remove things that are not in the set?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it won't, it was a small improvement to only call pendingRequests.delete for the requests we added

if ( error instanceof Error && error.name !== 'TimeoutError' ) {
throw error;
private trackCartRequests( timeout = 5000 ) {
const pendingRequests = new Set< string >();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is an issue here with using Set, which only holds unique values, because we are only adding http://localhost:8889/wp-json/wc/store/v1/cart/add-item to the Set when a product is added to the cart.

If we add 2 different products, one after the other, the Set will only have 1 value.

We could switch to a counter to keep track of the calls being completed. WDYT?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call, added count tracking

straku and others added 2 commits July 9, 2025 15:27
@straku straku force-pushed the lstr/track-cart-requests branch from d63f6af to e3c24f2 Compare July 9, 2025 13:29
Copy link
Contributor

@ralucaStan ralucaStan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changes look good. I am approving after testing locally again

@straku straku merged commit 4ec314f into trunk Jul 11, 2025
30 checks passed
@straku straku deleted the lstr/track-cart-requests branch July 11, 2025 07:02
@github-actions github-actions bot added this to the 10.1.0 milestone Jul 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
focus: e2e tests Issues related to e2e tests plugin: woocommerce Issues related to the WooCommerce Core plugin.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants