|
| 1 | +import { describe, expect, it } from 'vitest'; |
| 2 | +import { describeFetchError } from '../../src/lib/describe-fetch-error'; |
| 3 | + |
| 4 | +describe('describeFetchError', () => { |
| 5 | + it('returns the message for a plain Error without a cause', () => { |
| 6 | + let err = new Error('boom'); |
| 7 | + expect(describeFetchError(err)).toBe('boom'); |
| 8 | + }); |
| 9 | + |
| 10 | + it('returns the string form for a non-Error value', () => { |
| 11 | + expect(describeFetchError('plain string')).toBe('plain string'); |
| 12 | + expect(describeFetchError(42)).toBe('42'); |
| 13 | + expect(describeFetchError(null)).toBe('null'); |
| 14 | + expect(describeFetchError(undefined)).toBe('undefined'); |
| 15 | + }); |
| 16 | + |
| 17 | + it('appends an Error cause with a (caused by: …) suffix', () => { |
| 18 | + // Build via assignment to sidestep the ErrorOptions TS lib target. |
| 19 | + let socketErr = new Error('ECONNRESET: socket hang up'); |
| 20 | + let fetchErr = new TypeError('fetch failed') as TypeError & { |
| 21 | + cause?: unknown; |
| 22 | + }; |
| 23 | + fetchErr.cause = socketErr; |
| 24 | + expect(describeFetchError(fetchErr)).toBe( |
| 25 | + 'fetch failed (caused by: ECONNRESET: socket hang up)', |
| 26 | + ); |
| 27 | + }); |
| 28 | + |
| 29 | + it('renders a non-Error cause via String()', () => { |
| 30 | + let err = new Error('outer') as Error & { cause?: unknown }; |
| 31 | + err.cause = { code: 'ENOTFOUND' }; |
| 32 | + expect(describeFetchError(err)).toBe('outer (caused by: [object Object])'); |
| 33 | + }); |
| 34 | + |
| 35 | + it('preserves falsy-but-defined causes that a truthy check would drop', () => { |
| 36 | + // The behavior this guards is the difference between `error.cause` |
| 37 | + // (truthy check, drops falsy values) and `error.cause != null` |
| 38 | + // (preserves any explicit value). Verifies the four falsy |
| 39 | + // primitives a Promise.reject could plausibly carry. |
| 40 | + for (let cause of ['', 0, false, NaN]) { |
| 41 | + let err = new Error('outer') as Error & { cause?: unknown }; |
| 42 | + err.cause = cause; |
| 43 | + expect(describeFetchError(err)).toBe( |
| 44 | + `outer (caused by: ${String(cause)})`, |
| 45 | + ); |
| 46 | + } |
| 47 | + }); |
| 48 | + |
| 49 | + it('omits the (caused by: …) suffix for null or undefined causes', () => { |
| 50 | + for (let cause of [null, undefined]) { |
| 51 | + let err = new Error('outer') as Error & { cause?: unknown }; |
| 52 | + err.cause = cause; |
| 53 | + expect(describeFetchError(err)).toBe('outer'); |
| 54 | + } |
| 55 | + }); |
| 56 | +}); |
0 commit comments