86 lines
2.5 KiB
TypeScript
86 lines
2.5 KiB
TypeScript
import { GET, HEAD } from './route'
|
|
import { NextRequest } from 'next/server'
|
|
|
|
// Mock the process object for tests
|
|
const mockProcess = {
|
|
uptime: jest.fn().mockReturnValue(1234),
|
|
env: {
|
|
npm_package_version: '1.0.0',
|
|
NODE_ENV: 'test',
|
|
},
|
|
}
|
|
|
|
const originalProcess = global.process
|
|
beforeEach(() => {
|
|
global.process = { ...originalProcess, ...mockProcess } as any
|
|
})
|
|
|
|
afterEach(() => {
|
|
global.process = originalProcess
|
|
})
|
|
|
|
describe('/api/health', () => {
|
|
describe('GET request', () => {
|
|
it('should return successful health status with required data', async () => {
|
|
const response = await GET()
|
|
|
|
// Check response status
|
|
expect(response.status).toBe(200)
|
|
|
|
// Get JSON data
|
|
const data = await response.json()
|
|
|
|
// Verify required fields
|
|
expect(data).toHaveProperty('status', 'ok')
|
|
expect(data).toHaveProperty('timestamp')
|
|
expect(data).toHaveProperty('uptime')
|
|
expect(data).toHaveProperty('version')
|
|
expect(data).toHaveProperty('environment')
|
|
|
|
// Verify timestamp is a valid ISO string
|
|
expect(() => new Date(data.timestamp)).not.toThrow()
|
|
expect(data.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/)
|
|
|
|
// Verify uptime matches mock
|
|
expect(data.uptime).toBe(1234)
|
|
|
|
// Verify version
|
|
expect(data.version).toBe('1.0.0')
|
|
})
|
|
|
|
it('should include correct Cache-Control headers', async () => {
|
|
const response = await GET()
|
|
|
|
expect(response.headers.get('Cache-Control')).toBe('no-cache, no-store, must-revalidate')
|
|
expect(response.headers.get('Pragma')).toBe('no-cache')
|
|
expect(response.headers.get('Expires')).toBe('0')
|
|
})
|
|
|
|
it('should handle errors gracefully', async () => {
|
|
// Temporarily break process.uptime to simulate error
|
|
const originalUptime = global.process.uptime
|
|
global.process.uptime = (() => { throw new Error('Uptime error') }) as any
|
|
|
|
const response = await GET()
|
|
|
|
expect(response.status).toBe(503)
|
|
|
|
const data = await response.json()
|
|
expect(data.status).toBe('error')
|
|
expect(data).toHaveProperty('timestamp')
|
|
expect(data).toHaveProperty('message', 'Health check failed')
|
|
|
|
// Restore process.uptime
|
|
global.process.uptime = originalUptime
|
|
})
|
|
})
|
|
|
|
describe('HEAD request', () => {
|
|
it('should return 200 status without body', async () => {
|
|
const response = await HEAD()
|
|
|
|
expect(response.status).toBe(200)
|
|
expect(response.headers.get('Cache-Control')).toBe('no-cache, no-store, must-revalidate')
|
|
})
|
|
})
|
|
}) |