|
| 1 | +import { describe, expect, it, vi } from 'vitest' |
| 2 | +import { getApiErrorMessage } from '~/utils/api' |
| 3 | + |
| 4 | +describe('getApiErrorMessage', () => { |
| 5 | + it('returns an empty string for string response data and logs a warning excerpt', () => { |
| 6 | + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) |
| 7 | + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) |
| 8 | + const html = '<html>Server Error</html>' |
| 9 | + |
| 10 | + expect(getApiErrorMessage(html)).toBe('') |
| 11 | + expect(errorSpy).not.toHaveBeenCalled() |
| 12 | + expect(warnSpy).toHaveBeenCalledWith('[API] Non-JSON error response:', html) |
| 13 | + |
| 14 | + errorSpy.mockRestore() |
| 15 | + warnSpy.mockRestore() |
| 16 | + }) |
| 17 | + |
| 18 | + it('returns an empty string for null or undefined response data', () => { |
| 19 | + expect(getApiErrorMessage(null)).toBe('') |
| 20 | + expect(getApiErrorMessage(undefined)).toBe('') |
| 21 | + }) |
| 22 | + |
| 23 | + it('extracts the `error` field when present', () => { |
| 24 | + expect(getApiErrorMessage({ error: 'Something went wrong' })).toBe('Something went wrong') |
| 25 | + }) |
| 26 | + |
| 27 | + it('extracts the `message` field when present', () => { |
| 28 | + expect(getApiErrorMessage({ message: 'A message' })).toBe('A message') |
| 29 | + }) |
| 30 | + |
| 31 | + it('prefers `error` over `message`', () => { |
| 32 | + expect(getApiErrorMessage({ error: 'First', message: 'Second' })).toBe('First') |
| 33 | + }) |
| 34 | + |
| 35 | + it('formats an `errors` object into a human readable string', () => { |
| 36 | + expect(getApiErrorMessage({ errors: { name: 'required', email: 'invalid' } })).toBe('name: required ; email: invalid') |
| 37 | + }) |
| 38 | + |
| 39 | + it('joins response.errors array when present', () => { |
| 40 | + expect(getApiErrorMessage({ response: { errors: ['bad', 'worse'] } })).toBe('bad ; worse') |
| 41 | + }) |
| 42 | +}) |
0 commit comments