oh-my-muse/muse-admin/vitest.setup.ts
lili 3585219637
Some checks failed
Backend Maven CI / backend-local (push) Has been cancelled
feat(mvp): 收束1.0.0线A交付闭环
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 10:52:10 -07:00

54 lines
1.5 KiB
TypeScript
Raw 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.

/** 创建测试用内存 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 默认不再提供可直接访问的 localStoragehappy-dom 在当前组合下也可能未挂载。
// 这里统一补齐浏览器存储对象,避免全仓单测因环境缺口假红。
installStorage('localStorage');
installStorage('sessionStorage');