import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { notifications, notify } from '../src/lib/notifications.svelte'; function clear(): void { for (const entry of [...notifications.entries]) notifications.dismiss(entry.id); } describe('notification store', () => { beforeEach(() => { vi.useFakeTimers(); clear(); }); afterEach(() => { clear(); vi.useRealTimers(); }); it('adds an entry per variant with increasing ids', () => { const ids = [notify.success('saved'), notify.error('failed'), notify.warning('careful'), notify.info('fyi')]; expect(new Set(ids).size).toBe(4); expect([...ids].sort((a, b) => a - b)).toEqual(ids); expect(notifications.entries.map((entry) => [entry.variant, entry.message])).toEqual([ ['success', 'saved'], ['error', 'failed'], ['warning', 'careful'], ['info', 'fyi'], ]); }); it('removes an entry once its duration has passed, and only that entry', () => { notify.info('short', 1000); notify.info('long', 5000); vi.advanceTimersByTime(999); expect(notifications.entries).toHaveLength(2); vi.advanceTimersByTime(1); expect(notifications.entries.map((entry) => entry.message)).toEqual(['long']); vi.advanceTimersByTime(4000); expect(notifications.entries).toHaveLength(0); }); it('uses a five second default and keeps an entry with duration 0 until it is dismissed', () => { const timed = notify.success('default duration'); const sticky = notify.error('sticky', 0); expect(notifications.entries.find((entry) => entry.id === timed)?.duration).toBe(5000); vi.advanceTimersByTime(60_000); expect(notifications.entries.map((entry) => entry.id)).toEqual([sticky]); notify.dismiss(sticky); expect(notifications.entries).toHaveLength(0); }); it('dismissing early cancels the timer, and dismissing an unknown id is harmless', () => { const id = notify.info('dismissed early', 1000); notifications.dismiss(id); expect(vi.getTimerCount()).toBe(0); expect(() => notifications.dismiss(9999)).not.toThrow(); expect(notifications.entries).toHaveLength(0); }); });