-
Notifications
You must be signed in to change notification settings - Fork 361
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
base: main
Are you sure you want to change the base?
Conversation
🦋 Changeset detectedLatest commit: 53cdf34 The changes in this PR will be included in the next version bump. This PR includes changesets to release 0 packagesWhen 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 |
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
📝 WalkthroughWalkthroughA new empty changeset file Suggested labels
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 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
📒 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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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
Preferunknown
overany
for performance
Use type-only imports:import type { ... }
Use branded types for domain safety
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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:
- Tokens with short TTL (30s) are properly cached and removed after expiration
- Tokens with longer TTL (120s) remain cached before expiration and are removed afterward
- 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.
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(); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ 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.
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.
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(); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ 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.
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.
Looks good. The test cleanup suggestions from Coderabbit would be nice to implement |
Improves the token cache by adding dynamic TTL calculation based on JWT
exp
andiat
claims.This change:
Summary by CodeRabbit