Testing with Vitest
Relevant source files
The following files were used as context for generating this wiki page:
Testing within the @cellarnode/auth project is powered by Vitest, a Vite-native testing framework. The test suite is designed to ensure the reliability of the authentication logic, including token management, API interactions, and access control. It covers core modules such as the AuthStore, AuthClient, and AuthApi, utilizing extensive mocking of the global fetch API and timers to simulate network behavior and token expiration cycles.
Sources: package.json:57, vitest.config.ts:1-7
Test Configuration and Environment
The testing environment is configured via vitest.config.ts. The configuration specifies that the test runner should include all .test.ts files located within the __tests__ directory.
Sources: vitest.config.ts:4-6
Available Test Scripts
The project defines two primary scripts for interacting with the test suite:
| Script | Command | Description |
|---|---|---|
test | vitest run | Executes the test suite once. |
test:watch | vitest | Runs the test suite in watch mode for development. |
Sources: package.json:30-31
Unit Testing Modules
Auth Client Testing
Tests for the AuthClient focus on the injection of authentication headers and the handling of HTTP failure modes. The suite verifies that the Bearer token is correctly appended to requests unless explicitly skipped via the skipAuth option.
The client testing logic includes:
- Token Injection: Ensures
Authorization: Bearer <token>is sent. - Base URL Prepension: Verifies paths are correctly joined with the configured base URL.
- Retry Logic: Confirms that a
401 Unauthorizedstatus triggers exactly one refresh attempt and a subsequent retry. - Error Handling: Validates that
AuthErroris thrown with appropriate status codes and metadata (e.g.,remainingAttempts).
Sources: __tests__/auth-client.test.ts:21-125
Auth Store Testing
The AuthStore tests validate the lifecycle of an access token, particularly its storage and automatic renewal. These tests rely on vi.useFakeTimers() to simulate the passage of time without actual waiting.
Key scenarios tested:
- Persistence: Setting, getting, and clearing tokens.
- Scheduled Refresh: Verifies that a background refresh is triggered based on the
refreshBufferbefore the token expires. - Concurrency: Ensures that multiple simultaneous requests for an expired token result in a single deduplicated refresh call.
Sources: __tests__/auth-store.test.ts:10-100
Auth API Testing
Testing for createAuthApi validates the abstraction layer over the raw HTTP client. It ensures that specific endpoints (e.g., /auth/register, /auth/verify-otp) are called with the correct payloads and that the resulting data is properly stored.
Sources: __tests__/auth-api.test.ts:48-61
Auth Guard Testing
The auth-guard.test.ts file provides functional verification for the validateUserType utility. It tests the system's ability to distinguish between different user roles (producer, importer, admin) to prevent unauthorized portal access.
Sources: __tests__/auth-guard.test.ts:14-25
Mocking Strategies
To isolate logic, the test suite makes heavy use of Vitest's mocking utilities:
- Fetch Mocking:
global.fetchis replaced withvi.fn()to capture outgoing requests and return predefined JSON responses. - Store Mocking: Functional mocks of the
AuthStoreare created to track calls tosetAccessTokenandclearAccessToken. - Timer Mocking:
vi.advanceTimersByTime()is used to test time-dependent logic like the 60-second refresh buffer.
Sources: __tests__/auth-client.test.ts:6-19, __tests__/auth-store.test.ts:6-10
Summary
The testing architecture ensures that every layer of the authentication flow—from storage to API communication and guardrails—is verified. By utilizing Vitest's speed and powerful mocking capabilities, the project maintains high confidence in token reliability and security enforcement across different user types.