|
| 1 | +import { getRandomValues } from "crypto"; |
| 2 | +import { afterEach, beforeEach, describe, expect, test as it, vi } from "vitest"; |
| 3 | + |
| 4 | +describe("randomUUID", () => { |
| 5 | + afterEach(() => { |
| 6 | + vi.resetModules(); |
| 7 | + }); |
| 8 | + |
| 9 | + it("should call native randomUUID when available", async () => { |
| 10 | + const mockUUID = "mocked-uuid"; |
| 11 | + const nativeRandomUUID = vi.fn(() => mockUUID); |
| 12 | + vi.doMock("./randomUUID", () => ({ randomUUID: nativeRandomUUID })); |
| 13 | + |
| 14 | + const { randomUUID } = await import("./index"); |
| 15 | + const uuid = randomUUID(); |
| 16 | + |
| 17 | + expect(nativeRandomUUID).toHaveBeenCalled(); |
| 18 | + expect(uuid).toBe(mockUUID); |
| 19 | + }); |
| 20 | + |
| 21 | + describe("when native randomUUID is not available", () => { |
| 22 | + let randomUUID: any; |
| 23 | + const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; |
| 24 | + |
| 25 | + beforeEach(async () => { |
| 26 | + vi.doMock("./randomUUID", () => ({ randomUUID: undefined })); |
| 27 | + randomUUID = (await import("./index")).randomUUID; |
| 28 | + |
| 29 | + // Simulate crypto.getRandomValues in test, as it's expected to be available |
| 30 | + global.crypto = { |
| 31 | + getRandomValues: getRandomValues, |
| 32 | + } as any; |
| 33 | + }); |
| 34 | + |
| 35 | + it("each generation is unique and matches regex", () => { |
| 36 | + const uuids = new Set(); |
| 37 | + const iterations = 10_000; |
| 38 | + for (let i = 0; i < iterations; i++) { |
| 39 | + const uuid = randomUUID(); |
| 40 | + expect(uuid).toMatch(UUID_REGEX); |
| 41 | + uuids.add(uuid); |
| 42 | + } |
| 43 | + expect(uuids.size).toBe(iterations); |
| 44 | + }); |
| 45 | + }); |
| 46 | +}); |
0 commit comments