| 1 | import { getSecureID } from "./getSecureID"; |
| 2 | |
| 3 | // Mock the crypto.randomUUID function |
| 4 | const mockRandomUUID = jest.fn(); |
| 5 | global.crypto = { |
| 6 | ...global.crypto, |
| 7 | randomUUID: mockRandomUUID, |
| 8 | }; |
| 9 | |
| 10 | describe("getSecureID", () => { |
| 11 | beforeEach(() => { |
| 12 | // Reset the static property before each test |
| 13 | (getSecureID as any).uuid = undefined; |
| 14 | |
| 15 | // Reset the mock implementation |
| 16 | mockRandomUUID.mockReset(); |
| 17 | // Setup a mock implementation that returns a fixed value for testing |
| 18 | mockRandomUUID.mockReturnValue("test-uuid-1234"); |
| 19 | }); |
| 20 | |
| 21 | test("should generate a UUID on first call", () => { |
| 22 | const result = getSecureID(); |
| 23 | expect(mockRandomUUID).toHaveBeenCalledTimes(1); |
| 24 | expect(result).toBe("<!-- SID: test-uuid-1234 -->"); |
| 25 | }); |
| 26 | |
| 27 | test("should reuse the same UUID on subsequent calls", () => { |
| 28 | const firstResult = getSecureID(); |
| 29 | const secondResult = getSecureID(); |
| 30 | |
| 31 | // The UUID generation should only happen once |
| 32 | expect(mockRandomUUID).toHaveBeenCalledTimes(1); |
| 33 | |
| 34 | // Both results should be identical |
| 35 | expect(firstResult).toBe(secondResult); |
| 36 | expect(firstResult).toBe("<!-- SID: test-uuid-1234 -->"); |
| 37 | }); |
| 38 | |
| 39 | test("should maintain the same UUID across different test cases if not reset", () => { |
| 40 | // Don't reset the UUID here to test persistence |
| 41 | (getSecureID as any).uuid = "persistent-uuid"; |
| 42 | |
| 43 | const result = getSecureID(); |
| 44 | |
| 45 | // No new UUID should be generated |
| 46 | expect(mockRandomUUID).not.toHaveBeenCalled(); |
| 47 | expect(result).toBe("<!-- SID: persistent-uuid -->"); |
| 48 | }); |
| 49 | }); |