import { afterEach, describe, expect, it, vi } from 'vitest' import { readDailyHangGoal, writeDailyHangGoal } from './hangGoalStorage.js' function memoryIndexedDB() { const values = new Map() const stores = new Set() const db = { objectStoreNames: { contains: (name) => stores.has(name) }, createObjectStore: (name) => { stores.add(name); return { createIndex() {} } }, close() {}, transaction() { const transaction = { objectStore() { return { get(key) { const request = {} queueMicrotask(() => { request.result = values.get(key) request.onsuccess?.() queueMicrotask(() => transaction.oncomplete?.()) }) return request }, put(value, key) { values.set(key, value) queueMicrotask(() => transaction.oncomplete?.()) }, } }, } return transaction }, } return { open() { const request = { result: db } queueMicrotask(() => { if (!stores.has('routineOverrides')) request.onupgradeneeded?.() request.onsuccess?.() }) return request }, } } afterEach(() => vi.unstubAllGlobals()) describe('daily hanging goal storage', () => { it('reads and writes a local goal without changing the seed', async () => { vi.stubGlobal('indexedDB', memoryIndexedDB()) expect(await readDailyHangGoal()).toBeNull() await writeDailyHangGoal(180) expect(await readDailyHangGoal()).toBe(180) }) it('rejects invalid values and unavailable storage', async () => { vi.stubGlobal('indexedDB', memoryIndexedDB()) await expect(writeDailyHangGoal(0)).rejects.toThrow('whole number') await expect(writeDailyHangGoal(2.5)).rejects.toThrow('whole number') vi.stubGlobal('indexedDB', undefined) await expect(readDailyHangGoal()).rejects.toThrow('unavailable') }) it('reports a blocked database upgrade', async () => { vi.stubGlobal('indexedDB', { open() { const request = {} queueMicrotask(() => request.onblocked?.()) return request }, }) await expect(readDailyHangGoal()).rejects.toThrow('blocked by another tab') }) })