-
Notifications
You must be signed in to change notification settings - Fork 406
chore(e2e): Tests for validating billing hooks behaviour #7161
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
chore(e2e): Tests for validating billing hooks behaviour #7161
Conversation
|
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughA 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Poem
Pre-merge checks and finishing touches✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
@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: 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:
- Semantic HTML structure using
<section>or<article>tags- Proper heading hierarchy (currently using multiple
<h2>tags without an<h1>)- ARIA labels for better screen reader support
- 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.
📒 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.tsxintegration/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.tsxintegration/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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor 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 assertionsfor literal types:as const
Usesatisfiesoperator 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 ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor 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.tsxintegration/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.tsxintegration/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.tsxintegration/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.tsxintegration/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
ClerkJsLoadedbut doesn't explicitly wait for the billing hooks data to load. If theusePlanshook 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.
| export default function Home() { | ||
| const { data: plans, count: planCount } = usePlans(); | ||
| const { data: subscription } = useSubscription(); | ||
| const { data: statements, count: statementCount } = useStatements(); |
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.
🧩 Analysis chain
Add explicit return type and handle loading/error states.
The component definition has several concerns:
- Missing explicit return type: Per coding guidelines, functions should have explicit return types.
- No loading or error state handling: The experimental hooks likely provide
isLoadinganderrorproperties 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 10Length 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 -100Length of output: 27
🏁 Script executed:
#!/bin/bash
# Search for PaginatedResources type definition
rg -nP --type=ts 'type PaginatedResources|interface PaginatedResources' -A 15Length of output: 2331
🏁 Script executed:
#!/bin/bash
# Get the actual file under review
cat integration/templates/next-app-router/src/app/billing/hooks/page.tsxLength 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 -150Length of output: 30
Add explicit return type and handle loading/error states from hooks.
The component is missing two improvements:
- Missing explicit return type: Per coding guidelines, all functions should have explicit return types. Add
JSX.Element. - No loading/error state handling: All three hooks expose
isLoadinganderrorproperties 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()anduseStatements()returnPaginatedResources<T>witherror,isLoading,isFetchinguseSubscription()returnsSubscriptionResultwitherror,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.
| {subscription ? ( | ||
| <div> | ||
| <h2>Subscribed to {subscription.subscriptionItems[0].plan.name}</h2> | ||
| </div> | ||
| ) : ( | ||
| <p>No subscription found</p> | ||
| )} |
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.
Unsafe array access will cause runtime error.
Line 29 directly accesses subscription.subscriptionItems[0] without verifying:
subscriptionItemsexistssubscriptionItemsis an array- 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.
| {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.
| 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(); | ||
| }); |
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.
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:
- The redirect to
/billing/hooksto complete - The page to re-render with signed-out state
- 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();
wobsoriano
left a comment
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.
🧪
Description
We already have unit tests for this, but this is a more realistic scenario :)
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
New Features
Tests