import { vi } from 'vitest'; import { MockLeaguesApiClient } from './mocks/MockLeaguesApiClient'; import { CircuitBreakerRegistry } from '../../../apps/website/lib/api/base/RetryHandler'; export class WebsiteTestContext { public mockLeaguesApiClient: MockLeaguesApiClient; private originalFetch: typeof global.fetch; private fetchMock = vi.fn(); constructor() { this.mockLeaguesApiClient = new MockLeaguesApiClient(); this.originalFetch = global.fetch; } static create() { return new WebsiteTestContext(); } setup() { this.originalFetch = global.fetch; global.fetch = this.fetchMock; process.env.NEXT_PUBLIC_API_BASE_URL = 'http://localhost:3001'; process.env.API_BASE_URL = 'http://localhost:3001'; vi.stubEnv('NODE_ENV', 'test'); CircuitBreakerRegistry.getInstance().resetAll(); } teardown() { global.fetch = this.originalFetch; this.fetchMock.mockClear(); this.mockLeaguesApiClient.clearMocks(); vi.restoreAllMocks(); vi.unstubAllEnvs(); CircuitBreakerRegistry.getInstance().resetAll(); // Reset environment variables delete process.env.NEXT_PUBLIC_API_BASE_URL; delete process.env.API_BASE_URL; } mockFetchResponse(data: any, status = 200, ok = true) { this.fetchMock.mockResolvedValueOnce(this.createMockResponse(data, status, ok)); } mockFetchError(error: Error) { this.fetchMock.mockRejectedValueOnce(error); } mockFetchComplex(handler: (input: RequestInfo | URL, init?: RequestInit) => Promise) { this.fetchMock.mockImplementation(handler); } createMockResponse(data: any, status = 200, ok = true): Response { return { ok, status, statusText: ok ? 'OK' : 'Error', headers: new Headers(), json: async () => data, text: async () => (typeof data === 'string' ? data : JSON.stringify(data)), blob: async () => new Blob(), arrayBuffer: async () => new ArrayBuffer(0), formData: async () => new FormData(), clone: () => this.createMockResponse(data, status, ok), body: null, bodyUsed: false, } as Response; } createMockErrorResponse(status: number, statusText: string, body: string): Response { return { ok: false, status, statusText, headers: new Headers(), text: async () => body, json: async () => ({ message: body }), blob: async () => new Blob(), arrayBuffer: async () => new ArrayBuffer(0), formData: async () => new FormData(), clone: () => this.createMockErrorResponse(status, statusText, body), body: null, bodyUsed: false, } as Response; } }