|
| 1 | +/** @vitest-environment node */ |
| 2 | +import { NextRequest } from 'next/server' |
| 3 | +import { beforeEach, describe, expect, it, vi } from 'vitest' |
| 4 | + |
| 5 | +const mocks = vi.hoisted(() => ({ |
| 6 | + fetch: vi.fn(), |
| 7 | + get: vi.fn(), |
| 8 | + set: vi.fn(), |
| 9 | +})) |
| 10 | +vi.mock('@/lib/auth', () => ({ getSession: async () => ({ user: { id: 'test-user' } }) })) |
| 11 | +vi.mock('@/lib/core/rate-limiter/route-helpers', () => ({ |
| 12 | + enforceUserRateLimit: async () => null, |
| 13 | +})) |
| 14 | +vi.mock('@/lib/api/server', () => ({ |
| 15 | + parseRequest: async () => ({ |
| 16 | + success: true, |
| 17 | + data: { query: { url: 'https://example.com/guide' } }, |
| 18 | + }), |
| 19 | +})) |
| 20 | +vi.mock('@/lib/core/config/redis', () => ({ getRedisClient: () => mocks })) |
| 21 | +vi.mock('@/lib/core/network/context.server', () => ({ |
| 22 | + runWithOutboundOrganization: (_organization: null, run: () => unknown) => run(), |
| 23 | +})) |
| 24 | +vi.mock('@/lib/core/utils/with-route-handler', () => ({ |
| 25 | + withRouteHandler: (handler: unknown) => handler, |
| 26 | +})) |
| 27 | +vi.mock('@/lib/link-preview/fetch-preview', () => ({ fetchLinkPreview: mocks.fetch })) |
| 28 | + |
| 29 | +import { GET } from '@/app/api/link-preview/route' |
| 30 | + |
| 31 | +const complete = { title: 'Guide', description: null, siteName: null } |
| 32 | + |
| 33 | +describe('link preview cache lifetime', () => { |
| 34 | + beforeEach(() => { |
| 35 | + vi.clearAllMocks() |
| 36 | + mocks.get.mockResolvedValue(null) |
| 37 | + mocks.set.mockResolvedValue('OK') |
| 38 | + }) |
| 39 | + |
| 40 | + it.each([ |
| 41 | + { preview: { ...complete, imageRetryable: true }, ttl: 60 }, |
| 42 | + { preview: complete, ttl: 24 * 60 * 60 }, |
| 43 | + { preview: null, ttl: 60 * 60 }, |
| 44 | + ])('caches $preview for $ttl seconds', async ({ preview, ttl }) => { |
| 45 | + mocks.fetch.mockResolvedValue(preview) |
| 46 | + const response = await GET(new NextRequest('https://example.com/api/link-preview')) |
| 47 | + expect(await response.json()).toEqual({ preview }) |
| 48 | + expect(mocks.set).toHaveBeenCalledWith(expect.any(String), JSON.stringify(preview), 'EX', ttl) |
| 49 | + }) |
| 50 | +}) |
0 commit comments