Files
frontend-miniapp/tests/unit/PersistentJsonCache.spec.ts
lyf 9ea1bfab71
Some checks failed
CI / verify (push) Has been cancelled
同步 sgs-frontend-mobile 源码
2026-07-27 11:26:01 +08:00

43 lines
1.5 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from 'vitest'
import {
readPersistentJsonCache,
writePersistentJsonCache
} from '@/utils/persistentJsonCache'
describe('persistentJsonCache', () => {
const values = new Map<string, string>()
const localStorage = {
getItem: (key: string) => values.get(key) || null,
setItem: (key: string, value: string) => values.set(key, value),
removeItem: (key: string) => values.delete(key),
clear: () => values.clear()
}
beforeEach(() => {
vi.stubGlobal('window', { localStorage })
localStorage.clear()
vi.restoreAllMocks()
})
it('stores and reads a fresh JSON payload', () => {
expect(writePersistentJsonCache('map:manifest', { version: 'v1' }, 60_000)).toBe(true)
expect(readPersistentJsonCache<{ version: string }>('map:manifest')).toEqual({ version: 'v1' })
})
it('keeps expired data only for an explicit stale fallback', () => {
vi.spyOn(Date, 'now').mockReturnValue(1_000)
writePersistentJsonCache('map:floor:L1', ['poi-1'], 100)
vi.spyOn(Date, 'now').mockReturnValue(1_101)
expect(readPersistentJsonCache<string[]>('map:floor:L1')).toBeNull()
expect(readPersistentJsonCache<string[]>('map:floor:L1', true)).toEqual(['poi-1'])
})
it('does not persist an oversized payload', () => {
const largePayload = 'x'.repeat(200 * 1024)
expect(writePersistentJsonCache('map:large', largePayload, 60_000)).toBe(false)
expect(localStorage.getItem('map:large')).toBeNull()
})
})