diff --git a/src/lib/__tests__/apiUtils.test.ts b/src/lib/__tests__/apiUtils.test.ts index fbd65ba..d5b3e8c 100644 --- a/src/lib/__tests__/apiUtils.test.ts +++ b/src/lib/__tests__/apiUtils.test.ts @@ -1,5 +1,5 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { handleErrorResponse, getAuthenticatedUser } from '../apiUtils'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { handleErrorResponse, getAuthenticatedUser, handleRateLimit } from '../apiUtils'; import { NextResponse } from 'next/server'; import { getServerSession } from "next-auth"; @@ -97,4 +97,47 @@ describe('apiUtils', () => { expect(result).toBeNull(); }); }); + + describe('handleRateLimit', () => { + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(1600000000000)); // Timestamp: 1600000000 + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('should throw RateLimitError using the reset timestamp from the X-RateLimit-Reset header', () => { + const resetTimestamp = 1600003600; + const headers = new Headers(); + headers.set('X-RateLimit-Reset', resetTimestamp.toString()); + const res = new Response(null, { headers }); + + expect(() => handleRateLimit(res)).toThrowError( + `GitHub API rate limit exceeded. Resets at ${new Date(resetTimestamp * 1000).toISOString()}` + ); + }); + + it('should throw RateLimitError using default time + 3600s if X-RateLimit-Reset header is missing', () => { + const headers = new Headers(); + const res = new Response(null, { headers }); + const expectedResetTimestamp = Math.floor(Date.now() / 1000) + 3600; + + expect(() => handleRateLimit(res)).toThrowError( + `GitHub API rate limit exceeded. Resets at ${new Date(expectedResetTimestamp * 1000).toISOString()}` + ); + }); + + it('should throw RateLimitError using default time + 3600s if X-RateLimit-Reset header is invalid', () => { + const headers = new Headers(); + headers.set('X-RateLimit-Reset', 'invalid'); + const res = new Response(null, { headers }); + const expectedResetTimestamp = Math.floor(Date.now() / 1000) + 3600; + + expect(() => handleRateLimit(res)).toThrowError( + `GitHub API rate limit exceeded. Resets at ${new Date(expectedResetTimestamp * 1000).toISOString()}` + ); + }); + }); });