Files

27 lines
960 B
TypeScript

import { afterEach, describe, expect, it, vi } from 'vitest'
import { createIdempotencyKey } from '../../src/idempotencyKey'
afterEach(() => vi.unstubAllGlobals())
describe('createIdempotencyKey', () => {
it('prefers the native UUID implementation', () => {
const randomUUID = vi.fn(() => 'native-uuid')
vi.stubGlobal('crypto', { randomUUID, getRandomValues: vi.fn() })
expect(createIdempotencyKey()).toBe('native-uuid')
expect(randomUUID).toHaveBeenCalledOnce()
})
it('generates an RFC 4122 UUID v4 when randomUUID is unavailable', () => {
vi.stubGlobal('crypto', { getRandomValues: (bytes: Uint8Array) => bytes.map((_, index) => index) })
expect(createIdempotencyKey()).toBe('00010203-0405-4607-8809-0a0b0c0d0e0f')
})
it('fails explicitly when no secure random source exists', () => {
vi.stubGlobal('crypto', {})
expect(() => createIdempotencyKey()).toThrow('当前浏览器不支持安全随机数')
})
})