import { describe, it, expect, beforeEach, vi } from 'vitest' import { NextResponse } from 'next/server' interface HeartbeatInput { path: string startedAt: string completedAt: string status: string httpStatus: number | null durationMs: number } const recordCronHeartbeat = vi.fn(async (_input: HeartbeatInput): Promise => {}) const verifyCronSecret = vi.fn((): NextResponse | null => null) vi.mock('@/lib/cron/heartbeat-store', () => ({ recordCronHeartbeat: (input: HeartbeatInput) => recordCronHeartbeat(input), })) vi.mock('@/lib/auth/cron', () => ({ verifyCronSecret: () => verifyCronSecret(), })) vi.mock('@/lib/logger', () => { const child = () => logger const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), child } return { createLogger: () => logger } }) vi.mock('@/lib/errors/get-structured-error', () => ({ errorResponse: () => NextResponse.json({ error: 'boom' }, { status: 500 }), errorResponseFromCode: () => NextResponse.json({ error: 'unauthorized' }, { status: 401 }), })) const { withCronContext } = await import('../with-cron-context') const PATH = '/api/webhooks/dispatch/cron' function request(): Request { return new Request(`http://app:3000${PATH}`, { headers: { authorization: 'Bearer secret' }, }) } beforeEach(() => { recordCronHeartbeat.mockClear() verifyCronSecret.mockClear() verifyCronSecret.mockReturnValue(null) }) /** * The heartbeat is the only evidence that a schedule still runs, so the wiring * — which path, which status, and that an auth rejection is NOT recorded as a * run — is worth asserting directly rather than inferring from the endpoint. */ describe('withCronContext heartbeat', () => { it('records the run under the request path on success', async () => { const handler = withCronContext('cron.webhook_dispatch', async () => NextResponse.json({ ok: true }), ) const response = await handler(request()) expect(response.status).toBe(200) expect(recordCronHeartbeat).toHaveBeenCalledTimes(1) const input = recordCronHeartbeat.mock.calls[0][0] expect(input.path).toBe(PATH) expect(input.status).toBe('ok') expect(input.httpStatus).toBe(200) expect(Number.isFinite(Date.parse(input.startedAt))).toBe(true) expect(Number.isFinite(Date.parse(input.completedAt))).toBe(true) expect(input.durationMs).toBeGreaterThanOrEqual(0) }) it('records a failed run as error so the health body can show it', async () => { const handler = withCronContext('cron.webhook_dispatch', async () => { throw new Error('kaboom') }) const response = await handler(request()) expect(response.status).toBe(500) expect(recordCronHeartbeat).toHaveBeenCalledTimes(1) expect(recordCronHeartbeat.mock.calls[0][0].status).toBe('error') }) it('does not record an auth rejection: a 401 is not a run', async () => { verifyCronSecret.mockReturnValue( NextResponse.json({ error: 'Unauthorized' }, { status: 401 }), ) const handler = withCronContext('cron.webhook_dispatch', async () => NextResponse.json({ ok: true }), ) const response = await handler(request()) expect(response.status).toBe(401) expect(recordCronHeartbeat).not.toHaveBeenCalled() }) it('never fails the cron run when the heartbeat write rejects', async () => { recordCronHeartbeat.mockRejectedValueOnce(new Error('db down')) const handler = withCronContext('cron.webhook_dispatch', async () => NextResponse.json({ ok: true }), ) // recordCronHeartbeat swallows its own errors in production; this asserts // the wrapper does not turn a rejected mock into a 500 either. await expect(handler(request())).resolves.toBeDefined() }) })