/** @jest-environment node */ import { createBrowserUuid } from '@/lib/browser-uuid' import { z } from 'zod' const cryptoDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'crypto')! afterEach(() => Object.defineProperty(globalThis, 'crypto', cryptoDescriptor)) test('generates valid UUID v4 values without relying on randomUUID', () => { const original = globalThis.crypto Object.defineProperty(globalThis, 'crypto', { configurable: true, value: { getRandomValues: original.getRandomValues.bind(original), randomUUID: undefined } }) const ids = Array.from({ length: 100 }, () => createBrowserUuid()) expect(new Set(ids).size).toBe(100) for (const id of ids) { expect(id).toMatch(/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/); expect(z.string().uuid().safeParse(id).success).toBe(true) } }) test('sets the UUID version and variant without discarding the remaining random bits', () => { Object.defineProperty(globalThis, 'crypto', { configurable: true, value: { getRandomValues: (bytes: Uint8Array) => bytes.fill(255) } }) expect(createBrowserUuid()).toBe('ffffffff-ffff-4fff-bfff-ffffffffffff') }) test.each([undefined, {}])('missing secure randomness reports a clear error and never creates a weak identifier', value => { Object.defineProperty(globalThis, 'crypto', { configurable: true, value }) expect(createBrowserUuid).toThrow('当前浏览器无法生成请求编号,请更新浏览器后再试') })