Some checks failed
Backend Maven CI / backend-local (push) Has been cancelled
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
54 lines
1.5 KiB
TypeScript
54 lines
1.5 KiB
TypeScript
/** 创建测试用内存 Storage;仅用于 Vitest 环境,不影响生产浏览器存储实现。 */
|
||
function createMemoryStorage(): Storage {
|
||
const store = new Map<string, string>();
|
||
|
||
return {
|
||
get length() {
|
||
return store.size;
|
||
},
|
||
clear() {
|
||
store.clear();
|
||
},
|
||
getItem(key: string) {
|
||
return store.has(key) ? store.get(key)! : null;
|
||
},
|
||
key(index: number) {
|
||
return Array.from(store.keys())[index] ?? null;
|
||
},
|
||
removeItem(key: string) {
|
||
store.delete(key);
|
||
},
|
||
setItem(key: string, value: string) {
|
||
store.set(key, String(value));
|
||
},
|
||
};
|
||
}
|
||
|
||
/** 同时挂到 window 与 globalThis,兼容直接访问 localStorage 的历史测试。 */
|
||
function installStorage(name: 'localStorage' | 'sessionStorage') {
|
||
const existing =
|
||
typeof window !== 'undefined'
|
||
? (window[name] as Storage | undefined)
|
||
: undefined;
|
||
const storage = existing ?? createMemoryStorage();
|
||
|
||
if (typeof window !== 'undefined') {
|
||
Object.defineProperty(window, name, {
|
||
configurable: true,
|
||
value: storage,
|
||
writable: true,
|
||
});
|
||
}
|
||
|
||
Object.defineProperty(globalThis, name, {
|
||
configurable: true,
|
||
value: storage,
|
||
writable: true,
|
||
});
|
||
}
|
||
|
||
// Node 26 默认不再提供可直接访问的 localStorage;happy-dom 在当前组合下也可能未挂载。
|
||
// 这里统一补齐浏览器存储对象,避免全仓单测因环境缺口假红。
|
||
installStorage('localStorage');
|
||
installStorage('sessionStorage');
|