Skip to content

Conversation

@panteliselef
Copy link
Member

@panteliselef panteliselef commented Nov 5, 2025

Description

We already have unit tests for this, but this is a more realistic scenario :)

Checklist

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

Type of change

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

Summary by CodeRabbit

  • New Features

    • Added a new billing page displaying available plans, current subscription status, and billing statements.
    • Integrated authentication state handling to show relevant billing information based on sign-in status.
  • Tests

    • Added integration tests validating billing functionality across signed-in and signed-out user states.

@panteliselef panteliselef requested review from a team November 5, 2025 18:53
@panteliselef panteliselef self-assigned this Nov 5, 2025
@changeset-bot
Copy link

changeset-bot bot commented Nov 5, 2025

⚠️ No Changeset found

Latest commit: dd97bbf

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

@vercel
Copy link

vercel bot commented Nov 5, 2025

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

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Nov 5, 2025 6:54pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 5, 2025

Walkthrough

A new Next.js client component displays billing information using experimental Clerk hooks for plans, statements, and subscriptions. An integration test suite validates the UI across signed-out and signed-in states, including subscription flow and sign-out behavior.

Changes

Cohort / File(s) Summary
Billing UI Component
integration/templates/next-app-router/src/app/billing/hooks/page.tsx
New client component using experimental Clerk hooks (usePlans, useSubscription, useStatements) to fetch and display plans, statements, and subscription status with conditional rendering for no-data states.
Billing Integration Tests
integration/tests/billing-hooks.test.ts
New integration test suite validating billing UI across signed-out/signed-in states, including setup/teardown, plan display verification, subscription workflow (sign-in → checkout → payment), and state changes after sign-out.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Page as Billing Hooks Page
    participant Clerk as Clerk Hooks
    participant UI as Component Render

    rect rgb(200, 220, 255)
        Note over User,UI: Signed-Out Flow
        User->>Page: Navigate to /billing/hooks
        Page->>Clerk: Call usePlans()
        Clerk-->>Page: Return plans list
        Page->>UI: Render plans (Pro plan visible)
        Page->>UI: Render "No statements found"
        Page->>UI: Render "No subscription found"
    end

    rect rgb(220, 240, 220)
        Note over User,UI: Signed-In Flow
        User->>Page: Sign in & navigate to /billing/hooks
        Page->>Clerk: Call usePlans()
        Page->>Clerk: Call useStatements()
        Page->>Clerk: Call useSubscription()
        Clerk-->>Page: Return plans, statements, subscription
        Page->>UI: Render plans, statements (total 99.96)
        Page->>UI: Render "Subscribed to Plus"
    end

    rect rgb(255, 240, 220)
        Note over User,UI: Sign-Out Flow
        User->>Page: Sign out via Clerk
        Page->>Clerk: Re-fetch hooks data
        Clerk-->>Page: Return empty/null data
        Page->>UI: Render plans only
        Page->>UI: Render "No statements found"
        Page->>UI: Render "No subscription found"
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Experimental hooks usage: Verify that usePlans, useSubscription, and useStatements hooks are correctly implemented and no-op fallbacks are appropriate
  • Test coverage completeness: Validate that all scenarios (signed-out, signed-in, subscription, sign-out) are correctly sequenced and assertions are comprehensive
  • Null/undefined handling: Confirm null guards and conditional rendering logic properly handle all data states

Poem

🐰 Hops through billing pages bright,
With plans and hooks in light,
Statements dance, subscriptions gleam—
Clerked by tests, a rabbit's dream! ✨

Pre-merge checks and finishing touches

✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'chore(e2e): Tests for validating billing hooks behaviour' accurately describes the main changes: adding E2E tests for billing hooks. It is concise, clear, and directly relates to the changeset.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch elef/bill-1399-add-e2e-to-check-for-data-being-cleared-from-billing-hooks

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Nov 5, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: dd97bbf

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

🧹 Nitpick comments (1)
integration/templates/next-app-router/src/app/billing/hooks/page.tsx (1)

8-35: Consider accessibility and semantic HTML improvements.

The component could benefit from:

  1. Semantic HTML structure using <section> or <article> tags
  2. Proper heading hierarchy (currently using multiple <h2> tags without an <h1>)
  3. ARIA labels for better screen reader support
  4. More descriptive test IDs or data attributes for easier testing

Example improvement:

return (
  <main>
    <section aria-label="Available Plans">
      <h1>Billing Information</h1>
      {plans?.map(plan => (
        <article key={plan.id}>
          <h2>Plan: {plan.name}</h2>
          <p>{plan.description}</p>
        </article>
      ))}
      {planCount > 0 ? <p>Plans found</p> : <p>No plans found</p>}
    </section>

    <section aria-label="Billing Statements">
      {statements?.map(statement => (
        <article key={statement.id}>
          <p>Statement total: {statement.totals.grandTotal.amountFormatted}</p>
        </article>
      ))}
      {statementCount > 0 ? <p>Statements found</p> : <p>No statements found</p>}
    </section>

    <section aria-label="Current Subscription">
      {subscription ? (
        <div>
          <h2>Subscribed to {subscription.subscriptionItems?.[0]?.plan?.name || 'Unknown Plan'}</h2>
        </div>
      ) : (
        <p>No subscription found</p>
      )}
    </section>
  </main>
);
📜 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 5536429 and dd97bbf.

📒 Files selected for processing (2)
  • integration/templates/next-app-router/src/app/billing/hooks/page.tsx (1 hunks)
  • integration/tests/billing-hooks.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{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:

  • integration/templates/next-app-router/src/app/billing/hooks/page.tsx
  • integration/tests/billing-hooks.test.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

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

Use Prettier for consistent code formatting

Files:

  • integration/templates/next-app-router/src/app/billing/hooks/page.tsx
  • integration/tests/billing-hooks.test.ts
**/*.{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:

  • integration/templates/next-app-router/src/app/billing/hooks/page.tsx
  • integration/tests/billing-hooks.test.ts
**/*.{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:

  • integration/templates/next-app-router/src/app/billing/hooks/page.tsx
integration/**

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

Framework integration templates and E2E tests should be placed under the integration/ directory

Files:

  • integration/templates/next-app-router/src/app/billing/hooks/page.tsx
  • integration/tests/billing-hooks.test.ts
integration/**/*

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

End-to-end tests and integration templates must be located in the 'integration/' directory.

Files:

  • integration/templates/next-app-router/src/app/billing/hooks/page.tsx
  • integration/tests/billing-hooks.test.ts
**/*.{js,ts,tsx,jsx}

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

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

Files:

  • integration/templates/next-app-router/src/app/billing/hooks/page.tsx
  • integration/tests/billing-hooks.test.ts
**/*.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:

  • integration/templates/next-app-router/src/app/billing/hooks/page.tsx
integration/**/*.{test,spec}.{js,ts}

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

Integration tests should use Playwright.

Files:

  • integration/tests/billing-hooks.test.ts
🧬 Code graph analysis (1)
integration/tests/billing-hooks.test.ts (2)
integration/testUtils/index.ts (1)
  • createTestUtils (24-86)
integration/presets/index.ts (1)
  • appConfigs (15-32)
⏰ 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). (30)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome, 16)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Static analysis
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (5)
integration/templates/next-app-router/src/app/billing/hooks/page.tsx (1)

1-2: LGTM!

Properly configured as a client component with appropriate experimental hook imports.

integration/tests/billing-hooks.test.ts (4)

1-22: LGTM!

Test setup is well-structured with:

  • Proper imports and environment configuration
  • Appropriate skip condition for Next.js-only tests
  • Resource management with user creation and cleanup

24-36: Verify that waiting for ClerkJs is sufficient.

The test waits for ClerkJsLoaded but doesn't explicitly wait for the billing hooks data to load. If the usePlans hook has any async behavior beyond Clerk initialization, there could be a race condition.

Consider adding an explicit wait for the first expected element before making assertions:

       await u.po.page.waitForClerkJsLoaded();
+      
+      // Ensure plans have loaded before making assertions
+      await u.po.page.waitForSelector('text=Plans found', { timeout: 5000 });

       await expect(u.po.page.getByText('Plans found')).toBeVisible();

This is particularly important if plans are fetched asynchronously after Clerk loads.


38-52: LGTM!

The subscription test flow is well-structured and properly uses serial mode since the second test depends on this subscription being created. The test correctly validates the payment success before continuing.


81-83: Assertion approach for hidden elements is correct.

Using toBeHidden() to verify that subscription and statement elements are not visible after sign-out is the appropriate approach. The { exact: true } flag ensures precise text matching.

Comment on lines +4 to +7
export default function Home() {
const { data: plans, count: planCount } = usePlans();
const { data: subscription } = useSubscription();
const { data: statements, count: statementCount } = useStatements();
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Add explicit return type and handle loading/error states.

The component definition has several concerns:

  1. Missing explicit return type: Per coding guidelines, functions should have explicit return types.
  2. No loading or error state handling: The experimental hooks likely provide isLoading and error properties that should be handled to improve UX.

Apply this diff to add return type and basic state handling:

-export default function Home() {
+export default function Home(): JSX.Element {
-  const { data: plans, count: planCount } = usePlans();
-  const { data: subscription } = useSubscription();
-  const { data: statements, count: statementCount } = useStatements();
+  const { data: plans, count: planCount, isLoading: plansLoading, error: plansError } = usePlans();
+  const { data: subscription, isLoading: subscriptionLoading, error: subscriptionError } = useSubscription();
+  const { data: statements, count: statementCount, isLoading: statementsLoading, error: statementsError } = useStatements();
+
+  if (plansLoading || subscriptionLoading || statementsLoading) {
+    return <main><p>Loading billing information...</p></main>;
+  }
+
+  if (plansError || subscriptionError || statementsError) {
+    return <main><p>Error loading billing information. Please try again.</p></main>;
+  }
+
   return (

Note: Verify that the experimental hooks actually expose isLoading and error properties before applying this change.


🏁 Script executed:

#!/bin/bash
# Description: Check the experimental hooks API to confirm they expose loading and error states

# Search for the hook type definitions or implementations
rg -nP --type=ts -A 10 'export (function|const) (usePlans|useSubscription|useStatements)'

Length of output: 9370


🏁 Script executed:

#!/bin/bash
# Search for createBillingPaginatedHook definition and return type

rg -nP --type=ts -B 5 -A 15 'function createBillingPaginatedHook|type createBillingPaginatedHook' 

Length of output: 2054


🏁 Script executed:

#!/bin/bash
# Search for SubscriptionResult type definition

rg -nP --type=ts 'type SubscriptionResult|interface SubscriptionResult' -A 10

Length of output: 870


🏁 Script executed:

#!/bin/bash
# Check what properties are actually destructured from these hooks in the codebase

rg -nP --type=tsx 'usePlans\(\)|useSubscription\(\)|useStatements\(\)' -A 5 -B 2 | head -100

Length of output: 27


🏁 Script executed:

#!/bin/bash
# Search for PaginatedResources type definition

rg -nP --type=ts 'type PaginatedResources|interface PaginatedResources' -A 15

Length of output: 2331


🏁 Script executed:

#!/bin/bash
# Get the actual file under review

cat integration/templates/next-app-router/src/app/billing/hooks/page.tsx

Length of output: 1027


🏁 Script executed:

#!/bin/bash
# Check how these hooks are actually used throughout the codebase with correct file type

rg -nP --type=tsx,ts 'const.*=\s*(usePlans|useSubscription|useStatements)\(' -A 3 | head -150

Length of output: 30


Add explicit return type and handle loading/error states from hooks.

The component is missing two improvements:

  1. Missing explicit return type: Per coding guidelines, all functions should have explicit return types. Add JSX.Element.
  2. No loading/error state handling: All three hooks expose isLoading and error properties that should be handled for better UX. The component currently renders potentially undefined data during loading and ignores errors.

The hooks expose these properties via their return types:

  • usePlans() and useStatements() return PaginatedResources<T> with error, isLoading, isFetching
  • useSubscription() returns SubscriptionResult with error, isLoading, isFetching
🤖 Prompt for AI Agents
In integration/templates/next-app-router/src/app/billing/hooks/page.tsx around
lines 4 to 7, the Home component lacks an explicit return type and does not
handle loading/error states from usePlans, useSubscription, and useStatements;
update the function signature to return JSX.Element and add simple guards that
check each hook's isLoading and error values (e.g., show a loading indicator
while any isLoading is true, and render an error message if any error exists),
and ensure the main render uses only defined plans, subscription, and statements
(fallback to empty arrays or null checks) so undefined data is not rendered
during fetches.

Comment on lines +27 to +33
{subscription ? (
<div>
<h2>Subscribed to {subscription.subscriptionItems[0].plan.name}</h2>
</div>
) : (
<p>No subscription found</p>
)}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Unsafe array access will cause runtime error.

Line 29 directly accesses subscription.subscriptionItems[0] without verifying:

  1. subscriptionItems exists
  2. subscriptionItems is an array
  3. The array has at least one element

This will throw a runtime error if subscriptionItems is undefined, null, or an empty array.

Apply this diff to add proper bounds checking:

       {subscription ? (
         <div>
-          <h2>Subscribed to {subscription.subscriptionItems[0].plan.name}</h2>
+          <h2>Subscribed to {subscription.subscriptionItems?.[0]?.plan?.name || 'Unknown Plan'}</h2>
         </div>
       ) : (
📝 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
{subscription ? (
<div>
<h2>Subscribed to {subscription.subscriptionItems[0].plan.name}</h2>
</div>
) : (
<p>No subscription found</p>
)}
{subscription ? (
<div>
<h2>Subscribed to {subscription.subscriptionItems?.[0]?.plan?.name || 'Unknown Plan'}</h2>
</div>
) : (
<p>No subscription found</p>
)}
🤖 Prompt for AI Agents
In integration/templates/next-app-router/src/app/billing/hooks/page.tsx around
lines 27 to 33, the code directly accesses
subscription.subscriptionItems[0].plan.name which can throw if subscriptionItems
is missing or empty; update the conditional/render to first verify
subscription.subscriptionItems is an array with length > 0 (or use optional
chaining and Array.isArray) before accessing [0], and render a safe fallback
(e.g., "No subscription items" or the generic "No subscription found") when the
check fails so no runtime error occurs.

Comment on lines +54 to +84
test('renders billing hooks with plans, statements and subscription', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
await u.po.signIn.goTo();
await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeUser.email, password: fakeUser.password });
await u.po.page.goToRelative('/billing/hooks');

await u.po.page.waitForClerkJsLoaded();

await expect(u.po.page.getByText('Plans found')).toBeVisible();
await expect(u.po.page.getByRole('heading', { name: 'Plan: Pro' })).toBeVisible();

await expect(u.po.page.getByText('Statements found')).toBeVisible();
await expect(u.po.page.getByText('Statement total: 99.96')).toBeVisible();

await expect(u.po.page.getByRole('heading', { name: 'Subscribed to Plus' })).toBeVisible();

await u.page.evaluate(async () => {
await window.Clerk.signOut({
redirectUrl: '/billing/hooks',
});
});

await expect(u.po.page.getByText('Plans found')).toBeVisible();
await expect(u.po.page.getByRole('heading', { name: 'Plan: Pro' })).toBeVisible();
await expect(u.po.page.getByText('No statements found')).toBeVisible();
await expect(u.po.page.getByText('No subscription found')).toBeVisible();

await expect(u.po.page.getByRole('heading', { name: 'Subscribed to Plus' })).toBeHidden();
await expect(u.po.page.getByText('Statements found', { exact: true })).toBeHidden();
await expect(u.po.page.getByText('Statement total: 99.96', { exact: true })).toBeHidden();
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Add wait after sign-out to prevent race condition.

After calling window.Clerk.signOut() on line 70-74, the test immediately makes assertions without waiting for:

  1. The redirect to /billing/hooks to complete
  2. The page to re-render with signed-out state
  3. The billing hooks to refetch data

This creates a race condition where assertions may run before sign-out completes.

Apply this diff to add an explicit wait:

       await u.page.evaluate(async () => {
         await window.Clerk.signOut({
           redirectUrl: '/billing/hooks',
         });
       });
+
+      // Wait for sign-out to complete and page to reload
+      await u.po.page.waitForURL('**/billing/hooks');
+      await u.po.page.waitForClerkJsLoaded();
+      // Wait for signed-out state to render
+      await expect(u.po.page.getByText('No subscription found')).toBeVisible({ timeout: 5000 });

       await expect(u.po.page.getByText('Plans found')).toBeVisible();

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.

🧪

@panteliselef panteliselef merged commit 83eeb56 into main Nov 5, 2025
45 checks passed
@panteliselef panteliselef deleted the elef/bill-1399-add-e2e-to-check-for-data-being-cleared-from-billing-hooks branch November 5, 2025 21:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants