35 lines
1.1 KiB
TypeScript
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,
|
|
);
|
|
});
|
|
});
|