/** * OmniCard AI (CRMmp) - 移动端多媒体离线缓存持久化策略单元测试 * 严格遵循 TDD 规范 */ describe('Point 64 (P2): 移动端名片离线多媒体缓存与本地持久化策略 (Media Cache)', () => { let cacheMod: any; let storageMap: Record; beforeEach(() => { storageMap = {}; (global as any).uni = { getStorageSync: jest.fn((key: string) => storageMap[key] || ''), setStorageSync: jest.fn((key: string, val: string) => { storageMap[key] = String(val); }), removeStorageSync: jest.fn((key: string) => { delete storageMap[key]; }), }; // @ts-ignore cacheMod = require('../../../mpuniapp/common/media-cache.uts'); cacheMod.clearAllMediaCache(); }); afterEach(() => { delete (global as any).uni; }); describe('1. 缓存存储与命中获取 (saveMediaToCache & getCachedMedia)', () => { const remoteUrl = 'https://cdn.omnicard.ai/avatars/alex.png'; const localPath = '_doc/cache/avatars/alex.png'; it('写入缓存后应能成功命中并返回本地文件路径', () => { cacheMod.saveMediaToCache(remoteUrl, localPath, 24); // 24小时有效 const hit = cacheMod.getCachedMedia(remoteUrl); expect(hit).toBeDefined(); expect(hit.localPath).toBe(localPath); expect(hit.isExpired).toBe(false); }); it('未缓存的 URL 查询应返回 null', () => { const miss = cacheMod.getCachedMedia('https://cdn.omnicard.ai/not-cached.png'); expect(miss).toBeNull(); }); }); describe('2. 缓存过期淘汰机制 (pruneExpiredMediaCache)', () => { it('已过期的缓存条目应被自动清理淘汰', () => { const oldUrl = 'https://cdn.omnicard.ai/old.png'; cacheMod.saveMediaToCache(oldUrl, '_doc/old.png', -1); // 传入负数表示已过期 const beforePrune = cacheMod.getCachedMedia(oldUrl); expect(beforePrune.isExpired).toBe(true); const prunedCount = cacheMod.pruneExpiredMediaCache(); expect(prunedCount).toBe(1); // 清理后再次获取应为 null expect(cacheMod.getCachedMedia(oldUrl)).toBeNull(); }); }); describe('3. 缓存容量上限保护', () => { it('应提供当前缓存条目数量统计', () => { cacheMod.saveMediaToCache('https://cdn.omnicard.ai/1.png', '_doc/1.png'); cacheMod.saveMediaToCache('https://cdn.omnicard.ai/2.png', '_doc/2.png'); const stats = cacheMod.getMediaCacheStats(); expect(stats.totalEntries).toBe(2); }); }); });