import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; import { getOrCreateClientId, randomUUID } from './clientId'; const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; beforeEach(() => sessionStorage.clear()); afterEach(() => { sessionStorage.clear(); vi.unstubAllGlobals(); }); describe('getOrCreateClientId', () => { test('generates a UUID on first call and persists it in sessionStorage', () => { const id = getOrCreateClientId(); expect(id).toMatch(UUID_V4); expect(sessionStorage.getItem('minstrel.client_id')).toBe(id); }); test('returns the same id on subsequent calls', () => { const a = getOrCreateClientId(); const b = getOrCreateClientId(); expect(a).toBe(b); }); }); describe('randomUUID', () => { test('still makes an id on a plain-HTTP page, where crypto.randomUUID is missing', () => { const real = globalThis.crypto; vi.stubGlobal('crypto', { getRandomValues: real.getRandomValues.bind(real) }); const a = randomUUID(); const b = randomUUID(); expect(a).toMatch(UUID_V4); expect(b).toMatch(UUID_V4); expect(a).not.toBe(b); }); });