Back to Repositories

Testing Local Storage Configuration Retrieval in OpenHands

This test suite validates the getCachedConfig utility function’s handling of local storage data retrieval and JSON parsing. It ensures robust error handling and proper data extraction from browser storage in the OpenHands frontend application.

Test Coverage Overview

The test suite provides comprehensive coverage of the getCachedConfig function’s core functionality and edge cases.

  • Tests null and undefined storage values
  • Validates handling of invalid JSON data
  • Verifies successful parsing of valid JSON objects
  • Covers storage access error scenarios

Implementation Analysis

The testing approach utilizes Vitest’s mocking capabilities to simulate various localStorage states and responses. It employs beforeEach hooks for test isolation and mock resets, while leveraging TypeScript’s type system for mock implementations.

  • Uses vi.fn() for Storage.prototype.getItem mocking
  • Implements Mock type for type-safe mocking
  • Employs expect().toEqual() for precise assertions

Technical Details

  • Testing Framework: Vitest
  • Language: TypeScript
  • Mocking Library: Vitest built-in mocking
  • Test Environment: Node.js simulated DOM
  • Storage Interface: Browser localStorage API

Best Practices Demonstrated

The test suite exemplifies several testing best practices, ensuring maintainable and reliable tests.

  • Proper test isolation through beforeEach cleanup
  • Comprehensive edge case coverage
  • Clear test case descriptions
  • Type-safe mock implementations
  • Single responsibility principle in test cases

all-hands-ai/openhands

frontend/__tests__/utils/storage.test.ts

            
import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";
import { getCachedConfig } from "../../src/utils/storage";

describe("getCachedConfig", () => {
  beforeEach(() => {
    // Clear all instances and calls to constructor and all methods
    Storage.prototype.getItem = vi.fn();
  });

  it("should return an empty object when local storage is null or undefined", () => {
    (Storage.prototype.getItem as Mock).mockReturnValue(null);
    expect(getCachedConfig()).toEqual({});

    (Storage.prototype.getItem as Mock).mockReturnValue(undefined);
    expect(getCachedConfig()).toEqual({});
  });

  it("should return an empty object when local storage has invalid JSON", () => {
    (Storage.prototype.getItem as Mock).mockReturnValue("invalid JSON");
    expect(getCachedConfig()).toEqual({});
  });

  it("should return parsed object when local storage has valid JSON", () => {
    const validJSON = '{"key":"value"}';
    (Storage.prototype.getItem as Mock).mockReturnValue(validJSON);
    expect(getCachedConfig()).toEqual({ key: "value" });
  });
});