Skip to content

feat(clerk-js): Additional vitest specs #5716

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

Merged
merged 14 commits into from
Jun 11, 2025
Merged

feat(clerk-js): Additional vitest specs #5716

merged 14 commits into from
Jun 11, 2025

Conversation

jacekradko
Copy link
Member

@jacekradko jacekradko commented Apr 25, 2025

Description

Some additional test conversions from jest to vitest now that we have both testing frameworks supported in clerk-js

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

  • Chores
    • Migrated all tests from Jest to Vitest, updating test utilities, mocks, and assertions for consistency.
    • Enhanced Vitest configuration with improved coverage reporting, SVG import mocking, and environment setup for browser API compatibility.
    • Updated development dependencies and scripts to support Vitest-based testing.
    • Added new utility modules and fixtures to streamline and improve test setup and mocking for Clerk.js components.
  • Bug Fixes
    • Updated test expectations to reflect the correct default localhost port (3000) in URL-related tests.
  • Tests
    • Introduced new and improved test helpers, fixtures, and utilities to facilitate more robust and isolated component and hook testing.

Copy link

changeset-bot bot commented Apr 25, 2025

🦋 Changeset detected

Latest commit: 684c7bf

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

This PR includes changesets to release 0 packages

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

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 Apr 25, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
clerk-js-sandbox ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 11, 2025 4:17pm

Copy link
Contributor

coderabbitai bot commented Jun 9, 2025

📝 Walkthrough

Walkthrough

This update migrates all Clerk.js tests and supporting utilities from the Jest testing framework to Vitest. It replaces Jest-specific mocks, spies, and test utilities with Vitest equivalents across all test files, updates test utility imports, and introduces new Vitest-based fixture and mock helper modules. The Vitest configuration is enhanced with SVG mocks, coverage reporting, and global constants. Several new utility modules are added for generating fixtures, mocking Clerk methods, and running fake timers within Vitest. Test assertions are updated to reflect a default localhost port of 3000. Environment setup is improved with locale, timezone, and browser API mocks to ensure consistent and reliable test execution.

Changes

Files/Groups Change Summary
.changeset/chatty-wombats-rest.md Added an empty changeset file.
eslint.config.mjs Added a Vitest-specific ESLint override disabling certain rules for test files.
package.json Updated @vitest/coverage-v8 devDependency from 3.0.2 to 3.0.5.
packages/clerk-js/package.json Added test:jest script and new devDependencies: @emotion/jest, jsdom.
packages/clerk-js/vitest.config.mts Enhanced Vitest config: added SVG mock plugin, global defines, coverage settings, alias for @/ to src directory, and included globals: false.
packages/clerk-js/vitest.setup.mts Expanded Vitest setup: enforced locale/timezone, polyfilled/mocked browser APIs, set up environment consistency.
packages/clerk-js/src/vitestUtils.ts Added new Vitest test utility module: custom render, extended matchers, userEvent, mock helpers, and environment mocks for React Native and WebAuthn.
packages/clerk-js/src/core/vitest/fixtures.ts Added Vitest fixture module for Clerk entities: mock data, factory functions, and fetch mocks.
packages/clerk-js/src/ui/utils/vitest/createFixtures.tsx Added Vitest utility for creating component fixtures with context providers and mocks.
packages/clerk-js/src/ui/utils/vitest/fixtures.ts Added functions to create base Clerk environment, client, and user JSON fixtures for tests.
packages/clerk-js/src/ui/utils/vitest/fixtureHelpers.ts Added comprehensive fixture helpers for Clerk UI component testing (environment, client, user, sign-in/up, config, etc.).
packages/clerk-js/src/ui/utils/vitest/mockHelpers.ts Added Vitest mock helpers for Clerk methods and route context values, with deep mocking support.
packages/clerk-js/src/ui/utils/vitest/runFakeTimers.ts Added utility to run code with Vitest fake timers, wrapping timer controls with React Testing Library's act.
packages/clerk-js/src/ui/components/OrganizationSwitcher/__tests__/vitestUtils.ts Added utility to create fake organization-related resource objects for component tests using Vitest.
packages/clerk-js/src/ui/utils/test/createFixtures.tsx Removed unused React import.
packages/clerk-js/src/core/__tests__/*,
packages/clerk-js/src/core/auth/__tests__/*,
packages/clerk-js/src/core/resources/__tests__/*,
packages/clerk-js/src/core/fraudProtection.spec.ts
Replaced all Jest imports, mocks, and utilities with Vitest equivalents; updated fixtures import paths; no test logic changes.
packages/clerk-js/src/ui/common/__tests__/redirects.spec.ts,
packages/clerk-js/src/utils/__tests__/url.spec.ts
Updated expected URLs in assertions to use http://localhost:3000 instead of http://localhost.
packages/clerk-js/src/ui/components/SignUp/__tests__/SignUpStart.spec.tsx,
packages/clerk-js/src/ui/elements/__tests__/PlainInput.spec.tsx,
packages/clerk-js/src/ui/elements/__tests__/RadioGroup.spec.tsx,
packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.spec.tsx
Switched test utility imports from Jest-based to Vitest-based modules; updated assertion casing where needed.
packages/clerk-js/src/ui/hooks/__tests__/useDevMode.spec.tsx,
packages/clerk-js/src/ui/hooks/__tests__/useSupportEmail.spec.tsx,
packages/clerk-js/src/ui/localization/__tests__/applyTokensToString.spec.ts
Replaced Jest mocks and imports with Vitest equivalents.
packages/clerk-js/src/ui/router/__mocks__/RouteContext.tsx,
packages/clerk-js/src/ui/router/__tests__/PathRouter.spec.tsx,
packages/clerk-js/src/ui/router/__tests__/Switch.spec.tsx,
packages/clerk-js/src/ui/router/__tests__/VirtualRouter.spec.tsx
Replaced Jest mocks and test utilities with Vitest equivalents; updated mock function implementations.
packages/clerk-js/src/ui/utils/__tests__/normalizeColorString.spec.ts Swapped Jest spies and mocks for Vitest's; updated type assertions.
packages/clerk-js/src/utils/__tests__/captcha.spec.ts,
packages/clerk-js/src/utils/__tests__/date.spec.ts,
packages/clerk-js/src/utils/__tests__/dynamicParamParser.spec.ts,
packages/clerk-js/src/utils/__tests__/errors.spec.ts,
packages/clerk-js/src/utils/__tests__/ignoreEventValue.spec.ts,
packages/clerk-js/src/utils/__tests__/instance.spec.ts,
packages/clerk-js/src/utils/__tests__/jwt.spec.ts,
packages/clerk-js/src/utils/__tests__/memoizeStateListenerCallback.spec.ts,
packages/clerk-js/src/utils/__tests__/organization.spec.ts,
packages/clerk-js/src/utils/__tests__/passkeys.spec.ts,
packages/clerk-js/src/utils/__tests__/path.spec.ts,
packages/clerk-js/src/utils/__tests__/queryStateParams.spec.ts,
packages/clerk-js/src/utils/__tests__/querystring.spec.ts,
packages/clerk-js/src/utils/__tests__/redirectUrls.spec.ts,
packages/clerk-js/src/utils/__tests__/resourceParams.spec.ts
Explicitly imported Vitest test functions; replaced Jest timer and spy utilities with Vitest's where needed.
packages/clerk-js/src/utils/__tests__/completeSignUpFlow.spec.ts,
packages/clerk-js/src/utils/__tests__/localStorage.spec.ts
Replaced Jest mocks, timers, and restore calls with Vitest equivalents.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4993246 and 684c7bf.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (2)
  • packages/clerk-js/package.json (3 hunks)
  • packages/clerk-js/vitest.config.mts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/clerk-js/package.json
  • packages/clerk-js/vitest.config.mts
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

@jacekradko jacekradko force-pushed the feat/clerkjs-vitest branch from 9a82b66 to ef039ae Compare June 9, 2025 19:51
@jacekradko jacekradko marked this pull request as ready for review June 9, 2025 19:52
Copy link

pkg-pr-new bot commented Jun 9, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 684c7bf

@jacekradko jacekradko changed the title feat(clerk-js): vitest feat(clerk-js): Additional vitest specs Jun 9, 2025
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: 21

🧹 Nitpick comments (18)
packages/clerk-js/src/core/resources/__tests__/Image.spec.ts (1)

15-20: Consider restoring the original BaseResource._fetch after tests. Overwriting the static _fetch method directly can leak into other tests. You may use vi.spyOn(BaseResource, '_fetch') along with vi.restoreAllMocks() in an afterEach hook, or capture and reassign the original method.

packages/clerk-js/src/core/resources/__tests__/ExternalAccount.spec.ts (1)

15-15: Mocking _fetch on BaseResource could be scoped. Consider using vi.spyOn(BaseResource, '_fetch') and restoring it post-test (vi.restoreAllMocks() or manual reassignment) to avoid cross-test side effects.

packages/clerk-js/src/__tests__/mocks/svgMock.tsx (1)

4-9: Improve type safety and add displayName for better debugging.

The component has a type mismatch - it accepts React.SVGProps<SVGSVGElement> but renders as a span. This could lead to type issues when SVG-specific props are passed.

Apply this diff to improve type safety and debugging:

-const SvgMock = React.forwardRef<HTMLSpanElement, React.SVGProps<SVGSVGElement>>((props, ref) => (
+const SvgMock = React.forwardRef<HTMLSpanElement, React.HTMLAttributes<HTMLSpanElement>>((props, ref) => (
   <span
     ref={ref}
     {...props}
   />
 ));
+
+SvgMock.displayName = 'SvgMock';
packages/clerk-js/src/ui/utils/vitest/runFakeTimers.ts (2)

1-1: Remove commented Jest import.

The commented Jest import should be removed as it's no longer needed.

-// import { jest } from '@jest/globals';

6-11: Improve type safety in withAct function.

The withAct function uses any types which reduces type safety. Consider improving the typing.

-const withAct = ((fn: any) =>
-  (...args: any) => {
+const withAct = <T extends (...args: any[]) => void>(fn: T): T =>
+  ((...args: Parameters<T>) => {
     act(() => {
       fn(...args);
     });
-  }) as WithAct;
+  }) as T;
packages/clerk-js/src/ui/utils/vitest/mockHelpers.ts (2)

1-1: Remove commented out Jest import.

Clean up the leftover Jest import comment since the migration to Vitest is complete.

-// import { jest } from '@jest/globals';

59-60: Clarify the purpose of the comment about touch mock.

The comment "Ensure touch mock matches expected signature if available, otherwise basic mock" seems incomplete or unclear about what the expected signature should be.

Consider updating the comment to be more specific:

-          // Ensure touch mock matches expected signature if available, otherwise basic mock
+          // Mock the touch method to return a resolved promise with the session
packages/clerk-js/vitest.config.mts (1)

33-49: Consider adding more specific exclusions to coverage configuration.

The coverage exclusions list is comprehensive, but you might want to exclude additional patterns like mock files and test utilities.

Add these exclusions to prevent test utilities from affecting coverage metrics:

       exclude: [
         'src/**/*.d.ts',
         'src/**/index.ts',
         'src/**/index.browser.ts',
         'src/**/index.headless.ts',
         'src/**/index.headless.browser.ts',
         'src/**/coverage/**',
         'src/**/dist/**',
         'src/**/node_modules/**',
         'src/(ui|utils|core)/__tests__/**',
+        'src/**/*.test.{ts,tsx}',
+        'src/**/*.spec.{ts,tsx}',
+        'src/**/vitest/**',
+        'src/**/__mocks__/**'
       ],
packages/clerk-js/vitest.setup.mts (1)

69-84: Consider making IntersectionObserver implementation more complete.

The current mock is minimal. Consider implementing the basic callback functionality for more realistic testing.

Enhance the IntersectionObserver mock:

-  //@ts-expect-error - Mocking class
-  globalThis.IntersectionObserver = class IntersectionObserver {
-    constructor() {}
-    disconnect() {
-      return null;
-    }
-    observe() {
-      return null;
-    }
-    takeRecords() {
-      return []; // Return empty array as per spec
-    }
-    unobserve() {
-      return null;
-    }
-  };
+  globalThis.IntersectionObserver = vi.fn().mockImplementation((callback) => ({
+    root: null,
+    rootMargin: '0px',
+    thresholds: [0],
+    disconnect: vi.fn(),
+    observe: vi.fn(),
+    unobserve: vi.fn(),
+    takeRecords: vi.fn(() => []),
+  })) as any;
packages/clerk-js/src/ui/components/OrganizationSwitcher/__tests__/vitestUtils.ts (2)

24-54: Avoid unnecessary optional‐chaining on required params

params is a required argument, yet several fields are accessed with optional-chaining (e.g. params?.maxAllowedMemberships).
Using ?. here hides genuine typing mistakes and prevents the compiler from warning if the field is missing. Replace with direct access.

-    maxAllowedMemberships: params?.maxAllowedMemberships,
-    createdAt: params?.createdAt || new Date(),
+    maxAllowedMemberships: params.maxAllowedMemberships,
+    createdAt: params.createdAt ?? new Date(),

65-88: Leverage Partial & Pick to avoid widespread as any casts

All mocked methods are typed as vi.fn() as any, defeating the purpose of strong typing.
You can keep type-safety by returning vi.fn<ReturnType<typeof someRealMethod>, Parameters<typeof someRealMethod>>(), or by declaring a reusable helper:

const mockFn = <T extends (...a: any[]) => any>(): vi.Mock<ReturnType<T>, Parameters<T>> =>
  vi.fn() as any;

Then:

- accept: vi.fn() as any,
+ accept: mockFn<OrganizationInvitationResource['accept']>(),

This preserves IntelliSense while keeping the code concise.

packages/clerk-js/src/ui/utils/vitest/createFixtures.tsx (2)

84-90: Variable shadowing obscures outer props helper

const props = { … } is overshadowed by the props parameter of MockClerkProvider, reducing readability and making accidental misuse easy.

-const props = {
+const componentCtxPropsHelper = {
   setProps: …
}
…
const MockClerkProvider = ({ children }: { children: React.ReactNode }) => {

94-104: Hard-coded component exclusion list will silently stale

componentsWithoutContext is an ad-hoc string array. If new components that require skipping are added, forgetting to update this list will break tests.

Consider deriving the information from types (e.g. a discriminated union) or exposing a helper componentNeedsContext(name) to centralize the logic.

packages/clerk-js/src/vitestUtils.ts (1)

1-6: Use named import for userEvent to avoid future breaking changes

@testing-library/user-event’s default export is not guaranteed; the docs recommend the named import:

-import UserEvent from '@testing-library/user-event';
+import { userEvent as userEventLib } from '@testing-library/user-event';

and inside render:

-const userEvent = UserEvent.setup({ delay: null });
+const user = userEventLib.setup({ delay: null });

This prevents surprises if the library switches to ESM with no default export.

packages/clerk-js/src/ui/utils/vitest/fixtureHelpers.ts (2)

295-301: withMultiSessionMode mutates state but ignores requested mode

The helper always flips single_session_mode to false, giving no way to re-enable the flag and making intent unclear. Accept a boolean parameter (default true) for symmetry.

-  const withMultiSessionMode = () => {
-    // TODO:
-    ac.single_session_mode = false;
-  };
+  const withMultiSessionMode = (enable = true) => {
+    ac.single_session_mode = !enable;
+  };

487-496: Avoid // @ts-expect-error – model social strategies properly

Relying on a blanket suppression hides real typing issues and can break after type upgrades.
Extend the UserSettingsJSON['social'] index signature instead of forcing an error.

packages/clerk-js/src/core/vitest/fixtures.ts (2)

111-116: id initialised with provider name

ExternalAccountJSON.id should be a unique identifier (ext_...), not the OAuth provider string.

-    id: params?.provider || '',
+    id: params?.id || 'ext_test',

260-270: mockFetch never restores the original global

Overriding global.fetch without teardown leaks between tests. Capture the original and return a restore helper.

-export const mockFetch = (ok = true, status = 200, responsePayload = {}) => {
-  // @ts-ignore
-  global.fetch = vi.fn(() => {
-    return Promise.resolve<RecursivePartial<Response>>({
+export const mockFetch = (ok = true, status = 200, responsePayload = {}) => {
+  // @ts-ignore
+  const original = global.fetch;
+  global.fetch = vi.fn(() =>
+    Promise.resolve<RecursivePartial<Response>>({
       status,
       statusText: status.toString(),
       ok,
       json: () => Promise.resolve(responsePayload),
-    });
-  });
+    }),
+  );
+  return () => (global.fetch = original);
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 684f3bd and 9449e53.

⛔ Files ignored due to path filters (5)
  • packages/clerk-js/src/core/resources/__tests__/__snapshots__/Client.spec.ts.snap is excluded by !**/*.snap
  • packages/clerk-js/src/core/resources/__tests__/__snapshots__/Environment.spec.ts.snap is excluded by !**/*.snap
  • packages/clerk-js/src/core/resources/__tests__/__snapshots__/Session.spec.ts.snap is excluded by !**/*.snap
  • packages/clerk-js/src/core/resources/__tests__/__snapshots__/UserSettings.spec.ts.snap is excluded by !**/*.snap
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (67)
  • .changeset/chatty-wombats-rest.md (1 hunks)
  • eslint.config.mjs (1 hunks)
  • package.json (1 hunks)
  • packages/clerk-js/package.json (3 hunks)
  • packages/clerk-js/src/__tests__/headless.spec.ts (1 hunks)
  • packages/clerk-js/src/__tests__/mocks/svgMock.tsx (1 hunks)
  • packages/clerk-js/src/core/__tests__/clerk.redirects.spec.ts (2 hunks)
  • packages/clerk-js/src/core/__tests__/fapiClient.spec.ts (5 hunks)
  • packages/clerk-js/src/core/__tests__/tokenCache.spec.ts (6 hunks)
  • packages/clerk-js/src/core/auth/__tests__/cookieSuffix.spec.ts (2 hunks)
  • packages/clerk-js/src/core/auth/__tests__/devBrowser.spec.ts (3 hunks)
  • packages/clerk-js/src/core/auth/__tests__/getCookieDomain.spec.ts (5 hunks)
  • packages/clerk-js/src/core/auth/__tests__/getSecureAttribute.spec.ts (1 hunks)
  • packages/clerk-js/src/core/fraudProtection.spec.ts (9 hunks)
  • packages/clerk-js/src/core/resources/__tests__/AuthConfig.spec.ts (1 hunks)
  • packages/clerk-js/src/core/resources/__tests__/Base.spec.ts (3 hunks)
  • packages/clerk-js/src/core/resources/__tests__/Client.spec.ts (5 hunks)
  • packages/clerk-js/src/core/resources/__tests__/Environment.spec.ts (1 hunks)
  • packages/clerk-js/src/core/resources/__tests__/ExternalAccount.spec.ts (3 hunks)
  • packages/clerk-js/src/core/resources/__tests__/Image.spec.ts (2 hunks)
  • packages/clerk-js/src/core/resources/__tests__/Session.spec.ts (4 hunks)
  • packages/clerk-js/src/core/resources/__tests__/Token.spec.ts (3 hunks)
  • packages/clerk-js/src/core/resources/__tests__/User.spec.ts (9 hunks)
  • packages/clerk-js/src/core/resources/__tests__/UserSettings.spec.ts (1 hunks)
  • packages/clerk-js/src/core/resources/__tests__/Web3Wallet.spec.ts (5 hunks)
  • packages/clerk-js/src/core/vitest/fixtures.ts (1 hunks)
  • packages/clerk-js/src/ui/common/__tests__/redirects.spec.ts (13 hunks)
  • packages/clerk-js/src/ui/components/OrganizationSwitcher/__tests__/vitestUtils.ts (1 hunks)
  • packages/clerk-js/src/ui/components/SignUp/__tests__/SignUpStart.spec.tsx (4 hunks)
  • packages/clerk-js/src/ui/elements/__tests__/PlainInput.spec.tsx (2 hunks)
  • packages/clerk-js/src/ui/elements/__tests__/RadioGroup.spec.tsx (2 hunks)
  • packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.spec.tsx (1 hunks)
  • packages/clerk-js/src/ui/hooks/__tests__/useDevMode.spec.tsx (1 hunks)
  • packages/clerk-js/src/ui/hooks/__tests__/useSupportEmail.spec.tsx (1 hunks)
  • packages/clerk-js/src/ui/localization/__tests__/applyTokensToString.spec.ts (2 hunks)
  • packages/clerk-js/src/ui/router/__mocks__/RouteContext.tsx (1 hunks)
  • packages/clerk-js/src/ui/router/__tests__/PathRouter.spec.tsx (1 hunks)
  • packages/clerk-js/src/ui/router/__tests__/Switch.spec.tsx (2 hunks)
  • packages/clerk-js/src/ui/router/__tests__/VirtualRouter.spec.tsx (1 hunks)
  • packages/clerk-js/src/ui/utils/__tests__/normalizeColorString.spec.ts (4 hunks)
  • packages/clerk-js/src/ui/utils/test/createFixtures.tsx (0 hunks)
  • packages/clerk-js/src/ui/utils/vitest/createFixtures.tsx (1 hunks)
  • packages/clerk-js/src/ui/utils/vitest/fixtureHelpers.ts (1 hunks)
  • packages/clerk-js/src/ui/utils/vitest/fixtures.ts (1 hunks)
  • packages/clerk-js/src/ui/utils/vitest/mockHelpers.ts (1 hunks)
  • packages/clerk-js/src/ui/utils/vitest/runFakeTimers.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/captcha.spec.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/completeSignUpFlow.spec.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/date.spec.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/dynamicParamParser.spec.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/errors.spec.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/ignoreEventValue.spec.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/instance.spec.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/jwt.spec.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/localStorage.spec.ts (4 hunks)
  • packages/clerk-js/src/utils/__tests__/memoizeStateListenerCallback.spec.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/organization.spec.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/passkeys.spec.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/path.spec.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/queryStateParams.spec.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/querystring.spec.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/redirectUrls.spec.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/resourceParams.spec.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/url.spec.ts (6 hunks)
  • packages/clerk-js/src/vitestUtils.ts (1 hunks)
  • packages/clerk-js/vitest.config.mts (1 hunks)
  • packages/clerk-js/vitest.setup.mts (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/clerk-js/src/ui/utils/test/createFixtures.tsx
🧰 Additional context used
🧬 Code Graph Analysis (6)
packages/clerk-js/src/ui/router/__mocks__/RouteContext.tsx (1)
packages/shared/src/utils/index.ts (1)
  • noop (5-5)
packages/clerk-js/src/utils/__tests__/localStorage.spec.ts (1)
packages/clerk-js/src/utils/localStorage.ts (1)
  • SafeLocalStorage (17-66)
packages/clerk-js/src/core/resources/__tests__/Session.spec.ts (1)
packages/clerk-js/src/core/events.ts (1)
  • eventBus (20-20)
packages/clerk-js/src/core/__tests__/clerk.redirects.spec.ts (1)
packages/clerk-js/src/core/resources/Environment.ts (1)
  • Environment (16-93)
packages/clerk-js/src/core/resources/__tests__/Client.spec.ts (1)
packages/clerk-js/src/core/vitest/fixtures.ts (1)
  • createSession (174-199)
packages/clerk-js/src/ui/utils/vitest/createFixtures.tsx (9)
packages/clerk-js/src/ui/utils/vitest/fixtureHelpers.ts (2)
  • createEnvironmentFixtureHelpers (25-32)
  • createClientFixtureHelpers (34-40)
packages/clerk-js/src/ui/utils/vitest/mockHelpers.ts (2)
  • mockRouteContextValue (85-103)
  • mockClerkMethods (46-83)
packages/clerk-js/src/ui/types.ts (2)
  • AvailableComponentName (147-147)
  • AvailableComponentProps (39-52)
packages/clerk-js/src/ui/utils/vitest/fixtures.ts (2)
  • createBaseEnvironmentJSON (13-23)
  • createBaseClientJSON (209-211)
packages/clerk-js/src/core/resources/Environment.ts (1)
  • Environment (16-93)
packages/types/src/clerk.ts (1)
  • LoadedClerk (1825-1827)
packages/clerk-js/src/ui/contexts/ClerkUIComponentsContext.tsx (1)
  • ComponentContextProvider (22-102)
packages/clerk-js/src/ui/customizables/index.ts (1)
  • AppearanceProvider (9-9)
packages/clerk-js/src/ui/elements/contexts/index.tsx (1)
  • FlowMetadataProvider (116-120)
🪛 Biome (1.9.4)
packages/clerk-js/src/ui/common/__tests__/redirects.spec.ts

[error] 3-3: Declarations inside of a import declaration may not have duplicates

a second declaration of buildVerificationRedirectUrl is not allowed

buildVerificationRedirectUrl is first declared here

(parse)

🪛 Gitleaks (8.26.0)
packages/clerk-js/src/ui/hooks/__tests__/useSupportEmail.spec.tsx

11-11: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

packages/clerk-js/src/ui/utils/vitest/fixtureHelpers.ts

88-88: Uncovered a JSON Web Token, which may lead to unauthorized access to web applications and sensitive user data.

(jwt)

packages/clerk-js/src/ui/utils/vitest/createFixtures.tsx

67-67: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

⏰ Context from checks skipped due to timeout of 90000ms (23)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 13)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Unit Tests (22, **)
  • 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: Analyze (javascript-typescript)
🔇 Additional comments (133)
packages/clerk-js/src/utils/__tests__/errors.spec.ts (1)

1-1: Migrate to Vitest imports

Explicitly importing describe, expect, and it from Vitest is correct and aligns with the broader test migration.

packages/clerk-js/src/core/resources/__tests__/UserSettings.spec.ts (1)

2-2: Switch to Vitest functions

Importing describe, expect, and it from Vitest properly replaces Jest globals in this test suite.

packages/clerk-js/src/utils/__tests__/passkeys.spec.ts (1)

7-7: Update imports for Vitest

Correctly importing core test functions from Vitest ensures consistency with the new testing framework.

package.json (1)

86-86: Bump @vitest/coverage-v8 version

Updating the coverage-v8 plugin to 3.0.5 to match the Vitest version is appropriate. Ensure this version is available on npm and aligns with your Vitest config.

packages/clerk-js/src/utils/__tests__/jwt.spec.ts (1)

1-2: Use explicit Vitest imports
The test now imports describe, expect, and it from Vitest, aligning with the Jest→Vitest migration. No other logic changes.

packages/clerk-js/src/utils/__tests__/querystring.spec.ts (1)

2-2: Use explicit Vitest imports
Adding describe, expect, and it from Vitest ensures consistency with the new test runner. The existing assertions remain unchanged.

packages/clerk-js/src/utils/__tests__/captcha.spec.ts (1)

1-2: Use explicit Vitest imports
Importing Vitest's describe, expect, and it supports the transition from Jest; the it.each syntax is preserved.

packages/clerk-js/src/core/resources/__tests__/Environment.spec.ts (1)

2-2: Use explicit Vitest imports
The test now explicitly pulls describe, expect, and it from Vitest. No snapshots or logic were altered.

packages/clerk-js/src/utils/__tests__/ignoreEventValue.spec.ts (1)

1-2: Use explicit Vitest imports
Swapped in Vitest's testing functions for Jest globals. Test behavior remains intact.

packages/clerk-js/src/utils/__tests__/organization.spec.ts (1)

1-1: Migrate test imports to Vitest
Imports for describe, expect, and it from Vitest align perfectly with the Jest→Vitest migration in this suite.

packages/clerk-js/src/utils/__tests__/queryStateParams.spec.ts (1)

1-1: Migrate test imports to Vitest
Switching to describe, expect, and it from Vitest is correct and consistent with the other converted tests.

packages/clerk-js/src/utils/__tests__/resourceParams.spec.ts (1)

2-2: Migrate test imports to Vitest
The explicit import of describe, expect, and it from Vitest correctly replaces the previous Jest imports.

packages/clerk-js/src/utils/__tests__/memoizeStateListenerCallback.spec.ts (1)

3-3: Migrate test imports to Vitest
Importing describe and it from Vitest is sufficient for the skipped tests here—no expect or vi usage needed.

packages/clerk-js/src/utils/__tests__/redirectUrls.spec.ts (1)

3-3: Migrate test imports to Vitest
The addition of afterAll, beforeEach, describe, expect, and it from Vitest correctly updates the test harness.

packages/clerk-js/src/utils/__tests__/instance.spec.ts (1)

1-1: Correct Vitest import for test functions

The Vitest globals (describe, expect, it) are properly imported, replacing Jest equivalents.

packages/clerk-js/src/utils/__tests__/path.spec.ts (1)

1-1: Correct Vitest import for test functions

Vitest globals (describe, expect, it) are correctly imported to replace Jest references. The existing it.each usage aligns with Vitest's API.

packages/clerk-js/src/__tests__/headless.spec.ts (2)

2-2: Update test environment directive

The JSDoc directive has been updated to @vitest-environment node, ensuring the test runs in the correct environment under Vitest.


5-5: Add Vitest imports for test functions

The test functions (describe, expect, it) are properly imported from Vitest, replacing the default Jest globals.

packages/clerk-js/src/utils/__tests__/completeSignUpFlow.spec.ts (2)

2-2: Import Vitest lifecycle hooks and mocking utilities

The import brings in beforeEach, describe, expect, it, and vi from Vitest, correctly replacing Jest equivalents.


6-8: Replace Jest mocks with Vitest vi.fn()

Mocks mockHandleComplete, mockNavigate, and mockAuthenticateWithRedirect are correctly instantiated with vi.fn().

packages/clerk-js/src/utils/__tests__/dynamicParamParser.spec.ts (1)

1-1: Correct Vitest import for test functions

The Vitest globals (describe, expect, it) are properly imported, completing the migration from Jest.

packages/clerk-js/package.json (2)

84-84: Jest-specific plugin added.
The @emotion/jest dependency is appropriate for Jest-based tests. Ensure it’s only applied to the Jest runner configuration so Vitest tests aren’t inadvertently extended by it.


93-94: SVG and DOM mocking dependencies added.
Adding jsdom and vite-plugin-svgr ensures the test environment supports DOM APIs and SVG imports when running Vitest.

packages/clerk-js/src/core/resources/__tests__/Base.spec.ts (3)

1-1: Switched to Vitest testing API.
Importing describe, expect, it, and vi from Vitest correctly replaces the Jest API for this test file.


25-25: Mocked request with vi.fn().mockResolvedValue.
Replacing jest.fn() with vi.fn() maintains the same mocking behavior under Vitest.


33-33: Mocked internal callback with vi.fn().
The __internal_setCountry mock is correctly converted to use Vitest’s vi.fn() API.

packages/clerk-js/src/core/resources/__tests__/User.spec.ts (2)

2-2: Updated test imports to Vitest.
Switching imports from Jest to Vitest (describe, expect, it, vi) aligns with the overall test migration.


18-18: Migrated resource fetch mocks to Vitest’s vi.fn.
All instances of BaseResource._fetch = jest.fn() have been correctly updated to use vi.fn() under Vitest.

Also applies to: 53-53, 152-152, 180-180, 207-207, 274-274, 292-292

packages/clerk-js/src/ui/hooks/__tests__/useSupportEmail.spec.tsx (3)

2-2: Adopted Vitest test utilities.
Updating imports to use describe, expect, test, and vi from Vitest ensures compatibility with the new test runner.


6-7: Initialized mocks with Vitest's vi.fn().
Replacing Jest mock functions with vi.fn() for mockUseOptions and mockUseEnvironment maintains consistent mock behavior.


14-18: Mocked application context with Vitest's vi.mock.
The useOptions and useEnvironment mocks are correctly converted to Vitest’s API.

packages/clerk-js/src/core/auth/__tests__/cookieSuffix.spec.ts (5)

1-1: Migrated imports to Vitest.
Switching the test utilities import from Jest to Vitest (afterEach, beforeEach, describe, expect, test, vi) aligns with the migration.


3-5: Mocked shared keys module with vi.mock.
Converting the Jest mock of getCookieSuffix to Vitest’s vi.mock preserves the intended behavior.


6-8: Mocked logger module with vi.mock.
Replacing the Jest mock for logger.logOnce with vi.fn() under Vitest is correct.


16-16: Set up rejected mock for insecure context.
Using mockRejectedValue on the Vitest vi.Mock ensures the code path for errors is tested appropriately.


20-21: Reset mocks after each test.
Resetting both getSharedCookieSuffix and logger.logOnce via mockReset() avoids state leakage across tests.

packages/clerk-js/src/ui/router/__tests__/PathRouter.spec.tsx (3)

4-4: Replace Jest globals with Vitest imports

The global hooks and mocking functions have been correctly switched to Vitest’s API.


9-9: Use vi.fn() for spy creation

Migrating from jest.fn() to vi.fn() ensures compatibility with Vitest’s mocking utilities.


11-26: Switch jest.mock() to vi.mock() for module mocking

The module mock for @clerk/shared/react is correctly updated to use Vitest’s vi.mock().

packages/clerk-js/src/ui/elements/__tests__/RadioGroup.spec.tsx (3)

3-3: Update imports to Vitest

Replacing Jest globals with Vitest’s describe, expect, and it is accurate.


6-6: Adjust fixture helper import path

Switching to the Vitest-specific createFixtures module aligns with the new test infrastructure.


170-170: Capitalize error expectation

The assertion now matches the updated error message casing (Some Error).

packages/clerk-js/src/ui/localization/__tests__/applyTokensToString.spec.ts (2)

1-1: Replace Jest hooks with Vitest

Migrating beforeEach, describe, expect, it, and vi imports to Vitest is correct.


39-39: Use vi.spyOn() for console warnings

Replacing jest.spyOn with vi.spyOn ensures consistent mocking under Vitest.

packages/clerk-js/src/core/auth/__tests__/getSecureAttribute.spec.ts (2)

1-1: Switch test imports to Vitest

Updating Jest imports to Vitest (afterEach, beforeEach, describe, expect, it, vi) is correctly applied.


9-9: Use vi.spyOn() for window getter

The spy on window.window is properly migrated to Vitest’s vi.spyOn.

packages/clerk-js/src/ui/elements/__tests__/PlainInput.spec.tsx (3)

3-3: Replace Jest globals with Vitest imports

Switching to Vitest’s describe, expect, and it is correctly implemented.


6-6: Update fixture helper import to Vitest path

Changing to the Vitest-specific createFixtures module aligns with the new test setup.


138-138: Capitalize error expectation

The test assertion now expects Some Error instead of lowercase, matching the updated UI behavior.

packages/clerk-js/src/core/resources/__tests__/Image.spec.ts (1)

1-1: Migration to Vitest imports looks correct. The import of describe, expect, it, and vi from Vitest properly replaces Jest globals.

packages/clerk-js/src/ui/hooks/__tests__/useDevMode.spec.tsx (4)

3-3: Framework import updated correctly. Switching from Jest to Vitest’s describe, expect, test, and vi is appropriate.


7-9: Hook mocks declared using vi.fn(). Your replacement of jest.fn() with vi.fn() for mockUseEnvironment, mockUseOptions, and mockUseAppearance is spot on.


11-16: Context mock conversion is valid. The vi.mock('../../contexts', …) implementation maintains behavior from Jest’s jest.mock.


18-22: Appearance mock conversion is valid. Replacing jest.mock with vi.mock for useAppearance retains original logic.

packages/clerk-js/src/core/resources/__tests__/ExternalAccount.spec.ts (1)

1-1: Vitest import changes are correct. Importing Vitest’s APIs replaces Jest globals appropriately.

packages/clerk-js/src/ui/utils/__tests__/normalizeColorString.spec.ts (4)

1-1: Switched to Vitest lifecycle & assertion APIs. The import of afterEach, beforeEach, describe, expect, test, and vi is correct.


7-7: vi.spyOn used correctly. The console.warn spy with a noop implementation properly replaces jest.spyOn.


11-11: vi.clearAllMocks() in afterEach is appropriate. This cleans up all spy/mock state between tests.


39-39: Manual console.warn resets are valid. Clearing the mock mid-test isolates call counts as intended.

Also applies to: 83-83, 87-87, 96-96

packages/clerk-js/src/ui/router/__tests__/VirtualRouter.spec.tsx (3)

4-4: Vitest import usage is correct. Switching to afterAll, beforeAll, beforeEach, describe, expect, it, and vi matches Vitest conventions.


8-8: vi.fn() for mockNavigate is correct. Replacing jest.fn() maintains the same mocking behavior.


12-19: vi.mock for useClerk navigation is accurate. The mock implementation using vi.fn correctly emulates navigate.

packages/clerk-js/src/core/resources/__tests__/Web3Wallet.spec.ts (1)

2-2: LGTM! Clean Jest to Vitest migration.

The migration is well-executed with consistent replacement of Jest utilities with Vitest equivalents:

  • Import statement properly updated to use Vitest utilities
  • All mock functions correctly changed from jest.fn() to vi.fn()
  • Test logic and assertions remain unchanged, preserving test integrity

Also applies to: 14-14, 37-37, 60-60, 85-85

packages/clerk-js/src/ui/common/__tests__/redirects.spec.ts (2)

1-2: LGTM! Proper Jest to Vitest migration.

The import statement has been correctly updated to use Vitest testing utilities instead of Jest.


9-9: Verify the localhost port change aligns with test environment.

All localhost URLs have been updated to include port 3000. Ensure this change aligns with your test environment configuration and doesn't break existing test setups.

Also applies to: 18-18, 26-26, 38-38, 50-50, 62-62, 74-74, 86-86, 98-98, 110-110, 122-122, 158-158, 170-170, 177-177, 178-178, 180-180, 184-184, 186-186, 191-191, 202-202, 221-221

eslint.config.mjs (1)

372-379: LGTM! Proper ESLint configuration for Vitest migration.

The new configuration block correctly:

  • Targets Vitest test files (.spec.{ts,tsx}) in the clerk-js package
  • Disables Jest-specific ESLint rules that would conflict with Vitest
  • Follows the established naming and structure conventions

This configuration is essential for preventing ESLint errors during the Jest to Vitest migration.

packages/clerk-js/src/utils/__tests__/date.spec.ts (1)

1-2: LGTM! Correct timer mock migration to Vitest.

The timer mocking has been properly migrated from Jest to Vitest:

  • Import statement correctly updated to include Vitest utilities
  • jest.useFakeTimers('modern')vi.useFakeTimers()
  • jest.setSystemTime()vi.setSystemTime(Date.now())
  • jest.useRealTimers()vi.useRealTimers()

The test logic remains unchanged and the timer mocking functionality is preserved.

Also applies to: 7-8, 12-12

packages/clerk-js/src/core/__tests__/tokenCache.spec.ts (4)

2-2: Migration: Switch test imports to Vitest

The import now explicitly brings in Vitest’s globals (describe, it, expect, vi, etc.) instead of relying on Jest’s environment.


8-14: Migration: Replace jest.mock with vi.mock

The vi.mock call correctly replaces the Jest mock for BaseResource with Vitest’s equivalent.


21-22: Migration: Replace Jest timer functions with Vitest equivalents

The useFakeTimers/useRealTimers calls have been updated to vi.useFakeTimers() and vi.useRealTimers(), aligning with Vitest’s API.

Also applies to: 25-26


91-91: Migration: Replace jest.advanceTimersByTime with vi.advanceTimersByTime

All calls to advance the fake timers have been updated to vi.advanceTimersByTime().

Also applies to: 102-102, 129-129, 133-133, 155-155, 158-158, 162-162

packages/clerk-js/src/ui/components/SignUp/__tests__/SignUpStart.spec.tsx (4)

3-3: Migration: Switch test imports to Vitest

The top-level import now uses describe, it, expect, and vi from Vitest instead of Jest.


7-7: Migration: Import rendering utilities from vitestUtils

The rendering helpers (render, screen, waitFor) have been switched to your new Vitest-specific utilities module.


10-10: Migration: Switch fixture helper import to Vitest helper

The bindCreateFixtures import now points to the Vitest fixture creator instead of the Jest-based one.


302-302: Migration: Replace jest.fn with vi.fn for window.history mocking

The replaceState mock is now created with vi.fn(), matching Vitest’s mocking API.

Also applies to: 338-338

packages/clerk-js/src/core/resources/__tests__/AuthConfig.spec.ts (2)

1-1: Migration: Switch test imports to Vitest

Imports now pull describe, it, expect, and vi from Vitest rather than using Jest’s globals.


6-8: Migration: Replace jest.mock with vi.mock

The module mock for unixEpochToDate is correctly rewritten with vi.mock and vi.fn.

packages/clerk-js/src/utils/__tests__/localStorage.spec.ts (4)

1-1: Migration: Switch test imports to Vitest

The test now imports all lifecycle hooks and mock utilities from Vitest.


31-31: Add Vitest mock cleanup in afterEach

Including vi.restoreAllMocks() ensures all mocks are reset between tests, mirroring Jest’s restoreAllMocks.


58-65: Migration: Replace Jest timer functions with Vitest equivalents

Updated the useFakeTimers()/useRealTimers() calls for the expiration test in setItem to Vitest’s API.


110-118: Migration: Replace Jest timer functions with Vitest equivalents

Similarly, the expiration scenario in getItem now uses vi.useFakeTimers(), vi.advanceTimersByTime(), and vi.useRealTimers().

packages/clerk-js/src/core/auth/__tests__/getCookieDomain.spec.ts (5)

1-1: Migration: Switch test imports to Vitest

The initial import now explicitly sources Vitest’s test functions and mocks.


11-11: Migration: Reset modules using vi.resetModules

Replacing jest.resetModules() with vi.resetModules() correctly ensures a fresh module cache for each test.


25-33: Migration: Replace jest.fn mocks with vi.fn

The chained mockReturnValueOnce usages on get, set, and remove handlers have been updated to Vitest’s vi.fn().


58-61: Migration: Replace jest.fn mocks with vi.fn

The handler mock in the undefined-domain test uses vi.fn(), maintaining the original behavior.


70-73: Migration: Replace jest.fn mocks with vi.fn

The cached-value test mocks are now implemented with vi.fn(), ensuring the call count assertion works as expected.

packages/clerk-js/src/ui/router/__tests__/Switch.spec.tsx (4)

3-3: Migrate to Vitest test API
Importing Vitest globals (describe, it, vi, etc.) is correct and aligns with the new test framework.


7-7: Capture navigation calls with a dedicated mock
Defining mockNavigate separately ensures you can assert on navigation arguments. Good extraction.


9-19: Replace Jest module mock with Vitest mock
The vi.mock setup mirrors the previous jest.mock behavior and correctly delegates to mockNavigate.


33-33: Use vi.clearAllMocks to reset mocks between tests
Replacing jest.clearAllMocks with vi.clearAllMocks ensures no residual state across tests.

packages/clerk-js/src/ui/hooks/__tests__/useCoreOrganizationList.spec.tsx (4)

2-2: Switch test globals to Vitest
Importing describe, it, and expect from Vitest aligns with the overall migration.


4-4: Leverage custom Vitest utilities
Confirm that vitestUtils exports act, renderHook, and waitFor with equivalent behavior to the previous Jest utilities.


9-9: Update organization suggestion fixtures import
Importing from the Vitest-specific fixtures path is consistent with other test migrations.


10-10: Bind Vitest fixtures helper
Using bindCreateFixtures for organization fixtures maintains test consistency and eliminates Jest dependencies.

packages/clerk-js/src/core/auth/__tests__/devBrowser.spec.ts (4)

1-1: Import Vitest lifecycle hooks and mocks
Switching from Jest globals to Vitest equivalents is correctly handled.


13-13: Mock fetch with Vitest
Setting global.fetch = vi.fn() preserves the original test logic under Vitest.


34-34: Clear fetch mock after each test
Using vi.mocked(global.fetch)?.mockClear() ensures no cross-test pollution of the mock.


40-46: Replace Jest mock factories with Vitest vi.fn()
Migrating jest.fn() calls (buildUrl, onAfterResponse, onBeforeRequest) to vi.fn() retains the behavior of the FAPI client mock.

packages/clerk-js/src/ui/router/__mocks__/RouteContext.tsx (2)

2-2: Use Vitest for mocks
Importing vi instead of jest aligns with Vitest conventions in mock modules.


5-11: Convert mock methods to vi.fn()
Replacing jest.fn() with vi.fn() for resolve, matches, and navigate ensures consistent mocking under Vitest.

packages/clerk-js/src/core/__tests__/fapiClient.spec.ts (4)

2-2: Adopt Vitest globals
Importing lifecycle hooks and mock utilities from Vitest is correct for the migration.


57-59: Clear the fetch mock between tests
Using (global.fetch as vi.Mock).mockClear() in beforeEach correctly resets call history.


188-192: Update inline fetch mock resolution
Switching jest mocks to vi.fn() inside the array response test keeps behavior consistent.


205-210: Handle 204 response mock with Vitest
Migrating the 204 response scenario to use vi.Mock retains the original test intent.

packages/clerk-js/src/core/resources/__tests__/Client.spec.ts (3)

2-2: LGTM: Vitest import correctly updated.

The import statement has been properly migrated from Jest to Vitest testing utilities.


4-4: LGTM: Fixture import path updated for Vitest.

The import path has been correctly updated to use the new Vitest-specific fixtures module.


25-25: LGTM: Mock functions correctly migrated to Vitest.

All Jest mock functions have been properly replaced with their Vitest equivalents (vi.fn(), vi.fn().mockResolvedValueOnce(), vi.fn().mockReturnValue()).

Also applies to: 55-55, 108-108

packages/clerk-js/src/core/fraudProtection.spec.ts (4)

1-2: LGTM: Vitest imports and types correctly updated.

The import statement has been properly migrated from Jest to Vitest, including the correct Mock type import.


12-12: LGTM: Mock type updated to Vitest.

The type annotation has been correctly changed from jest.Mock to Vitest's Mock type.


27-27: LGTM: Mock functions correctly migrated to Vitest.

All Jest mock functions have been properly replaced with their Vitest equivalents using vi.fn() and its chaining methods.

Also applies to: 34-34, 50-50, 69-69, 78-79, 98-99, 120-121, 152-156


71-71: LGTM: Async rejection expectations properly handled.

The addition of await for promise rejection expectations is correct for Vitest's async handling requirements.

Also applies to: 168-168

packages/clerk-js/src/utils/__tests__/url.spec.ts (2)

3-3: LGTM: Vitest import correctly updated.

The import statement has been properly migrated from Jest to Vitest testing utilities.


503-503: LGTM: Spy function correctly migrated to Vitest.

The spy function has been properly replaced with Vitest's vi.spyOn().

packages/clerk-js/src/core/resources/__tests__/Session.spec.ts (4)

2-2: LGTM: Vitest imports and types correctly updated.

The import statement has been properly migrated from Jest to Vitest, including the correct Mock type import.


7-7: LGTM: Fixture import path updated for Vitest.

The import path has been correctly updated to use the new Vitest-specific fixtures module, consistent with other test files.


27-27: LGTM: Spy functions correctly migrated to Vitest.

All Jest spy functions have been properly replaced with Vitest's vi.spyOn().

Also applies to: 173-173


225-225: LGTM: Mock type annotation updated to Vitest.

The type casting has been correctly changed from jest.Mock<any> to Vitest's Mock<any> type.

packages/clerk-js/src/core/resources/__tests__/Token.spec.ts (4)

2-2: LGTM! Clean Jest to Vitest import migration.

The import statement correctly migrates from Jest to Vitest testing utilities.


6-6: LGTM! Fixture imports updated for Vitest.

The import correctly switches to the vitest-specific fixtures module.


21-21: LGTM! Mock type correctly updated for Vitest.

The Mock type is now properly imported from Vitest instead of Jest.


53-53: LGTM! Spy utility correctly migrated to Vitest.

The change from jest.spyOn to vi.spyOn is correct for the Vitest migration.

packages/clerk-js/src/core/__tests__/clerk.redirects.spec.ts (5)

1-2: LGTM! Clean Jest to Vitest import migration.

The import statement correctly migrates all testing utilities from Jest to Vitest.


8-9: LGTM! Mock functions properly migrated to Vitest.

The mock functions are correctly updated to use vi.fn() instead of jest.fn().


11-12: LGTM! Module mocking correctly updated for Vitest.

The module mocks are properly migrated to use vi.mock() instead of jest.mock().


15-22: LGTM! Mock implementation correctly migrated.

The DevBrowser mock implementation properly uses vi.fn() for all mock functions.


25-30: LGTM! Mock implementations correctly updated for Vitest.

The Client and Environment mock implementations properly use vi.fn().mockImplementation().

packages/clerk-js/src/ui/utils/vitest/fixtures.ts (1)

93-106: Good use of type safety with containsAllOfType helper.

The frozen arrays with the containsAllOfType utility ensure compile-time validation that all required attribute keys are included, preventing runtime errors.

packages/clerk-js/src/ui/utils/vitest/mockHelpers.ts (1)

46-83: Good systematic mocking approach for Clerk resources.

The recursive mocking of nested resources (user, email addresses, phone numbers, etc.) provides comprehensive test coverage while maintaining the object structure.

packages/clerk-js/vitest.config.mts (2)

34-36: Verify if coverage should be enabled by default.

Coverage is enabled by default (enabled: true), which might slow down test execution during development.

Consider making coverage opt-in for better developer experience:

     coverage: {
       provider: 'v8',
-      enabled: true,
+      enabled: process.env.CI === 'true' || process.env.COVERAGE === 'true',
       reporter: ['text', 'json', 'html'],

9-21:

❌ Incorrect review comment

Verify SVG mock plugin behavior in test environment.

The SVG mock plugin only transforms files when NODE_ENV === 'test', but Vitest might not always set this environment variable. This could lead to SVG imports not being mocked properly.


🏁 Script executed:

#!/bin/bash
# Check if NODE_ENV is set in test-related scripts
rg -A 5 "NODE_ENV.*test" package.json scripts/ --type json

# Check if there are any other references to NODE_ENV in test files
fd -e ts -e tsx -e js -e jsx --exec grep -l "process.env.NODE_ENV" {} \; | grep -E "(test|spec)" | head -20

Length of output: 376


Incorrect concern — Vitest already sets NODE_ENV to “test”
Vitest automatically sets NODE_ENV (and VITE_MODE) to "test" when running, so your SVG‐mock transform will always fire as expected. No changes required.

Likely an incorrect or invalid review comment.

packages/clerk-js/vitest.setup.mts (2)

12-13: Good approach to preserve the original method.

Storing the original toLocaleDateString method before overriding it ensures proper cleanup and prevents test pollution.


87-95:

✅ Verification successful

Consider implementing Chrome API mocks if needed.

The commented Chrome API mock suggests it might be needed. Verify if any tests require these APIs.


🏁 Script executed:

#!/bin/bash
# Check if any test files reference Chrome APIs
rg -A 3 "chrome\.(runtime|storage|tabs)" --type ts --type tsx | grep -E "(test|spec)"

# Check for any Chrome extension related code
fd -e ts -e tsx --exec grep -l "chrome\." {} \; | grep -v node_modules | head -10

Length of output: 489


No Chrome API references in clerk-js tests—mocks not needed

I searched the entire repo for chrome. and only found usages in the browser-extension and chrome-extension packages (e.g. playground/browser-extension/..., packages/chrome-extension/...). There are no references to chrome.* in any files under packages/clerk-js, including its Vitest tests.

You can leave the Chrome mock snippet in packages/clerk-js/vitest.setup.mts commented out for future use, but no action is required now.

packages/clerk-js/src/vitestUtils.ts (1)

32-52: mockNativeRuntime manipulates global getters – guard against non-existent descriptors

globalThis.document may already be undefined in js-dom-less environments, making vi.spyOn(globalThis, 'document', 'get') throw.
Add an existence check or fallback to Object.defineProperty only when the descriptor exists to avoid crashing the test suite in Node-only runs.

Comment on lines +18 to +20
export const mockJwt =
'eyJhbGciOiJSUzI1NiIsImtpZCI6Imluc18yR0lvUWhiVXB5MGhYN0IyY1ZrdVRNaW5Yb0QiLCJ0eXAiOiJKV1QifQ.eyJhenAiOiJodHRwczovL2FjY291bnRzLmluc3BpcmVkLnB1bWEtNzQubGNsLmRldiIsImV4cCI6MTY2NjY0ODMxMCwiaWF0IjoxNjY2NjQ4MjUwLCJpc3MiOiJodHRwczovL2NsZXJrLmluc3BpcmVkLnB1bWEtNzQubGNsLmRldiIsIm5iZiI6MTY2NjY0ODI0MCwic2lkIjoic2Vzc18yR2JEQjRlbk5kQ2E1dlMxenBDM1h6Zzl0SzkiLCJzdWIiOiJ1c2VyXzJHSXBYT0VwVnlKdzUxcmtabjlLbW5jNlN4ciJ9.n1Usc-DLDftqA0Xb-_2w8IGs4yjCmwc5RngwbSRvwevuZOIuRoeHmE2sgCdEvjfJEa7ewL6EVGVcM557TWPW--g_J1XQPwBy8tXfz7-S73CEuyRFiR97L2AHRdvRtvGtwR-o6l8aHaFxtlmfWbQXfg4kFJz2UGe9afmh3U9-f_4JOZ5fa3mI98UMy1-bo20vjXeWQ9aGrqaxHQxjnzzC-1Kpi5LdPvhQ16H0dPB8MHRTSM5TAuLKTpPV7wqixmbtcc2-0k6b9FKYZNqRVTaIyV-lifZloBvdzlfOF8nW1VVH_fx-iW5Q3hovHFcJIULHEC1kcAYTubbxzpgeVQepGg';

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

Real-looking JWT committed to VCS

Same concern as in fixtureHelpers.ts. Replace with a clearly fake, very short token.

🤖 Prompt for AI Agents
In packages/clerk-js/src/core/vitest/fixtures.ts around lines 18 to 20, the
mockJwt constant contains a real-looking JWT token which should not be committed
to version control. Replace this token with a clearly fake, very short JWT
string that does not resemble a real token to avoid any security or privacy
concerns.

Comment on lines +77 to +80
object: 'email_address',
id: params?.email_address || '',
email_address: '[email protected]',
reserved: false,
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

id is set to an e-mail address

EmailAddressJSON.id should be the Clerk-generated ID (e.g. idn_...), not the address itself.
Use params.id (or generate one) and keep the address in email_address.

-    id: params?.email_address || '',
+    id: params?.id || 'idn_test_email',
📝 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
object: 'email_address',
id: params?.email_address || '',
email_address: '[email protected]',
reserved: false,
object: 'email_address',
- id: params?.email_address || '',
+ id: params?.id || 'idn_test_email',
email_address: '[email protected]',
reserved: false,
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/vitest/fixtures.ts around lines 77 to 80, the `id`
field is incorrectly set to the email address string. Update the `id` to use
`params.id` if available or generate a Clerk-style ID (e.g., starting with
`idn_`), and keep the actual email address in the `email_address` field
unchanged.

Comment on lines +184 to +191
user: createUser({}),
public_user_data: {
first_name: user.first_name,
last_name: user.last_name,
image_url: user.image_url,
has_image: user.has_image,
identifier: user.email_addresses?.find(e => e.id === user.primary_email_address_id)?.email_address || '',
},
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

public_user_data and user point at different users

createSession always injects a brand-new user, while public_user_data reflects the caller-provided user param, leading to inconsistent fixtures.

-    user: createUser({}),
+    const fullUser = createUser(user);
+    ...
+    user: fullUser,
+    public_user_data: {
+      first_name: fullUser.first_name,
+      last_name: fullUser.last_name,
+      image_url: fullUser.image_url,
+      has_image: fullUser.has_image,
+      identifier: fullUser.email_addresses[0]?.email_address || '',
+    },

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

🤖 Prompt for AI Agents
In packages/clerk-js/src/core/vitest/fixtures.ts around lines 184 to 191, the
public_user_data object is constructed from a different user instance than the
one created by createUser, causing inconsistency. To fix this, ensure that
public_user_data is derived from the same user object returned by createUser, so
both reference the identical user data and maintain fixture consistency.

Comment on lines +94 to +96
object: 'phone_number',
id: params?.phone_number || '',
phone_number: '+30 691 1111111',
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

Same bug for phone numbers

PhoneNumberJSON.id is not a phone number. Mirror the fix above.

-    id: params?.phone_number || '',
+    id: params?.id || 'idn_test_phone',
📝 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
object: 'phone_number',
id: params?.phone_number || '',
phone_number: '+30 691 1111111',
object: 'phone_number',
id: params?.id || 'idn_test_phone',
phone_number: '+30 691 1111111',
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/vitest/fixtures.ts around lines 94 to 96, the id
field of PhoneNumberJSON is incorrectly set to a phone number string. Update the
id field to use a unique identifier or a non-phone number value, mirroring the
fix applied previously to ensure id does not contain a phone number.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
packages/clerk-js/src/ui/utils/vitest/fixtureHelpers.ts (1)

87-89: This is a duplicate of a previously flagged issue.

The hardcoded JWT token has already been identified as triggering secret-scanning tools. The previous reviewer suggested replacing this with a clearly fake token.

🧹 Nitpick comments (6)
packages/clerk-js/src/core/__tests__/fapiClient.spec.ts (1)

65-65: Consider replacing delete operator for better performance.

The static analysis tool suggests avoiding the delete operator due to performance implications. While the impact is minimal in test cleanup, consider using undefined assignment for consistency.

- delete window.Clerk;
+ window.Clerk = undefined;
🧰 Tools
🪛 Biome (1.9.4)

[error] 65-65: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

packages/clerk-js/src/ui/utils/vitest/fixtureHelpers.ts (5)

151-151: Consider improving type safety by avoiding as any casts.

The use of as any bypasses TypeScript's type checking and could mask potential runtime errors. Consider creating proper type definitions or using more specific type assertions.

-      user_data: { ...(createUserFixture() as any) },
+      user_data: createUserFixture(),

Apply similar changes to lines 179 and 217 by ensuring createUserFixture() returns the correct type that matches the expected user_data structure.

Also applies to: 179-179, 217-217


298-299: TODO comment indicates incomplete implementation.

The TODO comment suggests that multi-session mode implementation might be incomplete or needs attention.

Would you like me to help investigate what needs to be implemented for multi-session mode or create an issue to track this task?


349-566: Consider breaking down this large function for better maintainability.

The createUserSettingsFixtureHelpers function is quite large (217 lines) and handles many different user settings configurations. Consider breaking it into smaller, more focused helper functions grouped by functionality (e.g., authentication methods, user attributes, sign-up settings).

Example refactor approach:

const createUserSettingsFixtureHelpers = (environment: EnvironmentJSON) => {
  return {
    ...createAuthenticationHelpers(environment),
    ...createUserAttributeHelpers(environment),
    ...createSignUpHelpers(environment),
  };
};

489-490: String concatenation for strategy could be error-prone.

The manual string concatenation 'oauth_' + provider could lead to inconsistencies. Consider using a more type-safe approach or template literals.

-    const strategy = 'oauth_' + provider;
+    const strategy = `oauth_${provider}`;

545-545: TODO comment indicates incomplete implementation.

The comment references pkg/generate/auth_config.go, suggesting there might be additional user settings that need to be implemented.

Would you like me to help identify what additional user settings might be missing or create an issue to track completing this implementation?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9449e53 and d72f1bd.

📒 Files selected for processing (3)
  • packages/clerk-js/src/core/__tests__/fapiClient.spec.ts (5 hunks)
  • packages/clerk-js/src/ui/common/__tests__/redirects.spec.ts (13 hunks)
  • packages/clerk-js/src/ui/utils/vitest/fixtureHelpers.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/clerk-js/src/ui/common/tests/redirects.spec.ts
🧰 Additional context used
🪛 Biome (1.9.4)
packages/clerk-js/src/core/__tests__/fapiClient.spec.ts

[error] 65-65: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (6)
packages/clerk-js/src/core/__tests__/fapiClient.spec.ts (6)

2-2: LGTM! Clean import migration to Vitest.

The import statement correctly replaces Jest utilities with their Vitest equivalents, maintaining all necessary testing functions.


28-29: Excellent addition! Addresses previous review feedback.

Capturing the original fetch reference before mocking prevents test pollution, directly addressing the previous review comment about mock leakage.


31-31: Correct migration from Jest to Vitest mocks.

The mock functions are properly converted from jest.fn() to vi.fn() for Vitest compatibility.

Also applies to: 34-34


60-60: Proper type assertion update for Vitest.

The cast to vi.Mock correctly replaces the Jest equivalent, ensuring type safety with Vitest mocks.


66-66: Essential cleanup prevents test pollution.

Restoring the original fetch in afterAll completes the proper mock lifecycle management, ensuring tests don't interfere with each other.


191-191: Consistent mock type casting throughout.

All mock type assertions are consistently updated to use vi.Mock instead of jest.Mock, completing the Vitest migration.

Also applies to: 194-194, 208-208

Copy link
Member

@tmilewski tmilewski left a comment

Choose a reason for hiding this comment

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

🚀 Added a few files to exclude in the vitest config.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
packages/clerk-js/vitest.config.mts (4)

6-23: Consider relocating the mock plugin before vite-plugin-svgr.

viteSvgMockPlugin overrides whatever is produced by previous transformers for .svg files. Keeping it after vite-plugin-svgr works but causes each SVG to go through svgr’s (un-needed) transform first, then be discarded.
Moving the mock plugin to the front of the array will skip that extra work and speed up test startup a bit.

-  plugins: [react({ jsxRuntime: 'automatic', jsxImportSource: '@emotion/react' }), svgr(), viteSvgMockPlugin()],
+  plugins: [
+    react({ jsxRuntime: 'automatic', jsxImportSource: '@emotion/react' }),
+    viteSvgMockPlugin(),  // run first for tests
+    svgr(),
+  ],

10-17: Use import.meta.env.MODE instead of process.env.NODE_ENV.

Under Vite/Vitest, process.env.NODE_ENV is shimmed but not officially documented; import.meta.env.MODE is the recommended API and is statically replaced at build time.

-      if (id.endsWith('.svg') && process.env.NODE_ENV === 'test') {
+      if (id.endsWith('.svg') && import.meta.env.MODE === 'test') {

28-31: Avoid hard-coding version to "test" – derive it from package.json.

Hard-coding may go stale and leaks into the bundle when vitest is run with --reporter html. You can read it once at config time:

-import { defineConfig } from 'vitest/config';
+import { defineConfig } from 'vitest/config';
+import { readFileSync } from 'fs';
+const pkgVersion = JSON.parse(
+  readFileSync(new URL('./package.json', import.meta.url), 'utf8'),
+).version;
...
-    __PKG_VERSION__: JSON.stringify('test'),
+    __PKG_VERSION__: JSON.stringify(pkgVersion),

33-51: Exclude generated declaration maps to keep coverage noise down.

If declarationMap is enabled in tsconfig, *.d.ts.map files end up in src/**. They are currently counted as uncovered. Add them to the exclusion list:

       exclude: [
         'src/**/*.d.ts',
+        'src/**/*.d.ts.map',
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0f14859 and 4993246.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • package.json (1 hunks)
  • packages/clerk-js/src/core/resources/__tests__/Client.spec.ts (5 hunks)
  • packages/clerk-js/src/core/resources/__tests__/Environment.spec.ts (1 hunks)
  • packages/clerk-js/src/core/resources/__tests__/Session.spec.ts (4 hunks)
  • packages/clerk-js/src/core/resources/__tests__/UserSettings.spec.ts (1 hunks)
  • packages/clerk-js/vitest.config.mts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/clerk-js/src/core/resources/tests/Session.spec.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/clerk-js/src/core/resources/tests/Environment.spec.ts
  • package.json
  • packages/clerk-js/src/core/resources/tests/UserSettings.spec.ts
  • packages/clerk-js/src/core/resources/tests/Client.spec.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)

@jacekradko jacekradko merged commit ce9e403 into main Jun 11, 2025
36 of 37 checks passed
@jacekradko jacekradko deleted the feat/clerkjs-vitest branch June 11, 2025 16:36
wobsoriano pushed a commit that referenced this pull request Jun 12, 2025
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.

3 participants