-
Notifications
You must be signed in to change notification settings - Fork 389
feat(clerk-js): Pass locale to Stripe elements #6885
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
base: main
Are you sure you want to change the base?
Conversation
🦋 Changeset detectedLatest commit: a7f50d0 The changes in this PR will be included in the next version bump. This PR includes changesets to release 19 packages
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 |
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughCore update flow now merges and initializes internal options before emitting props. Sandbox builds an intermediate options object (maps localization to a resource and sets sessionStorage) then calls a single Clerk.__unstable__updateProps. Adds useLocalization hook and tests to normalize and pass locale to Stripe Elements. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor App
participant Sandbox as sandbox/app.ts
participant Clerk as Clerk Core
note over Sandbox: Construct intermediate options\n(map localization -> resource, set sessionStorage)
App->>Sandbox: user updates settings
Sandbox->>Clerk: __unstable__updateProps({ options })
activate Clerk
Clerk->>Clerk: mergedOptions = merge(this.#options, _props.options)
Clerk->>Clerk: processedOptions = this.#initOptions(mergedOptions)
Clerk->>Clerk: this.#options = processedOptions
Clerk-->>Sandbox: updated props emitted
deactivate Clerk
sequenceDiagram
autonumber
actor User
participant App as React App
participant Hook as useLocalization
participant Clerk as OptionsContext
participant Stripe as Stripe Elements
note over Hook: read localization, default to "en", normalize to 2-letter code
User->>App: open checkout
App->>Hook: request locale
Hook->>Clerk: read options.localization
Clerk-->>Hook: localization value (or undefined)
Hook->>App: locale (e.g., "en", "fr")
App->>Stripe: mount Elements { locale }
Stripe-->>App: Elements container (data-locale)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests
Comment |
packages/clerk-js/src/core/clerk.ts
Outdated
const mergedOptions = { ...this.#options, ..._props.options }; | ||
|
||
// Update the Clerk instance's internal options | ||
this.#options = mergedOptions; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm unsure if there is a reason we weren't doing this previously, but without it clerk.__internal_getOption('localization')
would not work after __unstable__updateProps
was called in the sandbox
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (5)
packages/shared/src/react/commerce.tsx (2)
65-78
: Locale normalization is too naive; consider BCP‑47 and Stripe’s supported setSplitting on '-' loses region variants (e.g., pt-BR, fr-CA, zh-HK, zh-TW, es-419) and ignores 'auto'. This can degrade UX vs Stripe’s localized formats. Recommend:
- Accept 'auto' if Clerk opts for auto-detection.
- Preserve known region-specific locales Stripe supports; otherwise fall back to the base language or 'en'.
- Optionally log at debug level instead of fully swallowing errors for easier diagnosis.
I can provide a small helper (toStripeLocale) to normalize and validate against a supported set while keeping your current default of 'en'.
238-239
: Removeas any
and pass a typed Stripe locale
as any
hides type issues and may pass unsupported values to Stripe. Use Stripe’s locale type and a small normalizer:
- Import the type and return a properly typed value from your hook, then pass it directly.
Example minimal change (keeps current behavior while improving typing):
-import type { Stripe, StripeElements } from '@stripe/stripe-js'; +import type { Stripe, StripeElements, StripeElementsOptions } from '@stripe/stripe-js'; … -const useLocalization = () => { +const useLocalization = (): StripeElementsOptions['locale'] => { const clerk = useClerk(); let locale = 'en'; try { const localization = clerk.__internal_getOption('localization'); locale = localization?.locale || 'en'; } catch (_) {} // Normalize locale to 2-letter language code for Stripe compatibility - const normalizedLocale = locale.split('-')[0]; - return normalizedLocale; + const normalizedLocale = locale.split('-')[0] as StripeElementsOptions['locale']; + return normalizedLocale; }; … - locale: locale as any, + locale,This eliminates
any
and keeps your current two‑letter normalization. We can iterate later to preserve regional variants if desired.packages/clerk-js/sandbox/app.ts (1)
240-254
: Good consolidation; add a small guard to avoid no‑op updatesBuilding
options
once and calling__unstable__updateProps({ options })
is cleaner. To reduce needless work, consider bailing if the computedoptions.localization
hasn’t changed fromClerk.__internal_getOption('localization')
. Also, ifl[input.value]
is ever undefined, fall back tol.enUS
to stay robust.packages/shared/src/react/__tests__/commerce.test.tsx (2)
64-67
: SWR mock may not match both call sites; make it key‑awareThe same
useSWR
mock services two different keys: 'clerk-stripe-sdk' (returns{ loadStripe }
) and 'stripe-sdk' (returns the Stripe instance). The current mock always returns{ data: { loadStripe: fn } }
, which can hide shape issues. Consider:-jest.mock('swr', () => ({ - __esModule: true, - default: () => ({ data: { loadStripe: jest.fn().mockResolvedValue({}) } }), -})); +jest.mock('swr', () => ({ + __esModule: true, + default: (key: any, fetcher?: any) => { + if (key === 'clerk-stripe-sdk') { + return { data: { loadStripe: jest.fn().mockResolvedValue({}) } }; + } + if (key?.key === 'stripe-sdk') { + // Simulate resolved Stripe instance + return { data: {} }; + } + return { data: undefined }; + }, +}));This keeps the tests closer to runtime behavior and avoids accidental truthy mismatches.
85-321
: Reset mocks between tests to avoid cross‑test leakage
mockGetOption
is reconfigured in multiple tests without reset, which can cause order-dependent behavior. Add:beforeEach(() => { jest.clearAllMocks(); });Optionally also
jest.resetModules()
if module state matters.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (4)
packages/clerk-js/sandbox/app.ts
(1 hunks)packages/clerk-js/src/core/clerk.ts
(1 hunks)packages/shared/src/react/__tests__/commerce.test.tsx
(1 hunks)packages/shared/src/react/commerce.tsx
(3 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{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/sandbox/app.ts
packages/clerk-js/src/core/clerk.ts
packages/shared/src/react/commerce.tsx
packages/shared/src/react/__tests__/commerce.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/sandbox/app.ts
packages/clerk-js/src/core/clerk.ts
packages/shared/src/react/commerce.tsx
packages/shared/src/react/__tests__/commerce.test.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/sandbox/app.ts
packages/clerk-js/src/core/clerk.ts
packages/shared/src/react/commerce.tsx
packages/shared/src/react/__tests__/commerce.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/sandbox/app.ts
packages/clerk-js/src/core/clerk.ts
packages/shared/src/react/commerce.tsx
packages/shared/src/react/__tests__/commerce.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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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/sandbox/app.ts
packages/clerk-js/src/core/clerk.ts
packages/shared/src/react/commerce.tsx
packages/shared/src/react/__tests__/commerce.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/sandbox/app.ts
packages/clerk-js/src/core/clerk.ts
packages/shared/src/react/commerce.tsx
packages/shared/src/react/__tests__/commerce.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/shared/src/react/commerce.tsx
packages/shared/src/react/__tests__/commerce.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/shared/src/react/commerce.tsx
packages/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.test.tsx
🧬 Code graph analysis (1)
packages/clerk-js/sandbox/app.ts (1)
packages/clerk-js/src/core/clerk.ts (1)
Clerk
(199-2952)
⏰ 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). (2)
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (6)
packages/shared/src/react/__tests__/commerce.test.tsx (6)
10-24
: Stripe mock: narrow option typing for clarityUse a minimal options type instead of
any
to satisfy TS test guidelines and catch regressions.-jest.mock('../stripe-react', () => ({ - Elements: ({ children, options }: { children: React.ReactNode; options: any }) => ( +jest.mock('../stripe-react', () => ({ + Elements: ({ children, options }: { children: React.ReactNode; options: { locale?: string } }) => (
65-84
: Module mocks: add lightweight reset to avoid cross-test leakageMocks are reconfigured per test but never reset. Add a global reset to keep tests independent and easier to extend.
describe('PaymentElement Localization', () => { + afterEach(() => { + jest.clearAllMocks(); + mockGetOption.mockReset(); + });
162-182
: Helper stability: reset and set mock in one placeGuard against residual implementations when
renderWithLocale
is called multiple times.-const renderWithLocale = (locale: string) => { - // Mock the __internal_getOption to return the expected localization - mockGetOption.mockImplementation(key => { +const renderWithLocale = (locale: string) => { + mockGetOption.mockReset(); + mockGetOption.mockImplementation(key => { if (key === 'localization') { return { locale }; } return undefined; });
214-225
: Iterating locales: prefer table-driven tests for better failure output
it.each
yields clearer diffs on failures and runs cases independently.-it('should handle different locale values', () => { - const locales = ['en', 'es', 'fr', 'de', 'it']; - locales.forEach(locale => { - const { unmount } = renderWithLocale(locale); - const elements = screen.getByTestId('stripe-elements'); - expect(elements).toHaveAttribute('data-locale', locale); - unmount(); - }); -}); +it.each(['en', 'es', 'fr', 'de', 'it'])( + 'should pass locale "%s" through unchanged', + locale => { + const { unmount } = renderWithLocale(locale); + expect(screen.getByTestId('stripe-elements')).toHaveAttribute('data-locale', locale); + unmount(); + }, +);
191-212
: Add a negative/invalid-locale caseStrengthen defaults with an invalid locale (e.g.,
xx-YY
) asserting fallback toen
.it('should default to "en" when no locale is provided', () => { // ... expect(elements).toHaveAttribute('data-locale', 'en'); }); +it('should fallback to "en" for invalid/unknown locales', () => { + mockGetOption.mockReset(); + mockGetOption.mockImplementation(key => (key === 'localization' ? { locale: 'xx-YY' } : undefined)); + render( + <OptionsContext.Provider value={{ localization: { locale: 'xx-YY' } as any }}> + <__experimental_PaymentElementProvider checkout={mockCheckout}> + <__experimental_PaymentElement fallback={<div>Loading...</div>} /> + </__experimental_PaymentElementProvider> + </OptionsContext.Provider>, + ); + expect(screen.getByTestId('stripe-elements')).toHaveAttribute('data-locale', 'en'); +});Also applies to: 227-250
87-160
: Consider a typed factory for checkout fixturesThis large inline object is repeated across commerce tests in this area. A small factory (with override support) improves reuse and narrows types.
// test/utils/factories.ts export function createCheckout(overrides: Partial<Checkout> = {}): Checkout { return { id: 'checkout_123', // ...defaults as above... ...overrides, }; }Then import and use
createCheckout()
here to keep tests focused.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
packages/shared/src/react/__tests__/commerce.test.tsx
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.test.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/shared/src/react/__tests__/commerce.test.tsx
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/shared/src/react/__tests__/commerce.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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.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/shared/src/react/__tests__/commerce.test.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). (4)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
packages/shared/src/react/__tests__/commerce.test.tsx (3)
191-212
: Default locale case looks goodAsserting fallback to
en
when no localization is present is appropriate and aligns with the intended behavior.
252-283
: ClerkProvider-style resource case is validNormalizing
fr-FR
tofr
here is reasonable since Stripe acceptsfr
and there’s no region-specific variant for France to preserve.
171-173
: Annotateoptions
with the actual context value type
I couldn’t locate anOptionsContextValue
export inpackages/shared/src/react
. Please verify the correct context-value type exported by yourcontexts
module, import it, and then declare:const options: Partial<YourContextType> = { localization: { locale }, };
it('should normalize full locale strings to 2-letter codes for Stripe', () => { | ||
const testCases = [ | ||
{ input: 'en-US', expected: 'en' }, | ||
{ input: 'fr-FR', expected: 'fr' }, | ||
{ input: 'es-ES', expected: 'es' }, | ||
{ input: 'de-DE', expected: 'de' }, | ||
{ input: 'it-IT', expected: 'it' }, | ||
{ input: 'pt-BR', expected: 'pt' }, | ||
]; | ||
|
||
testCases.forEach(({ input, expected }) => { | ||
// Mock the __internal_getOption to return the expected localization | ||
mockGetOption.mockImplementation(key => { | ||
if (key === 'localization') { | ||
return { locale: input }; | ||
} | ||
return undefined; | ||
}); | ||
|
||
const options = { | ||
localization: { locale: input }, | ||
}; | ||
|
||
const { unmount } = render( | ||
<OptionsContext.Provider value={options}> | ||
<__experimental_PaymentElementProvider checkout={mockCheckout}> | ||
<__experimental_PaymentElement fallback={<div>Loading...</div>} /> | ||
</__experimental_PaymentElementProvider> | ||
</OptionsContext.Provider>, | ||
); | ||
|
||
const elements = screen.getByTestId('stripe-elements'); | ||
expect(elements).toHaveAttribute('data-locale', expected); | ||
|
||
unmount(); | ||
}); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion | 🟠 Major
🧩 Analysis chain
Normalization may drop supported regional locales (risk of worse UX)
The test enforces unconditional 2-letter normalization (e.g., pt-BR
→ pt
). Stripe Elements accepts several region codes (e.g., pt-BR
, fr-CA
, en-GB
, es-419
, zh-TW
). Collapsing these to base language can degrade translations.
Recommendation:
- Preserve locale if it’s in Stripe’s supported list (including region variants).
- Otherwise, try base language; finally fall back to
en
.
Update tests to reflect preservation where applicable.
- const testCases = [
- { input: 'en-US', expected: 'en' },
- { input: 'fr-FR', expected: 'fr' },
- { input: 'es-ES', expected: 'es' },
- { input: 'de-DE', expected: 'de' },
- { input: 'it-IT', expected: 'it' },
- { input: 'pt-BR', expected: 'pt' },
- ];
+ const testCases = [
+ // preserve known region variants supported by Stripe
+ { input: 'en-GB', expected: 'en-GB' },
+ { input: 'fr-CA', expected: 'fr-CA' },
+ { input: 'es-419', expected: 'es-419' },
+ { input: 'pt-BR', expected: 'pt-BR' },
+ { input: 'zh-TW', expected: 'zh-TW' },
+ // collapse to base where region is not needed/supported
+ { input: 'en-US', expected: 'en' },
+ { input: 'fr-FR', expected: 'fr' },
+ { input: 'es-ES', expected: 'es' },
+ { input: 'de-DE', expected: 'de' },
+ { input: 'it-IT', expected: 'it' },
+ ];
To confirm Stripe’s current supported locales list:
🌐 Web query:
What locales are supported by Stripe Elements as of September 2025? Does it accept region codes like en-GB, fr-CA, es-419, pt-BR, zh-TW?
💡 Result:
Short answer: Yes — Stripe Elements accepts specific locale codes (including region variants). The Stripe docs list the supported locales and include en-GB, fr-CA, es-419 and pt-BR. For Chinese they use region/script variants (zh-Hans for Simplified, zh-Hant-TW for Traditional Taiwan, zh-Hant-HK for Hong Kong). If you pass a locale not directly supported Stripe will pick a reasonable fallback (e.g., fr-BE → fr-FR). [1][2]
Sources:
- Stripe Elements / Connect embedded components supported locales (includes en-GB, fr-CA, es-419, pt-BR, zh-Hant-TW, zh-Hans). [1]
- Stripe Checkout / locale support & fallback behavior. [2]
Preserve Stripe-supported locale variants in normalization/tests
The current logic collapses every locale (e.g., pt-BR
, en-GB
) to its two-letter base, but Stripe Elements accepts region/script variants (en-GB, fr-CA, es-419, pt-BR, zh-Hans, zh-Hant-TW, zh-Hant-HK) [1][2]. Update the normalization (and corresponding tests) to:
- Use the full locale if it’s in Stripe’s supported list
- Otherwise fall back to the two-letter language tag
- Finally fall back to
en
as a last resort
Example test update:
- const testCases = [
- { input: 'en-US', expected: 'en' },
- { input: 'fr-FR', expected: 'fr' },
- // …
- ];
+ const testCases = [
+ // preserve supported region/script variants
+ { input: 'en-GB', expected: 'en-GB' },
+ { input: 'fr-CA', expected: 'fr-CA' },
+ { input: 'es-419', expected: 'es-419' },
+ { input: 'pt-BR', expected: 'pt-BR' },
+ { input: 'zh-Hans', expected: 'zh-Hans' },
+ { input: 'zh-Hant-TW', expected: 'zh-Hant-TW' },
+ // collapse unsupported variants
+ { input: 'en-US', expected: 'en' },
+ { input: 'fr-FR', expected: 'fr' },
+ { input: 'es-ES', expected: 'es' },
+ // …
+ ];
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
it('should normalize full locale strings to 2-letter codes for Stripe', () => { | |
const testCases = [ | |
{ input: 'en-US', expected: 'en' }, | |
{ input: 'fr-FR', expected: 'fr' }, | |
{ input: 'es-ES', expected: 'es' }, | |
{ input: 'de-DE', expected: 'de' }, | |
{ input: 'it-IT', expected: 'it' }, | |
{ input: 'pt-BR', expected: 'pt' }, | |
]; | |
testCases.forEach(({ input, expected }) => { | |
// Mock the __internal_getOption to return the expected localization | |
mockGetOption.mockImplementation(key => { | |
if (key === 'localization') { | |
return { locale: input }; | |
} | |
return undefined; | |
}); | |
const options = { | |
localization: { locale: input }, | |
}; | |
const { unmount } = render( | |
<OptionsContext.Provider value={options}> | |
<__experimental_PaymentElementProvider checkout={mockCheckout}> | |
<__experimental_PaymentElement fallback={<div>Loading...</div>} /> | |
</__experimental_PaymentElementProvider> | |
</OptionsContext.Provider>, | |
); | |
const elements = screen.getByTestId('stripe-elements'); | |
expect(elements).toHaveAttribute('data-locale', expected); | |
unmount(); | |
}); | |
}); | |
it('should normalize full locale strings to 2-letter codes for Stripe', () => { | |
- const testCases = [ | |
- { input: 'en-US', expected: 'en' }, | |
- { input: 'fr-FR', expected: 'fr' }, | |
- { input: 'es-ES', expected: 'es' }, | |
- { input: 'de-DE', expected: 'de' }, | |
- { input: 'it-IT', expected: 'it' }, | |
- { input: 'pt-BR', expected: 'pt' }, | |
const testCases = [ | |
// preserve Stripe-supported region/script variants | |
{ input: 'en-GB', expected: 'en-GB' }, | |
{ input: 'fr-CA', expected: 'fr-CA' }, | |
{ input: 'es-419', expected: 'es-419' }, | |
{ input: 'pt-BR', expected: 'pt-BR' }, | |
{ input: 'zh-Hans', expected: 'zh-Hans' }, | |
{ input: 'zh-Hant-TW', expected: 'zh-Hant-TW' }, | |
// fall back to 2-letter language code for unsupported variants | |
{ input: 'en-US', expected: 'en' }, | |
{ input: 'fr-FR', expected: 'fr' }, | |
{ input: 'es-ES', expected: 'es' }, | |
{ input: 'de-DE', expected: 'de' }, | |
{ input: 'it-IT', expected: 'it' }, | |
]; | |
testCases.forEach(({ input, expected }) => { | |
// Mock the __internal_getOption to return the expected localization | |
mockGetOption.mockImplementation(key => { | |
if (key === 'localization') { | |
return { locale: input }; | |
} | |
return undefined; | |
}); | |
const options = { | |
localization: { locale: input }, | |
}; | |
const { unmount } = render( | |
<OptionsContext.Provider value={options}> | |
<__experimental_PaymentElementProvider checkout={mockCheckout}> | |
<__experimental_PaymentElement fallback={<div>Loading...</div>} /> | |
</__experimental_PaymentElementProvider> | |
</OptionsContext.Provider>, | |
); | |
const elements = screen.getByTestId('stripe-elements'); | |
expect(elements).toHaveAttribute('data-locale', expected); | |
unmount(); | |
}); | |
}); |
🤖 Prompt for AI Agents
In packages/shared/src/react/__tests__/commerce.test.tsx around lines 285-321,
the test and underlying normalization collapse every locale to its 2-letter base
but Stripe supports specific region/script variants; change the normalization
logic to first check against Stripe's supported-locale list and return the full
incoming locale if present, otherwise fall back to the two-letter language
subtag, and as a final fallback return 'en'; update these tests to include
supported variants (e.g., 'en-GB', 'pt-BR', 'es-419', 'zh-Hans', 'zh-Hant-TW')
asserting the full variant is preserved, keep existing cases asserting
base-language fallback for unsupported variants, and ensure the mockGetOption
and OptionsContext values reflect the exact locale strings used in each case.
Description
Passes current standardized localization value to Stripe Elements.
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
New Features
Refactor
Tests
Chores