import { screen, waitFor } from '@testing-library/react'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { jsonResponse, renderUi } from '../test/utils'; import { NotificationBell } from './NotificationBell'; import { toPath, unreadOf, whenWords, type Notice } from './useNotifications'; const note = (id: number, over: Partial = {}): Notice => ({ id, kind: 'run.waiting_approval', title: `Notice ${id}`, body: 'Procure-to-Pay test run', coworker: 'Test generator', run_id: 'r1', link: '/runs/r1', created_at: new Date().toISOString(), ...over, }); function backend(items: Notice[]) { vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { const u = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; if (u.includes('/api/notifications')) return jsonResponse({ items }); return jsonResponse({}); }); } describe('notifications', () => { afterEach(() => { vi.restoreAllMocks(); window.localStorage.clear(); }); it('unread means newer than the last notice the person has seen', () => { const items = [note(5), note(4), note(3)]; expect(unreadOf(items, 0).map((n) => n.id)).toEqual([5, 4, 3]); expect(unreadOf(items, 4).map((n) => n.id)).toEqual([5]); expect(unreadOf(items, 5)).toEqual([]); }); it('links from the server become app paths when they point at this site', () => { expect(toPath('/runs/1')).toEqual({ path: '/runs/1', external: false }); expect(toPath(`${window.location.origin}/runs/1/report?x=1`)).toEqual({ path: '/runs/1/report?x=1', external: false }); expect(toPath('https://elsewhere.example/a')).toEqual({ path: 'https://elsewhere.example/a', external: true }); }); it('says when in plain words', () => { const now = Date.parse('2026-11-04T10:00:00Z'); expect(whenWords('2026-11-04T09:59:40Z', now)).toBe('just now'); expect(whenWords('2026-11-04T09:55:00Z', now)).toBe('5 min ago'); expect(whenWords('2026-11-04T07:00:00Z', now)).toBe('3 h ago'); }); it('the bell names the unread count and lists the notices', async () => { backend([note(3), note(2), note(1)]); window.localStorage.setItem('pw-notify-seen:', '1'); // signed out in this test: the key has no user name renderUi(); const bell = await screen.findByRole('button', { name: 'Notifications, 2 unread' }); bell.click(); expect(await screen.findByRole('list', { name: 'Latest notifications' })).toBeInTheDocument(); expect(screen.getByRole('link', { name: /Notice 3/ })).toHaveAttribute('href', '/runs/r1'); }); it('with nothing new, the bell says so', async () => { backend([]); renderUi(); const bell = await screen.findByRole('button', { name: 'Notifications, 0 unread' }); bell.click(); await waitFor(() => expect(screen.getByTestId('notify-empty')).toHaveTextContent("Nothing new. You'll see it here when a coworker needs you.")); }); });