|
| 1 | +import { afterEach, describe, expect, spyOn, test } from 'bun:test' |
| 2 | +import type { Context } from 'hono' |
| 3 | +import type { Env } from '../types' |
| 4 | +import { fetchContent } from './fetchContent' |
| 5 | + |
| 6 | +describe('fetchContent', () => { |
| 7 | + let fetchSpy: ReturnType<typeof spyOn> | undefined |
| 8 | + |
| 9 | + afterEach(() => { |
| 10 | + fetchSpy?.mockRestore() |
| 11 | + }) |
| 12 | + |
| 13 | + test('should return page content with Cache-Control header when fetched from remote', async () => { |
| 14 | + const mockRepoItems = [ |
| 15 | + { |
| 16 | + path: 'test', |
| 17 | + label: 'Test Item', |
| 18 | + }, |
| 19 | + ] |
| 20 | + |
| 21 | + const mockMarkdown = `--- |
| 22 | +title: Remote Test |
| 23 | +description: Remote Description |
| 24 | +--- |
| 25 | +
|
| 26 | +# Remote Content |
| 27 | +This is remote content.` |
| 28 | + |
| 29 | + const mockFetch = Object.assign( |
| 30 | + async (input: RequestInfo | URL) => { |
| 31 | + const url = typeof input === 'string' ? input : input.toString() |
| 32 | + if (url.endsWith('docs/index.json')) { |
| 33 | + return new Response(JSON.stringify(mockRepoItems), { |
| 34 | + status: 200, |
| 35 | + headers: { 'Content-Type': 'application/json' }, |
| 36 | + }) |
| 37 | + } |
| 38 | + return new Response(mockMarkdown, { |
| 39 | + status: 200, |
| 40 | + headers: { 'Content-Type': 'text/plain' }, |
| 41 | + }) |
| 42 | + }, |
| 43 | + { preconnect: () => {} }, |
| 44 | + ) |
| 45 | + |
| 46 | + fetchSpy = spyOn(globalThis, 'fetch').mockImplementation(mockFetch) |
| 47 | + |
| 48 | + const response = await fetchContent({ |
| 49 | + params: { |
| 50 | + owner: 'other', |
| 51 | + repository: 'repo', |
| 52 | + branch: 'feat', |
| 53 | + path: 'test-item', |
| 54 | + }, |
| 55 | + ctx: {} as Context<{ Bindings: Env }>, |
| 56 | + }) |
| 57 | + |
| 58 | + expect(response.status).toBe(200) |
| 59 | + expect(response.headers.get('Cache-Control')).toBe('public, max-age=600') |
| 60 | + const body = (await response.json()) as { |
| 61 | + seo: { title?: string } |
| 62 | + meta: { title?: string } |
| 63 | + } |
| 64 | + expect(body.seo.title).toBe('Remote Test') |
| 65 | + expect(body.meta.title).toBe('Test Item') |
| 66 | + }) |
| 67 | + |
| 68 | + test('should return 500 when remote fetch fails', async () => { |
| 69 | + const consoleSpy = spyOn(console, 'log').mockImplementation(() => {}) |
| 70 | + |
| 71 | + fetchSpy = spyOn(globalThis, 'fetch').mockResolvedValue( |
| 72 | + new Response('Not Found', { status: 404 }), |
| 73 | + ) |
| 74 | + |
| 75 | + const response = await fetchContent({ |
| 76 | + params: { |
| 77 | + owner: 'other', |
| 78 | + repository: 'repo', |
| 79 | + branch: 'feat', |
| 80 | + path: 'test', |
| 81 | + }, |
| 82 | + ctx: {} as Context<{ Bindings: Env }>, |
| 83 | + }) |
| 84 | + |
| 85 | + expect(response.status).toBe(500) |
| 86 | + consoleSpy.mockRestore() |
| 87 | + }) |
| 88 | +}) |
0 commit comments