uuid.test.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { afterEach, describe, expect, test } from "bun:test"
  2. import { uuid } from "./uuid"
  3. const cryptoDescriptor = Object.getOwnPropertyDescriptor(globalThis, "crypto")
  4. const secureDescriptor = Object.getOwnPropertyDescriptor(globalThis, "isSecureContext")
  5. const randomDescriptor = Object.getOwnPropertyDescriptor(Math, "random")
  6. const setCrypto = (value: Partial<Crypto>) => {
  7. Object.defineProperty(globalThis, "crypto", {
  8. configurable: true,
  9. value: value as Crypto,
  10. })
  11. }
  12. const setSecure = (value: boolean) => {
  13. Object.defineProperty(globalThis, "isSecureContext", {
  14. configurable: true,
  15. value,
  16. })
  17. }
  18. const setRandom = (value: () => number) => {
  19. Object.defineProperty(Math, "random", {
  20. configurable: true,
  21. value,
  22. })
  23. }
  24. afterEach(() => {
  25. if (cryptoDescriptor) {
  26. Object.defineProperty(globalThis, "crypto", cryptoDescriptor)
  27. }
  28. if (secureDescriptor) {
  29. Object.defineProperty(globalThis, "isSecureContext", secureDescriptor)
  30. }
  31. if (!secureDescriptor) {
  32. delete (globalThis as { isSecureContext?: boolean }).isSecureContext
  33. }
  34. if (randomDescriptor) {
  35. Object.defineProperty(Math, "random", randomDescriptor)
  36. }
  37. })
  38. describe("uuid", () => {
  39. test("uses randomUUID in secure contexts", () => {
  40. setCrypto({ randomUUID: () => "00000000-0000-0000-0000-000000000000" })
  41. setSecure(true)
  42. expect(uuid()).toBe("00000000-0000-0000-0000-000000000000")
  43. })
  44. test("falls back in insecure contexts", () => {
  45. setCrypto({ randomUUID: () => "00000000-0000-0000-0000-000000000000" })
  46. setSecure(false)
  47. setRandom(() => 0.5)
  48. expect(uuid()).toBe("8")
  49. })
  50. test("falls back when randomUUID throws", () => {
  51. setCrypto({
  52. randomUUID: () => {
  53. throw new DOMException("Failed", "OperationError")
  54. },
  55. })
  56. setSecure(true)
  57. setRandom(() => 0.5)
  58. expect(uuid()).toBe("8")
  59. })
  60. test("falls back when randomUUID is unavailable", () => {
  61. setCrypto({})
  62. setSecure(true)
  63. setRandom(() => 0.5)
  64. expect(uuid()).toBe("8")
  65. })
  66. })