Back to Repositories

Testing Authentication Token Management in OpenHands Frontend

This test suite validates the authentication service functionality in the OpenHands frontend application, focusing on token management and storage operations. The tests ensure proper token retrieval and local storage interactions, critical for maintaining user authentication state.

Test Coverage Overview

The test coverage focuses on the core authentication token management functionality:

  • Token retrieval from localStorage
  • Proper interaction with Storage.prototype methods
  • Mock implementation of storage operations
  • Verification of token access patterns

Implementation Analysis

The testing approach utilizes Vitest’s mocking capabilities to isolate storage operations. The implementation leverages modern TypeScript features with mock functions and type assertions, ensuring type safety throughout the test suite.

Key patterns include mock function setup, storage prototype interception, and assertion chaining.

Technical Details

Testing tools and configuration:

  • Vitest as the testing framework
  • TypeScript for type-safe testing
  • Mock implementations of Storage prototype
  • BeforeEach hooks for test isolation
  • Expect assertions for verification

Best Practices Demonstrated

The test suite exemplifies several testing best practices:

  • Clear test organization using describe blocks
  • Proper test isolation through beforeEach cleanup
  • Mock implementation of browser APIs
  • Type-safe testing with TypeScript
  • Focused test cases with single responsibility

all-hands-ai/openhands

frontend/__tests__/services/auth.test.ts

            
import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";
import { getToken } from "../../src/services/auth";

Storage.prototype.getItem = vi.fn();
Storage.prototype.setItem = vi.fn();

describe("Auth Service", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  describe("getToken", () => {
    it("should fetch and return a token", () => {
      (Storage.prototype.getItem as Mock).mockReturnValue("newToken");

      const data = getToken();
      expect(localStorage.getItem).toHaveBeenCalledWith("token"); // Used to set Authorization header
      expect(data).toEqual("newToken");
    });
  });
});