Files
eSIM-Tools/tests/setup.js
Abner c6bf3a0238 🔧 chore: 升级 js-yaml 依赖并优化测试环境的加密随机数生成
- `tests/setup.js` 中 `getRandomValues` 模拟改用 Node.js `crypto.randomBytes` 填充,替代基于 `Math.random` 的不安全随机源,确保测试环境使用 CSPRNG 生成随机值
- 新增 `crypto` 模块导入,移除手动循环填充逻辑,简化代码实现并降低随机数偏差风险
- 将 `js-yaml@3` 补丁版本从 3.15.0 升级至 3.15.1,`js-yaml@4` 从 4.3.0 升级至 4.3.1
- 同步更新 `package-lock.json`,保持依赖锁文件与 `package.json` 声明一致
2026-08-18 18:33:01 +08:00

95 lines
2.2 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Jest 测试设置文件
*/
import { randomBytes } from 'crypto';
// 导入 Jest DOM 扩展
import '@testing-library/jest-dom';
// 设置全局测试超时
jest.setTimeout(10000);
// 模拟 localStorage
const localStorageMock = {
getItem: jest.fn(),
setItem: jest.fn(),
removeItem: jest.fn(),
clear: jest.fn(),
};
global.localStorage = localStorageMock;
// 模拟 sessionStorage
const sessionStorageMock = {
getItem: jest.fn(),
setItem: jest.fn(),
removeItem: jest.fn(),
clear: jest.fn(),
};
global.sessionStorage = sessionStorageMock;
// 模拟 fetch API
global.fetch = jest.fn();
// 模拟 crypto API提供 webcrypto.subtle 接口)
// getRandomValues 使用 Node CSPRNG 填充,避免测试环境引入不安全的随机源
const webcryptoMock = {
getRandomValues: (arr) => {
arr.set(randomBytes(arr.length));
return arr;
},
subtle: {
digest: jest.fn(() => Promise.resolve(new ArrayBuffer(32)))
}
};
global.crypto = webcryptoMock;
globalThis.crypto = webcryptoMock;
if (typeof window !== 'undefined') {
window.crypto = webcryptoMock;
}
// 模拟 navigator.clipboard
global.navigator.clipboard = {
writeText: jest.fn(() => Promise.resolve()),
readText: jest.fn(() => Promise.resolve(''))
};
// 模拟 IntersectionObserver
global.IntersectionObserver = class IntersectionObserver {
constructor() {}
disconnect() {}
observe() {}
unobserve() {}
takeRecords() {
return [];
}
};
// 模拟 Service Worker
global.navigator.serviceWorker = {
register: jest.fn(() => Promise.resolve({
installing: null,
waiting: null,
active: null,
addEventListener: jest.fn()
}))
};
// Polyfill: TextEncoderNode 环境下用于 PKCE 生成)
if (typeof global.TextEncoder === 'undefined') {
const { TextEncoder } = require('util');
global.TextEncoder = TextEncoder;
}
// Polyfill: document.execCommand降级复制方案
if (typeof document.execCommand === 'undefined') {
document.execCommand = jest.fn(() => true);
}
// 清理每个测试后的模拟
afterEach(() => {
jest.clearAllMocks();
localStorageMock.getItem.mockClear();
localStorageMock.setItem.mockClear();
localStorageMock.removeItem.mockClear();
localStorageMock.clear.mockClear();
});