api/tests/cache.test.ts

94 lines · 3818 bytes

 1// Unit tests for the cache freshness + serve-stale-on-failure behaviour
 2import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
 3import { wrapFetch, type Storage, type StoredEntry } from '@/lib/cache'
 4
 5const FRESH = 60 // seconds
 6
 7// Minimal in-test storage that stamps the time on set, like the real backends
 8const makeStorage = () => {
 9  const map = new Map<string, StoredEntry>()
10  const storage: Storage = {
11    async get<T>(key: string) {
12      return (map.get(key) as StoredEntry<T>) ?? null
13    },
14    async set<T>(key: string, value: T) {
15      map.set(key, { value, cachedAt: Date.now() })
16    },
17    fetch: async () => {
18      throw new Error('uninit')
19    },
20  }
21  storage.fetch = wrapFetch(storage)
22  return { storage, map }
23}
24
25describe('cache wrapFetch', () => {
26  beforeEach(() => vi.useFakeTimers())
27  afterEach(() => vi.useRealTimers())
28
29  it('miss runs the loader, stores, and returns the value', async () => {
30    const { storage, map } = makeStorage()
31    const loader = vi.fn().mockResolvedValue('v1')
32    expect(await storage.fetch('k', FRESH, loader)).toBe('v1')
33    expect(loader).toHaveBeenCalledTimes(1)
34    expect(map.get('k')).toMatchObject({ value: 'v1' })
35  })
36
37  it('fresh cache is served without touching the loader', async () => {
38    const { storage } = makeStorage()
39    await storage.fetch('k', FRESH, vi.fn().mockResolvedValue('v1'))
40    vi.advanceTimersByTime(30_000) // still inside the window
41    const loader = vi.fn().mockResolvedValue('v2')
42    expect(await storage.fetch('k', FRESH, loader)).toBe('v1')
43    expect(loader).not.toHaveBeenCalled()
44  })
45
46  it('stale cache refreshes and re-stores on success', async () => {
47    const { storage, map } = makeStorage()
48    await storage.fetch('k', FRESH, vi.fn().mockResolvedValue('v1'))
49    vi.advanceTimersByTime(61_000) // past the window
50    const loader = vi.fn().mockResolvedValue('v2')
51    expect(await storage.fetch('k', FRESH, loader)).toBe('v2')
52    expect(loader).toHaveBeenCalledTimes(1)
53    expect(map.get('k')).toMatchObject({ value: 'v2' })
54  })
55
56  it('stale cache falls back to the stale value on failure, without overwriting', async () => {
57    const { storage, map } = makeStorage()
58    await storage.fetch('k', FRESH, vi.fn().mockResolvedValue('v1'))
59    vi.advanceTimersByTime(61_000)
60    const failing = vi.fn().mockRejectedValue(new Error('upstream down'))
61    expect(await storage.fetch('k', FRESH, failing)).toBe('v1')
62    expect(map.get('k')).toMatchObject({ value: 'v1' })
63  })
64
65  it('miss with a failing loader throws and caches nothing', async () => {
66    const { storage, map } = makeStorage()
67    const failing = vi.fn().mockRejectedValue(new Error('boom'))
68    await expect(storage.fetch('k', FRESH, failing)).rejects.toThrow('boom')
69    expect(map.has('k')).toBe(false)
70  })
71
72  it('entries never expire, a year-old value still serves when upstream fails', async () => {
73    const { storage } = makeStorage()
74    await storage.fetch('k', FRESH, vi.fn().mockResolvedValue('v1'))
75    vi.advanceTimersByTime(365 * 24 * 60 * 60 * 1000)
76    const failing = vi.fn().mockRejectedValue(new Error('down'))
77    expect(await storage.fetch('k', FRESH, failing)).toBe('v1')
78  })
79
80  it('an undefined loader result throws instead of caching an empty body', async () => {
81    const { storage, map } = makeStorage()
82    const loader = vi.fn().mockResolvedValue(undefined)
83    await expect(storage.fetch('k', FRESH, loader)).rejects.toThrow()
84    expect(map.has('k')).toBe(false)
85  })
86
87  it('a corrupted undefined cached value is treated as a miss, not served empty', async () => {
88    const { storage, map } = makeStorage()
89    map.set('k', { value: undefined, cachedAt: Date.now() })
90    expect(await storage.fetch('k', FRESH, vi.fn().mockResolvedValue('fresh'))).toBe(
91      'fresh',
92    )
93  })
94})