Files
syops/frontend/src/shared/utils/id.test.ts
T
hugo c7770c12d2 fix(admin): 兼容 HTTP 内网下 crypto.randomUUID 不可用
订单模板编辑页在非 secure context 白屏;统一经 createRandomUuid 降级生成会话与 operation_id。
2026-09-08 15:24:57 +08:00

35 lines
1.1 KiB
TypeScript

/**
* shared/utils/id.test.ts
* 用途:校验 createRandomUuid 在缺少 randomUUID 时仍可生成可用 ID。
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createRandomUuid } from './id';
describe('createRandomUuid', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it('uses crypto.randomUUID when available', () => {
// 断言:安全上下文走原生 API。
vi.stubGlobal('crypto', {
randomUUID: () => '11111111-2222-4333-8444-555555555555',
});
expect(createRandomUuid()).toBe('11111111-2222-4333-8444-555555555555');
});
it('falls back when randomUUID is missing (HTTP non-secure context)', () => {
// 断言:模拟内网 HTTP,无 randomUUID 也不抛错,且返回非空串。
vi.stubGlobal('crypto', {
getRandomValues: (bytes: Uint8Array) => {
for (let i = 0; i < bytes.length; i += 1) bytes[i] = i;
return bytes;
},
});
const value = createRandomUuid();
expect(value).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
);
});
});