|
| 1 | +import { afterEach, describe, expect, it, vi } from 'vitest'; |
| 2 | +import { fetchWithCorsProxy } from './fetch-with-cors-proxy'; |
| 3 | + |
| 4 | +describe('fetchWithCorsProxy', () => { |
| 5 | + afterEach(() => { |
| 6 | + vi.restoreAllMocks(); |
| 7 | + }); |
| 8 | + |
| 9 | + it('upgrades plain HTTP requests to HTTPS before fetching directly', async () => { |
| 10 | + const fetchMock = vi |
| 11 | + .spyOn(globalThis, 'fetch') |
| 12 | + .mockResolvedValue(new Response('ok')); |
| 13 | + |
| 14 | + await fetchWithCorsProxy('http://example.com/resource.zip'); |
| 15 | + |
| 16 | + expect(fetchMock).toHaveBeenCalledTimes(1); |
| 17 | + const directRequest = fetchMock.mock.calls[0][0] as Request; |
| 18 | + expect(directRequest.url).toBe('https://example.com/resource.zip'); |
| 19 | + }); |
| 20 | + |
| 21 | + it('upgrades HTTP URLs before retrying via the CORS proxy', async () => { |
| 22 | + const fetchMock = vi |
| 23 | + .spyOn(globalThis, 'fetch') |
| 24 | + .mockRejectedValueOnce(new Error('network fail')) |
| 25 | + .mockResolvedValueOnce(new Response('proxied')); |
| 26 | + |
| 27 | + await fetchWithCorsProxy( |
| 28 | + 'http://example.com/wp-cron.php', |
| 29 | + undefined, |
| 30 | + 'https://proxy.test/?url=' |
| 31 | + ); |
| 32 | + |
| 33 | + expect(fetchMock).toHaveBeenCalledTimes(2); |
| 34 | + const initialRequest = fetchMock.mock.calls[0][0] as Request; |
| 35 | + expect(initialRequest.url).toBe('https://example.com/wp-cron.php'); |
| 36 | + |
| 37 | + const proxiedRequest = fetchMock.mock.calls[1][0] as Request; |
| 38 | + expect(proxiedRequest.url).toBe( |
| 39 | + 'https://proxy.test/?url=https://example.com/wp-cron.php' |
| 40 | + ); |
| 41 | + }); |
| 42 | +}); |
0 commit comments