Skip to content

test(clerk-js): Add dynamic TTL calculation tests for JWT expiration handling #6231

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

nikosdouvlis
Copy link
Member

@nikosdouvlis nikosdouvlis commented Jul 1, 2025

Improves the token cache by adding dynamic TTL calculation based on JWT exp and iat claims.

This change:

  • Adds tests to verify token expiration handling based on JWT TTL.
  • Creates a helper function to generate JWTs with custom TTL values for testing.
  • Ensures tokens with TTLs greater than 60 seconds are handled correctly.

Summary by CodeRabbit

  • Tests
    • Added new tests to verify dynamic token expiration handling in the token cache, including scenarios for both short and long TTLs. These tests ensure tokens are cached and removed at the correct times.

Copy link

changeset-bot bot commented Jul 1, 2025

🦋 Changeset detected

Latest commit: 53cdf34

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 Jul 1, 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 Jul 1, 2025 1:34pm

Copy link
Contributor

coderabbitai bot commented Jul 1, 2025

📝 Walkthrough

Walkthrough

A new empty changeset file .changeset/ten-kiwis-cry.md was added, containing only frontmatter delimiters and no content. In the test suite for MemoryTokenCache, a helper function createJwtWithTtl was introduced to generate JWT strings with customizable expiration and issued-at claims. Two test cases were added under a new "dynamic TTL calculation" describe block. These tests use mocked time and fake timers to verify that the cache correctly calculates token expiration based on the JWT claims, ensuring tokens are cached and removed according to their TTL.

Suggested labels

types


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

Copy link

pkg-pr-new bot commented Jul 1, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 53cdf34

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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

19-41: Improve type safety and add JSDoc documentation.

The helper function is well-implemented but could benefit from explicit typing and documentation.

+/**
+ * Creates a JWT with custom TTL for testing purposes
+ * @param ttlSeconds - Time to live in seconds
+ * @returns JWT string with custom expiration
+ */
-function createJwtWithTtl(ttlSeconds: number): string {
+function createJwtWithTtl(ttlSeconds: number): string {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 524c5e0 and 53cdf34.

📒 Files selected for processing (2)
  • .changeset/ten-kiwis-cry.md (1 hunks)
  • packages/clerk-js/src/core/__tests__/tokenCache.spec.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
`**/*.{js,jsx,ts,tsx}`: All code must pass ESLint checks with the project's conf...

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Use Prettier for consistent code formatting
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
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Validate all inputs and sanitize outputs
Implement proper logging with different levels

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

List of files the instruction was applied to:

  • packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
`packages/**/*.ts`: TypeScript is required for all packages

packages/**/*.ts: TypeScript is required for all packages

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

List of files the instruction was applied to:

  • packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
`**/{__tests__,**/__tests__}/**/*.{js,jsx,ts,tsx}`: Test files should be co-located with source files or in `__tests__` directories

**/{__tests__,**/__tests__}/**/*.{js,jsx,ts,tsx}: Test files should be co-located with source files or in __tests__ directories

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

List of files the instruction was applied to:

  • packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
`packages/**/*.{ts,tsx,d.ts}`: Packages should export TypeScript types alongside runtime code

packages/**/*.{ts,tsx,d.ts}: Packages should export TypeScript types alongside runtime code

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

List of files the instruction was applied to:

  • packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
`**/*.{ts,tsx}`: Use proper TypeScript error types

**/*.{ts,tsx}: Use proper TypeScript error types

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

List of files the instruction was applied to:

  • packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
`**/*.{test,spec}.{js,ts,tsx}`: Unit tests should use Jest or Vitest as the test runner.

**/*.{test,spec}.{js,ts,tsx}: Unit tests should use Jest or Vitest as the test runner.

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

List of files the instruction was applied to:

  • packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
`packages/{clerk-js,elements,themes}/**/*`: Visual regression testing should be performed for UI components.

packages/{clerk-js,elements,themes}/**/*: Visual regression testing should be performed for UI components.

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

List of files the instruction was applied to:

  • packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
`**/*.{ts,tsx}`: Always define explicit return types for functions, especially p...

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
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
Document public functions and APIs with JSDoc-style comments including @param, @returns, @throws, and @example
Define custom error classes for domain-specific errors
Use the Result pattern for error handling instead of throwing exceptions
Use optional chaining and nullish coalescing for safe property access
Let TypeScript infer types when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use readonly arrays and objects for immutability
Use immutable update patterns (spread, etc.) for objects and arrays
Use lazy loading for large types
Prefer unknown over any for performance
Use type-only imports: import type { ... }
Use branded types for domain safety
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints in TypeScript generics
No unused type parameters in generics
Proper use of utility types instead of manual type construction
Type-only imports where possible for performance
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

📄 Source: CodeRabbit Inference Engine (.cursor/rules/typescript.mdc)

List of files the instruction was applied to:

  • packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
`**/__tests__/**/*.{ts,tsx}`: Use Vitest for type-safe testing in TypeScript Cre...

**/__tests__/**/*.{ts,tsx}: Use Vitest for type-safe testing in TypeScript
Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces in tests

📄 Source: CodeRabbit Inference Engine (.cursor/rules/typescript.mdc)

List of files the instruction was applied to:

  • packages/clerk-js/src/core/__tests__/tokenCache.spec.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: dstaley
PR: clerk/javascript#6116
File: .changeset/tangy-garlics-say.md:1-2
Timestamp: 2025-06-13T16:09:53.061Z
Learning: In the Clerk JavaScript repository, contributors create intentionally empty changeset files (containing only the YAML delimiters) when a PR touches only non-published parts of the codebase (e.g., sandbox assets). This signals that no package release is required, so such changesets should not be flagged as missing content.
.changeset/ten-kiwis-cry.md (1)
Learnt from: dstaley
PR: clerk/javascript#6116
File: .changeset/tangy-garlics-say.md:1-2
Timestamp: 2025-06-13T16:09:53.061Z
Learning: In the Clerk JavaScript repository, contributors create intentionally empty changeset files (containing only the YAML delimiters) when a PR touches only non-published parts of the codebase (e.g., sandbox assets). This signals that no package release is required, so such changesets should not be flagged as missing content.
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts (7)
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/typescript.mdc:0-0
Timestamp: 2025-06-30T10:33:45.961Z
Learning: Applies to **/__tests__/**/*.{ts,tsx} : Create type-safe test builders/factories
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/monorepo.mdc:0-0
Timestamp: 2025-06-30T10:30:56.197Z
Learning: Applies to packages/clerk-react/**/*.{test,spec}.{js,ts,tsx} : Component testing should use React Testing Library.
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/typescript.mdc:0-0
Timestamp: 2025-06-30T10:33:45.961Z
Learning: Applies to **/__tests__/**/*.{ts,tsx} : Use branded types for test isolation
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/monorepo.mdc:0-0
Timestamp: 2025-06-30T10:30:56.197Z
Learning: Applies to packages/@clerk/*/jest.config.{js,ts} : Each framework integration package must have its own test configuration.
Learnt from: wobsoriano
PR: clerk/javascript#6123
File: packages/nextjs/src/server/__tests__/getAuthDataFromRequest.test.ts:63-75
Timestamp: 2025-06-16T01:27:54.563Z
Learning: In packages/nextjs/src/server/data/getAuthDataFromRequest.ts, the tokenType behavior on mismatch is intentionally different between array and single acceptsToken values: when acceptsToken is an array and the token type doesn't match any in the array, tokenType returns null; when acceptsToken is a single value and the token type doesn't match, tokenType returns the requested single value. This design aligns with developer intent and provides a more ergonomic API for common use cases.
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/development.mdc:0-0
Timestamp: 2025-06-30T10:29:42.997Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Implement proper caching strategies
Learnt from: CR
PR: clerk/javascript#0
File: .cursor/rules/typescript.mdc:0-0
Timestamp: 2025-06-30T10:33:45.961Z
Learning: Applies to **/__tests__/**/*.{ts,tsx} : Implement proper mock types that match interfaces in tests
🧬 Code Graph Analysis (1)
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts (1)
packages/clerk-js/src/core/tokenCache.ts (1)
  • SessionTokenCache (136-136)
🪛 Gitleaks (8.26.0)
packages/clerk-js/src/core/__tests__/tokenCache.spec.ts

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

(jwt)

⏰ Context from checks skipped due to timeout of 90000ms (23)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 13)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Static analysis
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
.changeset/ten-kiwis-cry.md (1)

1-3: LGTM! Empty changeset follows established convention.

This empty changeset correctly signals that no package release is required since the PR only touches test files.

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

191-264: Excellent test coverage for dynamic TTL calculation.

The test structure and logic are well-designed. These tests effectively verify that:

  1. Tokens with short TTL (30s) are properly cached and removed after expiration
  2. Tokens with longer TTL (120s) remain cached before expiration and are removed afterward
  3. The cache correctly calculates expiration based on JWT claims rather than fixed timeouts

The use of fake timers and controlled time advancement provides reliable, deterministic testing of time-based behavior.

Comment on lines +192 to +222
it('calculates expiresIn from JWT exp and iat claims and sets timeout based on calculated TTL', async () => {
const cache = SessionTokenCache;

// Mock Date.now to return a fixed timestamp initially
const initialTime = 1675876730000; // Same as our JWT's iat in milliseconds
vi.spyOn(Date, 'now').mockImplementation(() => initialTime);

// Test with a 30-second TTL
const shortTtlJwt = createJwtWithTtl(30);
const shortTtlToken = new Token({
object: 'token',
id: 'short-ttl',
jwt: shortTtlJwt,
});

const shortTtlKey = { tokenId: 'short-ttl', audience: 'test' };
const shortTtlResolver = Promise.resolve(shortTtlToken);
cache.set({ ...shortTtlKey, tokenResolver: shortTtlResolver });
await shortTtlResolver;

const cachedEntry = cache.get(shortTtlKey);
expect(cachedEntry).toMatchObject(shortTtlKey);

// Advance both the timer and the mocked current time
const advanceBy = 31 * 1000;
vi.advanceTimersByTime(advanceBy);
vi.spyOn(Date, 'now').mockImplementation(() => initialTime + advanceBy);

const cachedEntry2 = cache.get(shortTtlKey);
expect(cachedEntry2).toBeUndefined();
});
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

Fix Date.now mock cleanup to ensure test isolation.

The Date.now mock is not properly restored between test cases, which could cause test isolation issues.

  it('calculates expiresIn from JWT exp and iat claims and sets timeout based on calculated TTL', async () => {
    const cache = SessionTokenCache;

    // Mock Date.now to return a fixed timestamp initially
    const initialTime = 1675876730000; // Same as our JWT's iat in milliseconds
-   vi.spyOn(Date, 'now').mockImplementation(() => initialTime);
+   const dateNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => initialTime);

    // Test with a 30-second TTL
    const shortTtlJwt = createJwtWithTtl(30);
    const shortTtlToken = new Token({
      object: 'token',
      id: 'short-ttl',
      jwt: shortTtlJwt,
    });

    const shortTtlKey = { tokenId: 'short-ttl', audience: 'test' };
    const shortTtlResolver = Promise.resolve(shortTtlToken);
    cache.set({ ...shortTtlKey, tokenResolver: shortTtlResolver });
    await shortTtlResolver;

    const cachedEntry = cache.get(shortTtlKey);
    expect(cachedEntry).toMatchObject(shortTtlKey);

    // Advance both the timer and the mocked current time
    const advanceBy = 31 * 1000;
    vi.advanceTimersByTime(advanceBy);
-   vi.spyOn(Date, 'now').mockImplementation(() => initialTime + advanceBy);
+   dateNowSpy.mockImplementation(() => initialTime + advanceBy);

    const cachedEntry2 = cache.get(shortTtlKey);
    expect(cachedEntry2).toBeUndefined();
+   
+   // Cleanup
+   dateNowSpy.mockRestore();
  });
📝 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
it('calculates expiresIn from JWT exp and iat claims and sets timeout based on calculated TTL', async () => {
const cache = SessionTokenCache;
// Mock Date.now to return a fixed timestamp initially
const initialTime = 1675876730000; // Same as our JWT's iat in milliseconds
vi.spyOn(Date, 'now').mockImplementation(() => initialTime);
// Test with a 30-second TTL
const shortTtlJwt = createJwtWithTtl(30);
const shortTtlToken = new Token({
object: 'token',
id: 'short-ttl',
jwt: shortTtlJwt,
});
const shortTtlKey = { tokenId: 'short-ttl', audience: 'test' };
const shortTtlResolver = Promise.resolve(shortTtlToken);
cache.set({ ...shortTtlKey, tokenResolver: shortTtlResolver });
await shortTtlResolver;
const cachedEntry = cache.get(shortTtlKey);
expect(cachedEntry).toMatchObject(shortTtlKey);
// Advance both the timer and the mocked current time
const advanceBy = 31 * 1000;
vi.advanceTimersByTime(advanceBy);
vi.spyOn(Date, 'now').mockImplementation(() => initialTime + advanceBy);
const cachedEntry2 = cache.get(shortTtlKey);
expect(cachedEntry2).toBeUndefined();
});
it('calculates expiresIn from JWT exp and iat claims and sets timeout based on calculated TTL', async () => {
const cache = SessionTokenCache;
// Mock Date.now to return a fixed timestamp initially
const initialTime = 1675876730000; // Same as our JWT's iat in milliseconds
const dateNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => initialTime);
// Test with a 30-second TTL
const shortTtlJwt = createJwtWithTtl(30);
const shortTtlToken = new Token({
object: 'token',
id: 'short-ttl',
jwt: shortTtlJwt,
});
const shortTtlKey = { tokenId: 'short-ttl', audience: 'test' };
const shortTtlResolver = Promise.resolve(shortTtlToken);
cache.set({ ...shortTtlKey, tokenResolver: shortTtlResolver });
await shortTtlResolver;
const cachedEntry = cache.get(shortTtlKey);
expect(cachedEntry).toMatchObject(shortTtlKey);
// Advance both the timer and the mocked current time
const advanceBy = 31 * 1000;
vi.advanceTimersByTime(advanceBy);
dateNowSpy.mockImplementation(() => initialTime + advanceBy);
const cachedEntry2 = cache.get(shortTtlKey);
expect(cachedEntry2).toBeUndefined();
// Cleanup
dateNowSpy.mockRestore();
});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/__tests__/tokenCache.spec.ts around lines 192 to
222, the Date.now mock is not restored after the test, risking interference with
other tests. To fix this, add a cleanup step to restore the original Date.now
implementation after the test completes, typically by calling
vi.restoreAllMocks() or Date.now.mockRestore() in an afterEach or finally block
to ensure test isolation.

Comment on lines +224 to +263
it('handles tokens with TTL greater than 60 seconds correctly', async () => {
const cache = SessionTokenCache;

// Mock Date.now to return a fixed timestamp initially
const initialTime = 1675876730000; // Same as our JWT's iat in milliseconds
vi.spyOn(Date, 'now').mockImplementation(() => initialTime);

// Test with a 120-second TTL
const longTtlJwt = createJwtWithTtl(120);
const longTtlToken = new Token({
object: 'token',
id: 'long-ttl',
jwt: longTtlJwt,
});

const longTtlKey = { tokenId: 'long-ttl', audience: 'test' };
const longTtlResolver = Promise.resolve(longTtlToken);
cache.set({ ...longTtlKey, tokenResolver: longTtlResolver });
await longTtlResolver;

// Check token is cached initially
const cachedEntry = cache.get(longTtlKey);
expect(cachedEntry).toMatchObject(longTtlKey);

// Advance 90 seconds - token should still be cached
const firstAdvance = 90 * 1000;
vi.advanceTimersByTime(firstAdvance);
vi.spyOn(Date, 'now').mockImplementation(() => initialTime + firstAdvance);

const cachedEntryAfter90s = cache.get(longTtlKey);
expect(cachedEntryAfter90s).toMatchObject(longTtlKey);

// Advance to 121 seconds - token should be removed
const secondAdvance = 31 * 1000;
vi.advanceTimersByTime(secondAdvance);
vi.spyOn(Date, 'now').mockImplementation(() => initialTime + firstAdvance + secondAdvance);

const cachedEntryAfter121s = cache.get(longTtlKey);
expect(cachedEntryAfter121s).toBeUndefined();
});
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

Apply the same mock cleanup pattern for consistency.

This test should follow the same Date.now mock cleanup pattern as the previous test.

  it('handles tokens with TTL greater than 60 seconds correctly', async () => {
    const cache = SessionTokenCache;

    // Mock Date.now to return a fixed timestamp initially
    const initialTime = 1675876730000; // Same as our JWT's iat in milliseconds
-   vi.spyOn(Date, 'now').mockImplementation(() => initialTime);
+   const dateNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => initialTime);

    // Test with a 120-second TTL
    const longTtlJwt = createJwtWithTtl(120);
    const longTtlToken = new Token({
      object: 'token',
      id: 'long-ttl',
      jwt: longTtlJwt,
    });

    const longTtlKey = { tokenId: 'long-ttl', audience: 'test' };
    const longTtlResolver = Promise.resolve(longTtlToken);
    cache.set({ ...longTtlKey, tokenResolver: longTtlResolver });
    await longTtlResolver;

    // Check token is cached initially
    const cachedEntry = cache.get(longTtlKey);
    expect(cachedEntry).toMatchObject(longTtlKey);

    // Advance 90 seconds - token should still be cached
    const firstAdvance = 90 * 1000;
    vi.advanceTimersByTime(firstAdvance);
-   vi.spyOn(Date, 'now').mockImplementation(() => initialTime + firstAdvance);
+   dateNowSpy.mockImplementation(() => initialTime + firstAdvance);

    const cachedEntryAfter90s = cache.get(longTtlKey);
    expect(cachedEntryAfter90s).toMatchObject(longTtlKey);

    // Advance to 121 seconds - token should be removed
    const secondAdvance = 31 * 1000;
    vi.advanceTimersByTime(secondAdvance);
-   vi.spyOn(Date, 'now').mockImplementation(() => initialTime + firstAdvance + secondAdvance);
+   dateNowSpy.mockImplementation(() => initialTime + firstAdvance + secondAdvance);

    const cachedEntryAfter121s = cache.get(longTtlKey);
    expect(cachedEntryAfter121s).toBeUndefined();
+   
+   // Cleanup
+   dateNowSpy.mockRestore();
  });
📝 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
it('handles tokens with TTL greater than 60 seconds correctly', async () => {
const cache = SessionTokenCache;
// Mock Date.now to return a fixed timestamp initially
const initialTime = 1675876730000; // Same as our JWT's iat in milliseconds
vi.spyOn(Date, 'now').mockImplementation(() => initialTime);
// Test with a 120-second TTL
const longTtlJwt = createJwtWithTtl(120);
const longTtlToken = new Token({
object: 'token',
id: 'long-ttl',
jwt: longTtlJwt,
});
const longTtlKey = { tokenId: 'long-ttl', audience: 'test' };
const longTtlResolver = Promise.resolve(longTtlToken);
cache.set({ ...longTtlKey, tokenResolver: longTtlResolver });
await longTtlResolver;
// Check token is cached initially
const cachedEntry = cache.get(longTtlKey);
expect(cachedEntry).toMatchObject(longTtlKey);
// Advance 90 seconds - token should still be cached
const firstAdvance = 90 * 1000;
vi.advanceTimersByTime(firstAdvance);
vi.spyOn(Date, 'now').mockImplementation(() => initialTime + firstAdvance);
const cachedEntryAfter90s = cache.get(longTtlKey);
expect(cachedEntryAfter90s).toMatchObject(longTtlKey);
// Advance to 121 seconds - token should be removed
const secondAdvance = 31 * 1000;
vi.advanceTimersByTime(secondAdvance);
vi.spyOn(Date, 'now').mockImplementation(() => initialTime + firstAdvance + secondAdvance);
const cachedEntryAfter121s = cache.get(longTtlKey);
expect(cachedEntryAfter121s).toBeUndefined();
});
it('handles tokens with TTL greater than 60 seconds correctly', async () => {
const cache = SessionTokenCache;
// Mock Date.now to return a fixed timestamp initially
const initialTime = 1675876730000; // Same as our JWT's iat in milliseconds
const dateNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => initialTime);
// Test with a 120-second TTL
const longTtlJwt = createJwtWithTtl(120);
const longTtlToken = new Token({
object: 'token',
id: 'long-ttl',
jwt: longTtlJwt,
});
const longTtlKey = { tokenId: 'long-ttl', audience: 'test' };
const longTtlResolver = Promise.resolve(longTtlToken);
cache.set({ ...longTtlKey, tokenResolver: longTtlResolver });
await longTtlResolver;
// Check token is cached initially
const cachedEntry = cache.get(longTtlKey);
expect(cachedEntry).toMatchObject(longTtlKey);
// Advance 90 seconds - token should still be cached
const firstAdvance = 90 * 1000;
vi.advanceTimersByTime(firstAdvance);
dateNowSpy.mockImplementation(() => initialTime + firstAdvance);
const cachedEntryAfter90s = cache.get(longTtlKey);
expect(cachedEntryAfter90s).toMatchObject(longTtlKey);
// Advance to 121 seconds - token should be removed
const secondAdvance = 31 * 1000;
vi.advanceTimersByTime(secondAdvance);
dateNowSpy.mockImplementation(() => initialTime + firstAdvance + secondAdvance);
const cachedEntryAfter121s = cache.get(longTtlKey);
expect(cachedEntryAfter121s).toBeUndefined();
// Cleanup
dateNowSpy.mockRestore();
});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/__tests__/tokenCache.spec.ts around lines 224 to
263, the test mocks Date.now multiple times but does not restore the original
implementation after the test. To fix this, add a cleanup step to restore the
original Date.now mock after the test completes, using vi.restoreAllMocks() or a
similar method, ensuring consistency with other tests that mock Date.now.

@jacekradko
Copy link
Member

Looks good. The test cleanup suggestions from Coderabbit would be nice to implement

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.

4 participants