Testing the Auth API
Relevant source files
The following files were used as context for generating this wiki page:
Testing the Auth API involves verifying the interactions between the high-level AuthApi interface, the underlying AuthClient responsible for HTTP requests, and the AuthStore which manages token persistence and refreshing. The testing suite ensures that authentication flows—including registration, OTP (One-Time Password) requests, verification, and token management—behave correctly under various network and state conditions.
The test infrastructure uses vitest to mock external dependencies like fetch and verify that the correct headers, request bodies, and error handling logic are applied across the authentication lifecycle. This ensures that framework-agnostic core logic remains robust before being consumed by React UI components.
Architecture and Test Components
The testing environment mimics the production architecture by mocking the three primary pillars of the authentication system.
The relationship between test files and the core authentication modules.
Sources: tests/auth-api.test.ts:1-20, src/index.ts:1-5
Core Testing Modules
| Component | Responsibility in Tests | Relevant File |
|---|---|---|
AuthApi | Orchestrates high-level auth flows (register, login, logout). | src/auth-api.ts |
AuthClient | Handles HTTP transport, Bearer token injection, and 401 retries. | src/auth-client.ts |
AuthStore | Manages in-memory token state and automatic background refreshing. | src/auth-store.ts |
AuthGuard | Validates user permissions based on userType. | src/auth-guard.ts |
Authentication Flow Testing
The tests verify specific API endpoints and the logic applied to responses, particularly regarding token extraction and storage.
OTP and Verification Flow
The verification process is critical as it must handle multiple response formats to find the Access Token.
Sequence of events during an OTP verification test.
Sources: src/auth-api.ts:39-65, tests/auth-api.test.ts:70-85
Token Extraction Logic
Tests verify that extractAccessToken can retrieve tokens from various nested JSON structures, ensuring compatibility with different backend implementations.
| Field Checked | Paths Tested |
|---|---|
| Top Level | accessToken, access_token, token |
| Data Object | data.accessToken, data.access_token |
| Session Object | session.accessToken, session.access_token |
Sources: src/extract-token.ts:1-20, tests/auth-api.test.ts:87-101
Client and Network Testing
The AuthClient tests focus on the middleware-like behavior of the fetch wrapper, including header injection and error handling.
Bearer Token Injection
Tests ensure that the Authorization header is correctly injected unless skipAuth is explicitly set to true.
- Authenticated Request: Tests verify
Authorization: Bearer <token>is present. - Skip Auth: Tests verify the header is absent for endpoints like
/auth/registerand/auth/request-otp.
Sources: tests/auth-client.test.ts:28-56, src/auth-client.ts:33-40
401 Unauthorized Retry Logic
A key feature of the client is its ability to attempt a token refresh upon receiving a 401 status code.
The automated retry logic tested in auth-client.test.ts.
Sources: src/auth-client.ts:54-73, tests/auth-client.test.ts:81-103
Store and State Testing
Tests for AuthStore focus on time-sensitive operations, such as token expiration and scheduled refreshes.
Refresh Scheduling
The store uses a refreshBuffer (default 60 seconds) to trigger a token refresh before the current one expires. Tests use vi.useFakeTimers() to advance time and assert that the refresh call is made at the correct interval.
// Example from Store Tests
it("schedules refresh before expiry", async () => {
store.setAccessToken("tok_123", 120); // expires in 120s, buffer 60s
vi.advanceTimersByTime(59_000); // No refresh yet
await vi.advanceTimersByTimeAsync(2_000); // Refresh fired at 60s
});
Sources: src/auth-store.ts:11-20, tests/auth-store.test.ts:41-62
Concurrent Refresh Deduplication
The store is tested to ensure that if multiple components request a token simultaneously (ensureAccessToken(true)), only one network request is dispatched.
Sources: src/auth-store.ts:74-80, tests/auth-store.test.ts:64-81
Error Model Testing
Tests validate that AuthError objects contain the necessary metadata for the UI to display helpful messages.
| Property | Description | Source |
|---|---|---|
status | HTTP status code (e.g., 400, 401, 500) | src/types.ts:40 |
code | Machine-readable error code (e.g., OTP_INVALID) | src/types.ts:41 |
remainingAttempts | Optional count of remaining OTP attempts | src/types.ts:43 |
Sources: src/types.ts:38-48, tests/auth-client.test.ts:121-143
Conclusion
Testing the Auth API ensures the reliability of the core authentication logic by validating the interplay between network requests, state management, and error handling. By strictly testing the AuthClient's retry mechanisms and the AuthStore's refresh scheduling, the project maintains a seamless authentication experience that is resilient to token expiration and common API errors.