calendar-visibility.test.ts3.0 KBView on GitHub
/**
 * Tests for `setCalendars`' reconciliation of `visibleCalendarIds`.
 *
 * `calendar-visible-ids` is a single global localStorage key, so IDs persisted
 * while one Google account was active survive a switch to another. Fanning out
 * `calendar.listEvents` over a stale ID makes Google return 404, which surfaced
 * as a tRPC 500. `setCalendars` must therefore drop any persisted ID that isn't
 * in the freshly-fetched calendar list, and fall back to primary if that empties
 * the set.
 */

import type { CalendarListEntry } from '@/modules/calendar/types/calendar-types';
import { createCalendarSlice } from '@/modules/calendar/store/calendarSlice';

const STORAGE_KEY=[redacted];

/** Drives the slice's `setCalendars` against a plain state object. */
function runSetCalendars(visibleCalendarIds: Set<string>, calendars: CalendarListEntry[]) {
  const state = { calendars: [] as CalendarListEntry[], visibleCalendarIds };
  const set = (updater: (draft: typeof state) => void) => updater(state);
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const slice = createCalendarSlice(set as any, (() => state) as any, {} as any);
  slice.setCalendars(calendars);
  return state;
}

const cal = (id: string, primary = false): CalendarListEntry => ({ id, primary }) as CalendarListEntry;

describe('setCalendars — visibleCalendarIds reconciliation', () => {
  beforeEach(() => localStorage.clear());

  it('drops a persisted ID that belongs to another account', () => {
    const state = runSetCalendars(new Set(['<email>', '<email>']), [
      cal('<email>', true),
    ]);

    expect(Array.from(state.visibleCalendarIds)).toEqual(['<email>']);
    expect(JSON.parse(localStorage.getItem(STORAGE_KEY) as string)).toEqual([
      '<email>',
    ]);
  });

  it('falls back to primary when every persisted ID is stale', () => {
    const state = runSetCalendars(new Set(['<email>']), [
      cal('<email>'),
      cal('<email>', true),
    ]);

    expect(Array.from(state.visibleCalendarIds)).toEqual(['<email>']);
  });

  it('defaults to primary on first load when nothing is persisted', () => {
    const state = runSetCalendars(new Set(), [cal('<email>'), cal('<email>', true)]);

    expect(Array.from(state.visibleCalendarIds)).toEqual(['<email>']);
  });

  it('keeps every ID when all of them are still available', () => {
    const state = runSetCalendars(new Set(['<email>', '<email>']), [
      cal('<email>', true),
      cal('<email>'),
    ]);

    expect(Array.from(state.visibleCalendarIds).sort()).toEqual(['<email>', '<email>']);
    // Unchanged set — no redundant write
    expect(localStorage.getItem(STORAGE_KEY)).toBeNull();
  });

  it('leaves state alone when the calendar list is empty (not yet loaded)', () => {
    const state = runSetCalendars(new Set(['<email>']), []);

    expect(Array.from(state.visibleCalendarIds)).toEqual(['<email>']);
  });
});