|
| 1 | +import type { DevframeMessageEntry } from '@devframes/hub' |
| 2 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' |
| 3 | +import { addToast, dismissToast, useToasts } from './toasts' |
| 4 | + |
| 5 | +function createMessage(id: string, autoDismiss: number | false): DevframeMessageEntry { |
| 6 | + return { |
| 7 | + id, |
| 8 | + message: id, |
| 9 | + level: 'info', |
| 10 | + from: 'browser', |
| 11 | + timestamp: 0, |
| 12 | + autoDismiss, |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +function dismissAllToasts(): void { |
| 17 | + for (const toast of [...useToasts()]) |
| 18 | + dismissToast(toast.id) |
| 19 | +} |
| 20 | + |
| 21 | +describe('toast auto-dismiss', () => { |
| 22 | + beforeEach(() => { |
| 23 | + vi.useFakeTimers() |
| 24 | + dismissAllToasts() |
| 25 | + }) |
| 26 | + |
| 27 | + afterEach(() => { |
| 28 | + dismissAllToasts() |
| 29 | + vi.useRealTimers() |
| 30 | + }) |
| 31 | + |
| 32 | + it('keeps a persistent toast visible until it is explicitly dismissed', () => { |
| 33 | + addToast(createMessage('persistent', false)) |
| 34 | + |
| 35 | + expect(vi.getTimerCount()).toBe(0) |
| 36 | + |
| 37 | + vi.advanceTimersByTime(60_000) |
| 38 | + |
| 39 | + expect(useToasts()).toHaveLength(1) |
| 40 | + |
| 41 | + dismissToast('persistent') |
| 42 | + |
| 43 | + expect(useToasts()).toHaveLength(0) |
| 44 | + }) |
| 45 | + |
| 46 | + it('cancels an existing auto-dismiss timer when its toast becomes persistent', () => { |
| 47 | + addToast(createMessage('updated', 1_000)) |
| 48 | + |
| 49 | + expect(vi.getTimerCount()).toBe(1) |
| 50 | + |
| 51 | + addToast(createMessage('updated', false)) |
| 52 | + |
| 53 | + expect(vi.getTimerCount()).toBe(0) |
| 54 | + |
| 55 | + vi.advanceTimersByTime(60_000) |
| 56 | + |
| 57 | + expect(useToasts()).toHaveLength(1) |
| 58 | + }) |
| 59 | + |
| 60 | + it('continues to auto-dismiss timed toasts', () => { |
| 61 | + addToast(createMessage('timed', 1_000)) |
| 62 | + |
| 63 | + vi.advanceTimersByTime(999) |
| 64 | + expect(useToasts()).toHaveLength(1) |
| 65 | + |
| 66 | + vi.advanceTimersByTime(1) |
| 67 | + expect(useToasts()).toHaveLength(0) |
| 68 | + }) |
| 69 | +}) |
0 commit comments