gongxiangp2/lib/__tests__/taobao-image-proxy-route.test.ts
2026-05-07 16:37:22 +08:00

90 lines
2.6 KiB
TypeScript

/** @jest-environment node */
import { GET } from '@/app/api/taobao-detail-plus/image-proxy/route'
import { getServerSession } from 'next-auth'
jest.mock('next-auth', () => ({
getServerSession: jest.fn(),
}))
jest.mock('@/lib/auth', () => ({
authOptions: {},
}))
const TINY_PNG_BASE64 =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9VE3d2kAAAAASUVORK5CYII='
describe('taobao image proxy route', () => {
beforeEach(() => {
jest.clearAllMocks()
;(getServerSession as jest.Mock).mockResolvedValue({
user: { id: 'user-1', name: 'tester' },
})
global.fetch = jest.fn() as jest.Mock
})
function createRequest(url: string) {
return {
nextUrl: new URL(url),
} as any
}
test('未登录时应返回 401', async () => {
;(getServerSession as jest.Mock).mockResolvedValue(null)
const response = await GET(
createRequest(
'https://example.com/api/taobao-detail-plus/image-proxy?url=https%3A%2F%2Fimg.alicdn.com%2Fa.png',
),
)
const body = await response.json()
expect(response.status).toBe(401)
expect(body.error.code).toBe('UNAUTHORIZED')
})
test('图片来源域名不允许时应返回 400', async () => {
const response = await GET(
createRequest(
'https://example.com/api/taobao-detail-plus/image-proxy?url=https%3A%2F%2Fevil.example.com%2Fa.png',
),
)
const body = await response.json()
expect(response.status).toBe(400)
expect(body.error.code).toBe('IMAGE_HOST_NOT_ALLOWED')
})
test('允许的图片地址应返回 png 数据', async () => {
const upstreamBuffer = Buffer.from(TINY_PNG_BASE64, 'base64')
;(global.fetch as jest.Mock).mockResolvedValue({
ok: true,
arrayBuffer: async () =>
upstreamBuffer.buffer.slice(
upstreamBuffer.byteOffset,
upstreamBuffer.byteOffset + upstreamBuffer.byteLength,
),
})
const response = await GET(
createRequest(
'https://example.com/api/taobao-detail-plus/image-proxy?url=https%3A%2F%2Fimg.alicdn.com%2Fa.png',
),
)
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toBe('image/png')
expect(Number(response.headers.get('x-image-width'))).toBeGreaterThan(0)
expect(Number(response.headers.get('x-image-height'))).toBeGreaterThan(0)
const bodyBuffer = Buffer.from(await response.arrayBuffer())
expect(bodyBuffer.length).toBeGreaterThan(0)
expect(global.fetch).toHaveBeenCalledWith(
'https://img.alicdn.com/a.png',
expect.objectContaining({
method: 'GET',
}),
)
})
})