import { describe, expect, it } from 'bun:test' import type { CacheOperation } from '../src' import { createMemoryCache, onCacheOperation } from '../src' import { cacheOperationChannel } from '../src/observer' describe('cache operation observer', () => { it('publishes nothing and reports no subscribers until one is attached', async () => { expect(cacheOperationChannel.hasSubscribers).toBe(false) const cache = createMemoryCache() await cache.set('quiet', 1) expect(await cache.get('quiet')).toBe(1) }) it('reports hits, misses, writes and removals with their keys', async () => { const seen: CacheOperation[] = [] const stop = onCacheOperation(operation => seen.push(operation)) try { const cache = createMemoryCache() expect(await cache.get('absent')).toBeUndefined() await cache.set('present', 'value', 30) expect(await cache.get('present')).toBe('value') expect(await cache.remember('computed', 60, () => 42)).toBe(42) expect(await cache.remember('computed', 60, () => 43)).toBe(42) await cache.del('present') expect(seen.map(({ type, key }) => `${type}:${key}`)).toEqual([ 'miss:absent', 'write:present', 'hit:present', 'miss:computed', 'hit:computed', 'forget:present', ]) expect(seen[1]!.ttl).toBe(30) expect(typeof seen[3]!.durationMs).toBe('number') } finally { stop() } expect(cacheOperationChannel.hasSubscribers).toBe(false) }) })