67 lines
2.0 KiB
TypeScript
67 lines
2.0 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
|
|
const { mockSend, mockFrom } = vi.hoisted(() => ({
|
|
mockSend: vi.fn(),
|
|
mockFrom: vi.fn(),
|
|
}))
|
|
|
|
vi.mock('resend', () => {
|
|
function MockResend() {}
|
|
MockResend.prototype.emails = { send: mockSend }
|
|
return { Resend: MockResend }
|
|
})
|
|
|
|
vi.mock('@/lib/supabase/server', () => ({
|
|
createClient: vi.fn().mockResolvedValue({ from: mockFrom }),
|
|
}))
|
|
|
|
import { sendNewIncidentEmail } from '@/lib/notifications/email'
|
|
|
|
const mockIncidentRow = {
|
|
reported_at: '2026-07-10T09:00:00Z',
|
|
sites: { name: 'SCW1' },
|
|
reporter: { name: 'John Doe' },
|
|
}
|
|
|
|
function setupMocks(recipientData: object[]) {
|
|
mockFrom.mockImplementation((table: string) => {
|
|
if (table === 'users') {
|
|
return {
|
|
select: vi.fn().mockReturnThis(),
|
|
in: vi.fn().mockReturnThis(),
|
|
eq: vi.fn().mockResolvedValue({ data: recipientData, error: null }),
|
|
}
|
|
}
|
|
return {
|
|
select: vi.fn().mockReturnThis(),
|
|
eq: vi.fn().mockReturnThis(),
|
|
single: vi.fn().mockResolvedValue({ data: mockIncidentRow, error: null }),
|
|
}
|
|
})
|
|
}
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
mockSend.mockResolvedValue({ data: { id: 'email-123' }, error: null })
|
|
setupMocks([
|
|
{ email: 'supervisor@setiacorp.com', name: 'Ahmad', role: 'supervisor' },
|
|
{ email: 'hse@setiacorp.com', name: 'Priya', role: 'hse' },
|
|
])
|
|
})
|
|
|
|
describe('sendNewIncidentEmail', () => {
|
|
it('sends email to supervisor and hse users', async () => {
|
|
await sendNewIncidentEmail('inc-001', 'site-001', 'SCW1-202607-0001', 'near_miss')
|
|
expect(mockSend).toHaveBeenCalledTimes(1)
|
|
const call = mockSend.mock.calls[0][0]
|
|
expect(call.to).toEqual(expect.arrayContaining(['supervisor@setiacorp.com', 'hse@setiacorp.com']))
|
|
expect(call.subject).toContain('SCW1-202607-0001')
|
|
})
|
|
|
|
it('does not send if no recipients', async () => {
|
|
setupMocks([])
|
|
await sendNewIncidentEmail('inc-001', 'site-001', 'SCW1-202607-0001', 'near_miss')
|
|
expect(mockSend).not.toHaveBeenCalled()
|
|
})
|
|
})
|