Skip to content

Conversation

panteliselef
Copy link
Member

@panteliselef panteliselef commented Aug 13, 2025

Description

Before

Screen.Recording.2025-08-13.at.7.01.27.PM.mov

After

Screen.Recording.2025-08-13.at.7.01.04.PM.mov

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

  • Bug Fixes

    • Removed UI flicker in the Pricing Table for signed-in users; plan visibility now renders consistently across auth and subscription states.
  • Tests

    • Added tests covering plan visibility for signed-in, signed-out, loading, and various subscription states to prevent regressions.
  • Chores

    • Prepared a patch release to deliver the fix.

@panteliselef panteliselef requested review from aeliox and brkalow August 13, 2025 16:02
@panteliselef panteliselef self-assigned this Aug 13, 2025
Copy link

changeset-bot bot commented Aug 13, 2025

🦋 Changeset detected

Latest commit: 0bb3c52

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

Copy link

vercel bot commented Aug 13, 2025

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

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

Copy link

pkg-pr-new bot commented Aug 13, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 0bb3c52

Copy link
Contributor

coderabbitai bot commented Aug 13, 2025

📝 Walkthrough

Walkthrough

Adds a changeset (.changeset/few-eagles-grab.md) for a patch release of @clerk/clerk-js. PricingTable.tsx now destructures useSubscription as { data: subscription, subscriptionItems } and introduces plansToRender (useMemo) to determine visible plans based on clerk.isSignedIn and subscription; plansToRender is passed to PricingTableMatrix and PricingTableDefault. New unit tests cover plan visibility across signed-in/out and various subscription states; the test file contains duplicated describe blocks with identical tests.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


🪧 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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 33e7a7b and 74ceaf3.

📒 Files selected for processing (2)
  • .changeset/few-eagles-grab.md (1 hunks)
  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (2 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
.changeset/**

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/few-eagles-grab.md
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/PricingTable/PricingTable.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/PricingTable/PricingTable.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/PricingTable/PricingTable.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/PricingTable/PricingTable.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/PricingTable/PricingTable.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/PricingTable/PricingTable.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/PricingTable/PricingTable.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/PricingTable/PricingTable.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/PricingTable/PricingTable.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/PricingTable/PricingTable.tsx
🧬 Code Graph Analysis (1)
packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (4)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (2)
  • useSubscription (63-78)
  • usePlans (80-90)
packages/shared/src/react/hooks/useSubscription.tsx (1)
  • useSubscription (32-65)
packages/shared/src/react/hooks/index.ts (2)
  • useSubscription (15-15)
  • usePlans (14-14)
packages/shared/src/react/hooks/usePlans.tsx (1)
  • usePlans (9-22)
⏰ 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). (26)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Static analysis
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (3)
.changeset/few-eagles-grab.md (1)

1-6: Changeset looks good

Patch release is appropriately scoped and message is concise. No issues.

packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx (2)

83-83: Passing plansToRender to PricingTableMatrix is correct

Routing the memoized list into the matrix variant aligns with the new rendering flow to prevent flickers.


91-91: Passing plansToRender to PricingTableDefault is correct

Consistent with the matrix variant and completes the fix path across both render modes.

const { mode = 'mounted', signInMode = 'redirect' } = usePricingTableContext();
const isCompact = mode === 'modal';
const { subscriptionItems } = useSubscription();
const { data: subscription, subscriptionItems } = useSubscription();
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Destructure loading flag from useSubscription to drive the rendering guard

Expose isLoading to differentiate “loading” vs “no subscription” states as suggested in the plansToRender fix.

-  const { data: subscription, subscriptionItems } = useSubscription();
+  const { data: subscription, isLoading: isSubscriptionLoading, subscriptionItems } = useSubscription();
📝 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.

Suggested change
const { data: subscription, subscriptionItems } = useSubscription();
const { data: subscription, isLoading: isSubscriptionLoading, subscriptionItems } = useSubscription();
🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx around line
15, update the useSubscription destructuring to also extract isLoading (e.g.
const { data: subscription, subscriptionItems, isLoading } = useSubscription())
and use that flag to drive the render guard: return a loading placeholder or
null while isLoading is true, and only treat a falsy subscription as “no
subscription” once isLoading is false; keep the existing subscription existence
checks unchanged for the “no subscription” case.

Comment on lines +19 to +25
const plansToRender = useMemo(() => {
return clerk.isSignedIn
? subscription // All users in billing-enabled applications have a subscription
? plans
: []
: plans;
}, [clerk.isSignedIn, plans, subscription]);
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Fix loading vs null handling to avoid hiding plans for eligible signed-in users

useSubscription may return:

  • undefined while loading
  • a subscription object when present
  • null/empty when no subscription exists

The current truthy check hides plans for both “loading” and “no subscription” cases. That risks permanently rendering an empty list for signed-in users who legitimately have no subscription (unless the platform guarantees a subscription object always exists). Gate on the loading state instead.

Apply this diff to make the logic robust and intentional:

-  const plansToRender = useMemo(() => {
-    return clerk.isSignedIn
-      ? subscription // All users in billing-enabled applications have a subscription
-        ? plans
-        : []
-      : plans;
-  }, [clerk.isSignedIn, plans, subscription]);
+  const plansToRender = useMemo(() => {
+    if (!clerk.isSignedIn) {
+      return plans;
+    }
+    // Hide plans while the subscription is loading to prevent flicker.
+    // Once the request has resolved (even if it returns null), render plans.
+    return isSubscriptionLoading ? [] : plans;
+  }, [clerk.isSignedIn, isSubscriptionLoading, plans]);

Follow-up:

  • If it’s indeed guaranteed that every signed-in user in billing-enabled apps always has a subscription object (never null), please confirm. Otherwise this fix is necessary.
  • Consider showing a lightweight skeleton when returning [] to communicate loading to the user.

Additionally, please add tests covering:

  • signed-in + subscription loading -> no plans
  • signed-in + subscription null -> plans visible
  • signed-out -> plans visible

I can scaffold test cases with mocked contexts for these states if helpful.


🏁 Script executed:

#!/bin/bash
# Locate the definition(s) and usage of `useSubscription` in the codebase
rg "useSubscription" -n packages/clerk-js/src

Length of output: 2324


#!/bin/bash
# Show the implementation of useSubscription in Plans.tsx
rg -n "export const useSubscription" -A20 packages/clerk-js/src/ui/contexts/components/Plans.tsx

🏁 Script executed:

#!/bin/bash
# Show the implementation of useSubscription in Plans.tsx to inspect its return shape
rg -n "export const useSubscription" -A20 packages/clerk-js/src/ui/contexts/components/Plans.tsx

Length of output: 720


🏁 Script executed:

#!/bin/bash
# Locate definition of __experimental_useSubscription
rg -n "__experimental_useSubscription" -n

Length of output: 468


🏁 Script executed:

#!/bin/bash
# Display first 200 lines of useSubscription implementation to verify available return fields
sed -n '1,200p' packages/shared/src/react/hooks/useSubscription.ts

Length of output: 160


#!/bin/bash
# Find the implementation file for useSubscription in shared package
find packages/shared/src -type f | grep -i useSubscription

#!/bin/bash
# List all files under the shared react hooks directory to locate useSubscription implementation
echo "Files in packages/shared/src/react/hooks:"
find packages/shared/src/react/hooks -type f

# Display the contents of any file matching "useSubscription" in that directory
echo ""
echo "=== useSubscription Hook Implementation ==="
for file in $(find packages/shared/src/react/hooks -type f | grep -i useSubscription); do
  echo "----- $file -----"
  sed -n '1,200p' "$file"
  echo ""
done

#!/bin/bash
# List all files in the shared react hooks directory
echo "=== files in packages/shared/src/react/hooks ==="
find packages/shared/src/react/hooks -type f

# Search for any implementation of useSubscription within that directory
echo ""
echo "=== search for useSubscription implementation ==="
rg -n "useSubscription" -n packages/shared/src/react/hooks

#!/bin/bash
# List all files in the shared package to locate the actual useSubscription implementation
echo "=== Files matching useSubscription in packages/shared ==="
find packages/shared -type f | grep -i useSubscription

Update PricingTable to distinguish loading vs. no-subscription states

The current logic (subscription ? plans : []) treats “loading” and “no subscription” identically, hiding plans even when a signed-in user simply has no subscription. Instead, gate on the hook’s loading state and always show plans once the request resolves (regardless of whether subscription is null).

• File: packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx
• Lines: 19–25

Recommended diff:

-  const plansToRender = useMemo(() => {
-    return clerk.isSignedIn
-      ? subscription // All users in billing-enabled applications have a subscription
-        ? plans
-        : []
-      : plans;
-  }, [clerk.isSignedIn, plans, subscription]);
+  const plansToRender = useMemo(() => {
+    const { isLoading: isSubscriptionLoading } = useSubscription();
+    if (!clerk.isSignedIn) {
+      return plans;
+    }
+    // Hide plans only while the subscription is loading.
+    // Once loaded (even if `subscription` is null), render plans.
+    return isSubscriptionLoading ? [] : plans;
+  }, [clerk.isSignedIn, plans, useSubscription().isLoading]);

Follow-up actions:

  • Destructure isLoading (alias to isSubscriptionLoading) from useSubscription.
  • Add a lightweight skeleton or spinner when isSubscriptionLoading is true.
  • Add tests for:
    • Signed-in + loading → no plans shown
    • Signed-in + no subscription (null) → plans shown
    • Signed-out → plans shown

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
packages/clerk-js/src/ui/components/PricingTable/PricingTable.tsx lines 19-25:
the current plansToRender logic conflates "loading" with "no subscription" by
using subscription ? plans : [] for signed-in users; instead destructure
isLoading (alias isSubscriptionLoading) from useSubscription and use it to show
a lightweight skeleton/spinner while the subscription request is pending, and
change plansToRender so that when the subscription request has resolved
(isLoading === false) you render plans regardless of subscription being null;
update the dependency array to include isLoading, and add tests covering
signed-in+loading (no plans shown), signed-in+no-subscription (plans shown), and
signed-out (plans shown).

Copy link
Member

@wobsoriano wobsoriano left a comment

Choose a reason for hiding this comment

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

looks good based on the video

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: 1

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

217-217: Clarify test name to match the mocked state ("no subscription items" vs "no subscription")

This test mocks a subscription object with an empty subscriptionItems array rather than an absent subscription. Rename for precision and to avoid confusion with the dedicated null/undefined tests below.

-  it('shows no plans when user is signed in but has no subscription', async () => {
+  it('shows no plans when user is signed in and has no subscription items', async () => {

281-286: Prefer findBy over getBy wrapped in waitFor for presence assertions**

Using findByRole simplifies async presence checks and mirrors the pattern already used in this file (e.g., Line 87).

-    const { getByRole } = render(<PricingTable />, { wrapper });
-
-    await waitFor(() => {
-      // Should show plans when signed in and has subscription
-      expect(getByRole('heading', { name: 'Test Plan' })).toBeVisible();
-    });
+    const { findByRole } = render(<PricingTable />, { wrapper });
+    // Should show plans when signed in and has subscription
+    expect(await findByRole('heading', { name: 'Test Plan' })).toBeVisible();

299-304: Use findBy here as well for consistency and cleaner async handling*

This aligns the style across tests and avoids an extra waitFor wrapper.

-    const { getByRole } = render(<PricingTable />, { wrapper });
-
-    await waitFor(() => {
-      // Should show plans when signed out
-      expect(getByRole('heading', { name: 'Test Plan' })).toBeVisible();
-    });
+    const { findByRole } = render(<PricingTable />, { wrapper });
+    // Should show plans when signed out
+    expect(await findByRole('heading', { name: 'Test Plan' })).toBeVisible();

180-216: Introduce a typed test factory for plans to reduce casting and duplication

Inline fixtures rely on as any and re-specify the same shape repeatedly. A small builder improves type-safety, reduces noise, and eases future plan shape changes.

Example factory (place in a shared test utils module and import here):

type PartialDeep<T> = {
  [K in keyof T]?: T[K] extends object ? PartialDeep<T[K]> : T[K];
};

export const buildPlan = (overrides: PartialDeep<typeof testPlan> = {}) => {
  const base = {
    id: 'plan_default',
    name: 'Default',
    fee: { amount: 1000, amountFormatted: '10.00', currencySymbol: '$', currency: 'USD' },
    annualFee: { amount: 10000, amountFormatted: '100.00', currencySymbol: '$', currency: 'USD' },
    annualMonthlyFee: { amount: 833, amountFormatted: '8.33', currencySymbol: '$', currency: 'USD' },
    description: 'Default plan',
    hasBaseFee: true,
    isRecurring: true,
    isDefault: false,
    forPayerType: 'user',
    publiclyVisible: true,
    slug: 'default',
    avatarUrl: '',
    features: [] as any[],
    freeTrialEnabled: false,
    freeTrialDays: 0,
    __internal_toSnapshot: jest.fn(),
    pathRoot: '',
    reload: jest.fn(),
  } as const;
  return { ...base, ...overrides };
};

Then here:

const testPlan = buildPlan({ id: 'plan_test', name: 'Test Plan', slug: 'test' });

If you want, I can open a follow-up to consolidate the plan fixtures across tests.

📜 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 settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 74ceaf3 and 630fb83.

📒 Files selected for processing (1)
  • packages/clerk-js/src/ui/components/PricingTable/__tests__/PricingTable.test.tsx (1 hunks)
🧰 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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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). (5)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
packages/clerk-js/src/ui/components/PricingTable/__tests__/PricingTable.test.tsx (1)

179-346: Solid coverage for the new visibility logic; scenarios align with the flicker fix intent

The added suite validates key states: signed-out, signed-in with active subscription, and signed-in while subscription is null/undefined or empty. This directly exercises the flicker-prone paths and should prevent regressions.

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: 1

♻️ Duplicate comments (1)
packages/clerk-js/src/ui/components/PricingTable/__tests__/PricingTable.test.tsx (1)

347-404: Nice: the “loading → active” transition test directly guards against flicker

This scenario was requested earlier and is now covered. The pending promise + resolve-to-active pattern is correct and should prevent regressions in the loading window.

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

179-216: Prefer type-safe plan fixtures over as any casts

To keep tests future-proof and catch drift when API types evolve, consider typing testPlan using the satisfies operator against the public plan type (e.g., BillingPlanPublic or equivalent). This will let you drop several as any casts below and fail fast on shape changes.

If the plan type is available, an example pattern:

  • Import the plan type as a type-only import.
  • Define testPlan as as const satisfies BillingPlanPublic.

281-287: Use findByRole instead of getByRole + waitFor for presence assertions

findBy* queries are purpose-built for awaiting async DOM updates and reduce flakiness compared to wrapping getBy* in waitFor.

Apply these diffs:

@@
-    const { getByRole } = render(<PricingTable />, { wrapper });
-
-    await waitFor(() => {
-      // Should show plans when signed in and has subscription
-      expect(getByRole('heading', { name: 'Test Plan' })).toBeVisible();
-    });
+    const { findByRole } = render(<PricingTable />, { wrapper });
+    await waitFor(() => expect(fixtures.clerk.billing.getPlans).toHaveBeenCalled());
+    await waitFor(() => expect(fixtures.clerk.billing.getSubscription).toHaveBeenCalled());
+    // Should show plans when signed in and has subscription
+    expect(await findByRole('heading', { name: 'Test Plan' })).toBeVisible();
@@
-    const { getByRole } = render(<PricingTable />, { wrapper });
-
-    await waitFor(() => {
-      // Should show plans when signed out
-      expect(getByRole('heading', { name: 'Test Plan' })).toBeVisible();
-    });
+    const { findByRole } = render(<PricingTable />, { wrapper });
+    await waitFor(() => expect(fixtures.clerk.billing.getPlans).toHaveBeenCalled());
+    // Should show plans when signed out
+    expect(await findByRole('heading', { name: 'Test Plan' })).toBeVisible();

Also applies to: 299-305

📜 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 settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 630fb83 and 0bb3c52.

📒 Files selected for processing (1)
  • packages/clerk-js/src/ui/components/PricingTable/__tests__/PricingTable.test.tsx (1 hunks)
🧰 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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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/PricingTable/__tests__/PricingTable.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 (1)
packages/clerk-js/src/ui/components/PricingTable/__tests__/PricingTable.test.tsx (1)

225-232: Billing.getSubscription always returns a resource with subscriptionItems

The getSubscription call in our client is typed to return a CommerceSubscriptionResource, which always includes a subscriptionItems: CommerceSubscriptionItemResource[] field. It does not return null for “no subscription”—you’ll simply get an empty array (cast to any in tests) when there are no items. Modeling the “no subscription” scenario with { subscriptionItems: [] } is therefore consistent with the API shape and acceptable for testing this edge case.

Comment on lines +233 to +239
const { queryByRole } = render(<PricingTable />, { wrapper });

await waitFor(() => {
// Should not show any plans when signed in but no subscription
expect(queryByRole('heading', { name: 'Test Plan' })).not.toBeInTheDocument();
});
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Harden “absence” assertions to avoid false positives; wait for data fetches before asserting

Negative assertions wrapped in waitFor can pass immediately (before async effects settle), missing transient render states. Make the async flow deterministic by first waiting for the relevant API calls, then asserting the DOM is empty without waitFor.

Apply these diffs:

@@
-    const { queryByRole } = render(<PricingTable />, { wrapper });
-
-    await waitFor(() => {
-      // Should not show any plans when signed in but no subscription
-      expect(queryByRole('heading', { name: 'Test Plan' })).not.toBeInTheDocument();
-    });
+    const { queryByRole } = render(<PricingTable />, { wrapper });
+    await waitFor(() => expect(fixtures.clerk.billing.getPlans).toHaveBeenCalled());
+    await waitFor(() => expect(fixtures.clerk.billing.getSubscription).toHaveBeenCalled());
+    // Should not show any plans when signed in but no subscription
+    expect(queryByRole('heading', { name: 'Test Plan' })).not.toBeInTheDocument();
@@
-    const { queryByRole } = render(<PricingTable />, { wrapper });
-
-    await waitFor(() => {
-      // Should not show any plans when signed in but subscription is null
-      expect(queryByRole('heading', { name: 'Test Plan' })).not.toBeInTheDocument();
-    });
+    const { queryByRole } = render(<PricingTable />, { wrapper });
+    await waitFor(() => expect(fixtures.clerk.billing.getPlans).toHaveBeenCalled());
+    await waitFor(() => expect(fixtures.clerk.billing.getSubscription).toHaveBeenCalled());
+    // Should not show any plans when signed in but subscription is null
+    expect(queryByRole('heading', { name: 'Test Plan' })).not.toBeInTheDocument();
@@
-    const { queryByRole } = render(<PricingTable />, { wrapper });
-
-    await waitFor(() => {
-      // Should not show any plans when signed in but subscription is undefined (loading)
-      expect(queryByRole('heading', { name: 'Test Plan' })).not.toBeInTheDocument();
-    });
+    const { queryByRole } = render(<PricingTable />, { wrapper });
+    await waitFor(() => expect(fixtures.clerk.billing.getPlans).toHaveBeenCalled());
+    await waitFor(() => expect(fixtures.clerk.billing.getSubscription).toHaveBeenCalled());
+    // Should not show any plans when signed in but subscription is undefined (loading)
+    expect(queryByRole('heading', { name: 'Test Plan' })).not.toBeInTheDocument();
@@
-    // Assert no plans render while subscription is pending
-    await waitFor(() => {
-      expect(queryByRole('heading', { name: 'Test Plan' })).not.toBeInTheDocument();
-    });
+    // Assert no plans render while subscription is pending
+    await waitFor(() => expect(fixtures.clerk.billing.getPlans).toHaveBeenCalled());
+    expect(queryByRole('heading', { name: 'Test Plan' })).not.toBeInTheDocument();

Also applies to: 319-325, 339-345, 366-369

@panteliselef panteliselef merged commit d775436 into main Aug 14, 2025
39 checks passed
@panteliselef panteliselef deleted the elef/com-1153-fix-flickering-of-pricing-table-on-load branch August 14, 2025 17:10
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.

6 participants