|
| 1 | +import { createMockRequest } from '@sim/testing' |
| 2 | +import { asyncJobsMock, asyncJobsMockFns } from '@sim/testing/mocks/async-jobs.mock' |
| 3 | +import { authInternalMock, authInternalMockFns } from '@sim/testing/mocks/auth-internal.mock' |
| 4 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' |
| 5 | + |
| 6 | +vi.mock('@/lib/auth/internal', () => authInternalMock) |
| 7 | +vi.mock('@/lib/core/async-jobs', () => asyncJobsMock) |
| 8 | + |
| 9 | +import { GET } from '@/app/api/cron/cleanup-file-versions/route' |
| 10 | + |
| 11 | +const { mockVerifyCronAuth } = authInternalMockFns |
| 12 | + |
| 13 | +const mockEnqueue = asyncJobsMockFns.mockJobQueue.enqueue |
| 14 | + |
| 15 | +function request() { |
| 16 | + return createMockRequest( |
| 17 | + 'GET', |
| 18 | + undefined, |
| 19 | + {}, |
| 20 | + 'http://localhost:3000/api/cron/cleanup-file-versions' |
| 21 | + ) |
| 22 | +} |
| 23 | + |
| 24 | +/** The job id a dispatch was keyed to, as the queue reports it back. */ |
| 25 | +async function dispatchedJobId(): Promise<string> { |
| 26 | + const response = await GET(request()) |
| 27 | + expect(response.status).toBe(200) |
| 28 | + const body = (await response.json()) as { jobId: string } |
| 29 | + return body.jobId |
| 30 | +} |
| 31 | + |
| 32 | +describe('file version cleanup route', () => { |
| 33 | + beforeEach(() => { |
| 34 | + vi.useFakeTimers() |
| 35 | + vi.setSystemTime(new Date('2026-10-01T03:30:00Z')) |
| 36 | + mockVerifyCronAuth.mockReturnValue(null) |
| 37 | + mockEnqueue.mockReset() |
| 38 | + }) |
| 39 | + |
| 40 | + afterEach(() => { |
| 41 | + vi.useRealTimers() |
| 42 | + }) |
| 43 | + |
| 44 | + it('fails the cron invocation when the dispatch cannot be enqueued', async () => { |
| 45 | + mockEnqueue.mockRejectedValueOnce(new Error('queue unavailable')) |
| 46 | + |
| 47 | + const response = await GET(request()) |
| 48 | + |
| 49 | + expect(response.status).toBe(500) |
| 50 | + }) |
| 51 | + |
| 52 | + describe('with a queue that keys each job by the id it is given', () => { |
| 53 | + beforeEach(() => { |
| 54 | + mockEnqueue.mockImplementation( |
| 55 | + async (_type: string, _payload: unknown, options: { jobId: string }) => options.jobId |
| 56 | + ) |
| 57 | + }) |
| 58 | + |
| 59 | + it('dispatches a retry on the same day as the same job', async () => { |
| 60 | + const first = await dispatchedJobId() |
| 61 | + vi.setSystemTime(new Date('2026-10-01T23:59:59.999Z')) |
| 62 | + |
| 63 | + expect(await dispatchedJobId()).toBe(first) |
| 64 | + }) |
| 65 | + |
| 66 | + it('dispatches a new job on the next day', async () => { |
| 67 | + const first = await dispatchedJobId() |
| 68 | + vi.setSystemTime(new Date('2026-10-02T00:00:00.000Z')) |
| 69 | + |
| 70 | + expect(await dispatchedJobId()).not.toBe(first) |
| 71 | + }) |
| 72 | + }) |
| 73 | +}) |
0 commit comments