Skip to content

Conversation

@panteliselef
Copy link
Member

@panteliselef panteliselef commented Aug 22, 2025

Description

Previously the UI would simply prompt the end-user to start the free trial without selecting a payment method, behind the scenes their default payment method would be chosen. Now the user is prompt to select and the default payment is pre-selected.

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • New Features

    • Payment method selector now appears when you have a saved payment source and either an amount is due today or a free trial is active, improving checkout clarity.
  • Bug Fixes

    • Preserves the selected payment source when nothing is due today (including during free trials) and improves default selection logic.
  • Tests

    • Added tests verifying existing payment sources display and selection behavior during checkout confirmation.
  • Chores

    • Added a patch changeset documenting the release.

@panteliselef panteliselef self-assigned this Aug 22, 2025
@changeset-bot
Copy link

changeset-bot bot commented Aug 22, 2025

🦋 Changeset detected

Latest commit: f677693

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
@clerk/clerk-js Patch
@clerk/chrome-extension Patch
@clerk/clerk-expo Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@vercel
Copy link

vercel bot commented Aug 22, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Aug 22, 2025 4:18pm

@panteliselef panteliselef changed the title fix(clerk-js): Update checkout to list available methods at trial checkout [WIP] fix(clerk-js): Update checkout to list available methods at trial checkout Aug 22, 2025
@pkg-pr-new
Copy link

pkg-pr-new bot commented Aug 22, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@6608

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@6608

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@6608

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@6608

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@6608

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@6608

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@6608

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@6608

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@6608

@clerk/express

npm i https://pkg.pr.new/@clerk/express@6608

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@6608

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@6608

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@6608

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@6608

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@6608

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@6608

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@6608

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@6608

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@6608

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@6608

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@6608

@clerk/types

npm i https://pkg.pr.new/@clerk/types@6608

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@6608

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@6608

commit: f677693

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 22, 2025

📝 Walkthrough

Walkthrough

Updates CheckoutForm to destructure freeTrialEndsAt from checkout and changes payment-method rendering logic: the SegmentedControl now appears when there is ≥1 payment source and (totalDueNow.amount > 0 || freeTrialEndsAt). Replaces isSchedulePayment with shouldDefaultBeUsed = (totalDueNow.amount === 0 || !freeTrialEndsAt). If shouldDefaultBeUsed is true the form renders a Select to pick an existing or new payment source; otherwise it renders a hidden input to preserve the selection. Adds a unit test covering existing payment sources in checkout confirmation and introduces a changeset for a patch release. No public API signatures changed.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes


🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (2)

213-230: Localize the aria-label and refresh the stale comment; keep gating logic readable

  • The aria-label "Payment method source" is a user-facing string and should be localized via useLocalizations.
  • The comment on Line 212 no longer matches the condition (it now also shows when freeTrialEndsAt is set).
  • Minor: inlining the complex condition makes the block harder to scan; consider extracting a boolean for readability.

Apply this diff locally to the changed block:

-      {/* only show if there are payment sources and there is a total due now */}
-      {paymentSources.length > 0 && (totals.totalDueNow.amount > 0 || freeTrialEndsAt) && (
+      {/* show if there are payment sources and (amount due today > 0 OR an active free trial) */}
+      {paymentSources.length > 0 && (totals.totalDueNow.amount > 0 || !!freeTrialEndsAt) && (
         <SegmentedControl.Root
-          aria-label='Payment method source'
+          aria-label={t('commerce.checkout.paymentMethodSourceAriaLabel')}
           value={paymentMethodSource}
           onChange={value => setPaymentMethodSource(value as PaymentMethodSource)}
           size='lg'
           fullWidth
         >

And add the small plumbing to provide t():

- import { Box, Button, Col, descriptors, Flex, Form, localizationKeys, Text } from '../../customizables';
+ import { Box, Button, Col, descriptors, Flex, Form, localizationKeys, Text, useLocalizations } from '../../customizables';
 const CheckoutFormElements = () => {
   const { checkout } = useCheckout();
-  const { id, totals, freeTrialEndsAt } = checkout;
+  const { id, totals, freeTrialEndsAt } = checkout;
+  const { t } = useLocalizations();

Optional readability tweak (if you prefer extracting the condition):

-      {paymentSources.length > 0 && (totals.totalDueNow.amount > 0 || !!freeTrialEndsAt) && (
+      {paymentSources.length > 0 && (totals.totalDueNow.amount > 0 || !!freeTrialEndsAt) && (
         <SegmentedControl.Root

Happy to add a follow-up commit updating/adding the localization key commerce.checkout.paymentMethodSourceAriaLabel if it doesn’t exist yet.


385-416: Add an accessible, localized label to the Select

The Select lacks an accessible name. Add an aria-label (localized) so screen readers can announce the control.

Apply:

           <Select
             elementId='paymentSource'
+            aria-label={t('commerce.checkout.existingPaymentSourceSelectAriaLabel')}
             options={options}
             value={selectedPaymentSource?.id || null}
             onChange={option => {

If you don’t want to introduce a new key, commerce.paymentMethods could be reused, but a dedicated label is clearer for AT users.

🧹 Nitpick comments (2)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (2)

373-376: Variable name reads opposite to behavior; confirm intent and (optionally) align logic with PR goal

  • The name shouldDefaultBeUsed suggests “use the default without prompting,” but the true branch renders the Select, i.e., it prompts. This is confusing.
  • Given the PR’s goal “list available methods at trial checkout,” it seems we want the selector when a free trial is active (freeTrialEndsAt) or when nothing is due today. The current expression uses !freeTrialEndsAt, which hides the selector when a trial is active and there is an amount due today. Please confirm product intent for that edge case.

If the intent is “show selector when amount due today is 0 OR when a free trial is active,” consider this rename and tweak:

-    const shouldDefaultBeUsed = totalDueNow.amount === 0 || !freeTrialEndsAt;
+    const showPaymentSourceSelector = totalDueNow.amount === 0 || !!freeTrialEndsAt;
-        {shouldDefaultBeUsed ? (
+        {showPaymentSourceSelector ? (

If the current behavior is intentional, at minimum please rename for clarity:

-    const shouldDefaultBeUsed = totalDueNow.amount === 0 || !freeTrialEndsAt;
+    const showExistingPaymentSourceSelect = totalDueNow.amount === 0 || !freeTrialEndsAt;

Also consider making the “zero” check inclusive to future-proof against credits producing negative totals:

-    const showPaymentSourceSelector = totalDueNow.amount === 0 || !!freeTrialEndsAt;
+    const showPaymentSourceSelector = totalDueNow.amount <= 0 || !!freeTrialEndsAt;

Also applies to: 384-424


213-230: Please add tests for the new gating scenarios

No tests were added. Add component tests covering:

  • SegmentedControl visibility when: (a) amount > 0 and no trial, (b) amount = 0 and trial active, (c) amount = 0 and no trial.
  • ExistingPaymentSourceForm: Select vs hidden input rendering for the same combinations.
  • Submit label from useSubmitLabel: startFreeTrial vs pay vs subscribe.

I can scaffold tests with your preferred runner (looks like pnpm + react-testing-library).

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 4e15e06 and 823d655.

📒 Files selected for processing (1)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (4 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
packages/clerk-js/src/ui/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/clerk-js-ui.mdc)

packages/clerk-js/src/ui/**/*.{ts,tsx}: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/react.mdc)

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*

⚙️ CodeRabbit configuration file

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (1)

195-196: LGTM: freeTrialEndsAt pulled into scope where it’s needed

Bringing freeTrialEndsAt into CheckoutFormElements is appropriate and supports the new visibility logic below. No concerns here.

@panteliselef
Copy link
Member Author

!snapshot

@clerk-cookie
Copy link
Collaborator

Hey @panteliselef - the snapshot version command generated the following package versions:

Package Version
@clerk/agent-toolkit 0.1.26-snapshot.v20250822161915
@clerk/astro 2.11.7-snapshot.v20250822161915
@clerk/backend 2.9.5-snapshot.v20250822161915
@clerk/chrome-extension 2.5.25-snapshot.v20250822161915
@clerk/clerk-js 5.88.1-snapshot.v20250822161915
@clerk/elements 0.23.58-snapshot.v20250822161915
@clerk/clerk-expo 2.14.24-snapshot.v20250822161915
@clerk/expo-passkeys 0.3.35-snapshot.v20250822161915
@clerk/express 1.7.25-snapshot.v20250822161915
@clerk/fastify 2.4.25-snapshot.v20250822161915
@clerk/nextjs 6.31.5-snapshot.v20250822161915
@clerk/nuxt 1.8.11-snapshot.v20250822161915
@clerk/clerk-react 5.43.2-snapshot.v20250822161915
@clerk/react-router 1.9.5-snapshot.v20250822161915
@clerk/remix 4.11.5-snapshot.v20250822161915
@clerk/shared 3.22.1-snapshot.v20250822161915
@clerk/tanstack-react-start 0.22.5-snapshot.v20250822161915
@clerk/testing 1.11.4-snapshot.v20250822161915
@clerk/vue 1.11.5-snapshot.v20250822161915

Tip: Use the snippet copy button below to quickly install the required packages.
@clerk/agent-toolkit

npm i @clerk/[email protected] --save-exact

@clerk/astro

npm i @clerk/[email protected] --save-exact

@clerk/backend

npm i @clerk/[email protected] --save-exact

@clerk/chrome-extension

npm i @clerk/[email protected] --save-exact

@clerk/clerk-js

npm i @clerk/[email protected] --save-exact

@clerk/elements

npm i @clerk/[email protected] --save-exact

@clerk/clerk-expo

npm i @clerk/[email protected] --save-exact

@clerk/expo-passkeys

npm i @clerk/[email protected] --save-exact

@clerk/express

npm i @clerk/[email protected] --save-exact

@clerk/fastify

npm i @clerk/[email protected] --save-exact

@clerk/nextjs

npm i @clerk/[email protected] --save-exact

@clerk/nuxt

npm i @clerk/[email protected] --save-exact

@clerk/clerk-react

npm i @clerk/[email protected] --save-exact

@clerk/react-router

npm i @clerk/[email protected] --save-exact

@clerk/remix

npm i @clerk/[email protected] --save-exact

@clerk/shared

npm i @clerk/[email protected] --save-exact

@clerk/tanstack-react-start

npm i @clerk/[email protected] --save-exact

@clerk/testing

npm i @clerk/[email protected] --save-exact

@clerk/vue

npm i @clerk/[email protected] --save-exact

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (3)

574-586: Make waitFor callback synchronous; move the click outside.

Avoid using an async callback in waitFor and performing user interactions inside it. Keep waitFor for assertions only, then perform the click afterwards to reduce flakiness.

Apply this diff:

     await waitFor(async () => {
       // Verify checkout title is displayed
       expect(getByRole('heading', { name: 'Checkout' })).toBeVisible();

       // Verify segmented control for payment method source is rendered
-      const paymentMethodsButton = getByText('Payment Methods');
+      const paymentMethodsButton = getByText(/Payment Methods/i);
       expect(paymentMethodsButton).toBeVisible();

-      const addPaymentMethodButton = getByText('Add payment method');
+      const addPaymentMethodButton = getByText(/Add payment method/i);
       expect(addPaymentMethodButton).toBeVisible();

-      await userEvent.click(paymentMethodsButton);
+      // click deferred until after the assertions to keep waitFor callback sync
     });
+
+    await userEvent.click(paymentMethodsButton);

Also applies to: 587-587


589-597: Stabilize text queries to be case-insensitive.

UI copy can change capitalization. Using case-insensitive regex reduces brittleness while keeping assertions meaningful.

Apply this diff:

-      const visaPaymentSource = getByText('visa');
+      const visaPaymentSource = getByText(/visa/i);
       expect(visaPaymentSource).toBeVisible();

-      const last4Digits = getByText('⋯ 4242');
+      const last4Digits = getByText(/⋯\s*4242/);
       expect(last4Digits).toBeVisible();

       // Verify the default badge is shown for the first payment source
-      const defaultBadge = getByText('Default');
+      const defaultBadge = getByText(/default/i);
       expect(defaultBadge).toBeVisible();

599-602: Also assert the input is hidden to capture intent.

Since the code path is expected to render a hidden input, assert the type to lock in the behavior.

Apply this diff:

       // Verify the hidden input contains the correct payment source id
       const hiddenInput = baseElement.querySelector('input[name="payment_source_id"]');
       expect(hiddenInput).toHaveAttribute('value', 'pm_test_visa');
+      expect(hiddenInput).toHaveAttribute('type', 'hidden');
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 823d655 and f677693.

📒 Files selected for processing (3)
  • .changeset/tall-worms-pull.md (1 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (4 hunks)
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .changeset/tall-worms-pull.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
🧰 Additional context used
📓 Path-based instructions (14)
packages/clerk-js/src/ui/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/clerk-js-ui.mdc)

packages/clerk-js/src/ui/**/*.{ts,tsx}: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Unit tests should use Jest or Vitest as the test runner.

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Visual regression testing should be performed for UI components.

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/react.mdc)

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
**/*.test.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/react.mdc)

**/*.test.{jsx,tsx}: Use React Testing Library
Test component behavior, not implementation
Use proper test queries
Implement proper test isolation
Use proper test coverage
Test component interactions
Use proper test data
Implement proper test setup
Use proper test cleanup
Implement proper test assertions
Use proper test structure

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
**/__tests__/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)

**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
**/*

⚙️ CodeRabbit configuration file

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
🧬 Code graph analysis (1)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (1)
packages/clerk-js/src/ui/elements/Drawer.tsx (1)
  • Drawer (555-564)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (2)

469-603: Solid coverage for the trial checkout payment-methods path.

Nice addition validating: segmented control entry point, existing sources rendering, default badge, and preservation of selection via hidden input. This meaningfully exercises the new trial-checkout behavior.

Follow-ups (optional):

  • Add a counterpart test for the “no payment sources” path to verify the control is hidden or behaves as expected.
  • Add a positive-totalDueNow scenario (e.g., amount > 0, no trial) to cover the alternative branch of the new condition.

474-506: Verify PaymentSource types and getPaymentSources payload shape

The ripgrep check returned no matches for the PaymentSource type/interface definitions, getPaymentSources signature, or casing of total_count/totalCount, so it’s unclear whether our mock aligns with the SDK. Please manually confirm:

  • That the SDK exports a PaymentSource type or interface, and note the exact field names (e.g. totalCount vs. total_count).
  • The return type of getPaymentSources in the Clerk JS SDK (ensure our mock’s shape matches exactly).
  • Any other nullable or optional fields the real API may include so our tests don’t diverge from production behavior.

Once verified, update the test to both fail fast on a missing fixture and to match the true payload shape:

-   fixtures.clerk.user?.getPaymentSources.mockResolvedValue({
+   // Fail fast if the user fixture is missing
+   expect(fixtures.clerk.user).toBeDefined();
+   fixtures.clerk.user!.getPaymentSources.mockResolvedValue({
      data: [
        {
          id: 'pm_test_visa',
          last4: '4242',
          paymentMethod: 'card',
          cardType: 'visa',
          isDefault: true,
          isRemovable: true,
          status: 'active',
          walletType: undefined,
          remove: jest.fn(),
          makeDefault: jest.fn(),
          pathRoot: '/',
          reload: jest.fn(),
        },
        {
          id: 'pm_test_mastercard',
          last4: '5555',
          paymentMethod: 'card',
          cardType: 'mastercard',
          isDefault: false,
          isRemovable: true,
          status: 'active',
          walletType: undefined,
          remove: jest.fn(),
          makeDefault: jest.fn(),
          pathRoot: '/',
          reload: jest.fn(),
        },
      ],
-     total_count: 2,
+     // Use the exact property name from the SDK (e.g., totalCount)
+     totalCount: 2,
    });

@panteliselef panteliselef changed the title [WIP] fix(clerk-js): Update checkout to list available methods at trial checkout fix(clerk-js): Update checkout to list available methods at trial checkout Aug 22, 2025
@panteliselef panteliselef merged commit 7168243 into main Aug 22, 2025
42 of 43 checks passed
@panteliselef panteliselef deleted the elef/patch-trial-checkout branch August 22, 2025 18:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants