// @vitest-environment node import { describe, it, expect, vi, beforeEach } from 'vitest' // Mock asAdmin before importing the module under test const mockInsert = vi.fn() const mockValues = vi.fn().mockResolvedValue([]) vi.mock('@/lib/db/with-user', () => ({ asAdmin: vi.fn().mockImplementation(fn => fn({ insert: mockInsert.mockReturnValue({ values: mockValues }), }) ), })) import { createInAppNotifications } from '@/lib/notifications/in-app' describe('createInAppNotifications', () => { beforeEach(() => { vi.clearAllMocks() mockInsert.mockReturnValue({ values: mockValues }) mockValues.mockResolvedValue([]) }) it('inserts once per recipient', async () => { const { created } = await createInAppNotifications([ { userId: 'u1', title: 'New incident', link: '/hse/incidents/i1', incidentId: 'i1' }, { userId: 'u2', title: 'New incident', link: '/hse/incidents/i1', incidentId: 'i1' }, ]) expect(created).toBe(2) expect(mockValues).toHaveBeenCalledTimes(2) }) it('skips entries missing userId or title', async () => { const { created } = await createInAppNotifications([ { userId: '', title: 'x' }, { userId: 'u1', title: '' }, ]) expect(created).toBe(0) expect(mockValues).not.toHaveBeenCalled() }) it('counts only successful inserts; failed insert is caught', async () => { mockValues.mockRejectedValueOnce(new Error('DB error')) const { created } = await createInAppNotifications([ { userId: 'u1', title: 'x' }, ]) expect(created).toBe(0) }) it('deduplicates same userId+title+incidentId', async () => { const { created } = await createInAppNotifications([ { userId: 'u1', title: 'same', incidentId: 'i1' }, { userId: 'u1', title: 'same', incidentId: 'i1' }, ]) expect(created).toBe(1) expect(mockValues).toHaveBeenCalledTimes(1) }) })