|
| 1 | +import { describe, it, expect, vi, beforeEach } from 'vitest'; |
| 2 | +import { ApiClient } from '../../src/client/api.js'; |
| 3 | + |
| 4 | +const BASE_URL = 'https://stellar-explain-core.onrender.com'; |
| 5 | + |
| 6 | +describe('ApiClient', () => { |
| 7 | + beforeEach(() => { |
| 8 | + vi.restoreAllMocks(); |
| 9 | + }); |
| 10 | + |
| 11 | + it('throws a friendly message when API returns non-JSON response', async () => { |
| 12 | + vi.spyOn(globalThis, 'fetch').mockResolvedValue( |
| 13 | + new Response('<html>502 Bad Gateway</html>', { |
| 14 | + status: 502, |
| 15 | + statusText: 'Bad Gateway', |
| 16 | + headers: { 'content-type': 'text/html' }, |
| 17 | + }) |
| 18 | + ); |
| 19 | + |
| 20 | + const client = new ApiClient(BASE_URL, 10_000); |
| 21 | + await expect(client.health()).rejects.toThrow('Unexpected response from API'); |
| 22 | + }); |
| 23 | + |
| 24 | + it('throws a friendly message on network timeout', async () => { |
| 25 | + vi.spyOn(globalThis, 'fetch').mockImplementation( |
| 26 | + () => |
| 27 | + new Promise((_, reject) => { |
| 28 | + const err = new DOMException('The operation was aborted', 'AbortError'); |
| 29 | + reject(err); |
| 30 | + }) |
| 31 | + ); |
| 32 | + |
| 33 | + const client = new ApiClient(BASE_URL, 100); |
| 34 | + await expect(client.health()).rejects.toThrow('Request timed out after'); |
| 35 | + }); |
| 36 | + |
| 37 | + it('throws a friendly message on connection refused', async () => { |
| 38 | + vi.spyOn(globalThis, 'fetch').mockRejectedValue( |
| 39 | + new TypeError('fetch failed: reason: ECONNREFUSED') |
| 40 | + ); |
| 41 | + |
| 42 | + const client = new ApiClient('http://localhost:1'); |
| 43 | + await expect(client.health()).rejects.toThrow('Connection refused'); |
| 44 | + }); |
| 45 | + |
| 46 | + it('throws a friendly message on DNS failure', async () => { |
| 47 | + vi.spyOn(globalThis, 'fetch').mockRejectedValue( |
| 48 | + new TypeError('fetch failed: ENOTFOUND nonexistent.example.com') |
| 49 | + ); |
| 50 | + |
| 51 | + const client = new ApiClient('http://nonexistent.example.com'); |
| 52 | + await expect(client.health()).rejects.toThrow('Cannot reach'); |
| 53 | + }); |
| 54 | + |
| 55 | + it('includes response body text in API error messages', async () => { |
| 56 | + vi.spyOn(globalThis, 'fetch').mockResolvedValue( |
| 57 | + new Response('Service Unavailable', { |
| 58 | + status: 503, |
| 59 | + statusText: 'Service Unavailable', |
| 60 | + }) |
| 61 | + ); |
| 62 | + |
| 63 | + const client = new ApiClient(BASE_URL, 10_000); |
| 64 | + await expect(client.health()).rejects.toThrow('API error: 503'); |
| 65 | + }); |
| 66 | +}); |
0 commit comments