This commit is contained in:
42
tests/unit/PersistentJsonCache.spec.ts
Normal file
42
tests/unit/PersistentJsonCache.spec.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
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()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user