Something went wrong. Try again.
twinkl.social forked from kandake.africa/twinkl
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import { describe, it, expect, beforeEach, afterEach } from 'vitest';import { createDatabase, type Db } from './db';import { SqliteCache } from './cache';
describe('SqliteCache', () => { let db: Db; let cache: SqliteCache;
beforeEach(() => { db = createDatabase(':memory:'); cache = new SqliteCache(db); });
afterEach(() => { db.close(); });
it('returns undefined for a missing key', async () => { expect(await cache.get('nope')).toBeUndefined(); });
it('stores and retrieves a value', async () => { await cache.set('k', { hello: 'world' }); expect(await cache.get<{ hello: string }>('k')).toEqual({ hello: 'world' }); });
it('overwrites an existing key', async () => { await cache.set('k', 1); await cache.set('k', 2); expect(await cache.get('k')).toBe(2); });
it('expires values after their ttl', async () => { await cache.set('k', 'v', -1); expect(await cache.get('k')).toBeUndefined(); });
it('keeps values without a ttl', async () => { await cache.set('k', 'v'); expect(await cache.get('k')).toBe('v'); });
it('deletes a key', async () => { await cache.set('k', 'v'); await cache.delete('k'); expect(await cache.get('k')).toBeUndefined(); });
it('getOrLoad loads and caches on miss, then serves from cache', async () => { let calls = 0; const load = async () => { calls++; return 'loaded'; }; expect(await cache.getOrLoad('k', 1000, load)).toBe('loaded'); expect(await cache.getOrLoad('k', 1000, load)).toBe('loaded'); expect(calls).toBe(1); });
it('prune removes only expired rows', async () => { await cache.set('fresh', 'v', 10000); await cache.set('stale', 'v', -1); cache.prune(); expect(await cache.get('fresh')).toBe('v'); expect(await cache.get('stale')).toBeUndefined(); });});