Testing the Auth Store
Relevant source files
The following files were used as context for generating this wiki page:
The testing suite for the Auth Store ensures the robust management of JWT access tokens, automated background refresh logic, and concurrent request handling within the CellarNode authentication system. These tests validate that the store correctly maintains internal state, schedules token renewals before expiration, and provides a reliable interface for the AuthClient and AuthApi modules.
Testing is primarily conducted using Vitest, utilizing features such as fake timers to simulate time passage for token expiry and mocked fetch calls to simulate network interactions with the authentication backend.
Sources: tests/auth-store.test.ts:4-15, vitest.config.ts:1-6
Core Token Management Logic
The Auth Store is responsible for the basic lifecycle of an access token: storage, retrieval, and removal. Tests verify that the store initializes in a clean state and correctly updates its internal accessToken variable through public methods.
State Transitions
The following diagram illustrates the primary state transitions verified by the test suite:
The diagram shows how the store transitions from an empty state to an active state and how it handles token invalidation or refresh failures.
Sources: src/auth-store.ts:41-65, tests/auth-store.test.ts:17-36
Key Methods and Validation
| Method | Description | Test Validation |
|---|---|---|
getAccessToken() | Returns the current token or null. | Verified to return null initially and the correct string after being set. |
hasAccessToken() | Returns boolean existence of token. | Verified to toggle correctly between true and false. |
setAccessToken() | Stores token and schedules refresh. | Verified to store the token and trigger background timers. |
clearAccessToken() | Nullifies token and cancels timers. | Verified to clear state and ensure no further refresh attempts occur. |
Sources: src/types.ts:54-60, tests/auth-store.test.ts:17-36
Background Refresh and Timers
A critical feature of the Auth Store is its ability to automatically refresh tokens before they expire. This is governed by a refreshBuffer, which determines how many seconds before expiry the refresh request should be sent.
Refresh Scheduling Flow
The store calculates a delay based on the expiresIn value provided during token setting and the refreshBuffer configuration.
The sequence diagram demonstrates the timing logic where the store waits until the exact buffer threshold before initiating a network request.
Sources: src/auth-store.ts:10-18, tests/auth-store.test.ts:38-60
Concurrency and Deduplication
To prevent redundant network traffic, the Auth Store implements deduplication for concurrent refresh requests. If ensureAccessToken(true) is called multiple times while a refresh is already in progress, the store returns the same pending promise to all callers.
Deduplication Logic Test
Tests verify that even if multiple components request a token simultaneously, the fetch call to the refresh endpoint is only executed once.
This flowchart represents the logic in ensureAccessToken that handles multiple simultaneous requests for a valid token.
Sources: src/auth-store.ts:70-76, tests/auth-store.test.ts:62-79
Error Handling and Resiliency
Tests cover various failure scenarios to ensure the store fails gracefully and maintains security by clearing invalid session data.
- Refresh Failure: If the
/auth/refreshendpoint returns a non-OK status (e.g., 401 Unauthorized), the store clears the current access token and returnsnull. - Timer Cancellation: When
clearAccessTokenis called manually (e.g., during logout), any scheduled background refresh timers are explicitly cleared to prevent memory leaks or unexpected network activity. - Extraction Failures: If the API response does not contain a recognizable token format, the store handles the error and treats the refresh as a failure.
Sources: src/auth-store.ts:20-40, tests/auth-store.test.ts:88-112
Testing Infrastructure Configuration
The testing environment is configured via vitest.config.ts to include all files matching the pattern __tests__/**/*.test.ts.
Mock Environment Setup
In auth-store.test.ts, the following setup is used for every test:
vi.useFakeTimers(): Allows manual control oversetTimeoutfor testing expiry.global.fetch = vi.fn(): Replaces the native fetch API with a mock to intercept outgoing requests to thebaseUrl.
Sources: vitest.config.ts:1-6, tests/auth-store.test.ts:5-15
Testing the Auth Store is essential for ensuring that the CellarNode dashboard maintains a persistent and secure authenticated session. By validating timing logic, concurrent request handling, and error states, the suite guarantees that the AuthStore acts as a reliable source of truth for the rest of the application.