~bigbes/lethe

ref: 5d910e8263ed5002b4f04c2c3fa3146dec4b6b78 lethe/web/src/api/client.test.ts -rw-r--r-- 4.8 KiB
5d910e82 — Eugene Blikh server/web: tag Config fields for snake_case JSON output (IF1 contract) a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { apiFetch, apiFetchVoid, AuthError, APIError } from './client'
import { tokenStore } from '../lib/auth'

// ── Helpers ──────────────────────────────────────────────────────────────────

function makeOkResponse(body: unknown = {}, status = 200): Response {
  return {
    ok: true,
    status,
    headers: { get: () => null },
    json: () => Promise.resolve(body),
  } as unknown as Response
}

function makeErrorResponse(status: number, contentType?: string, body?: unknown): Response {
  return {
    ok: false,
    status,
    headers: {
      get: (h: string) => h.toLowerCase() === 'content-type' ? (contentType ?? null) : null,
    },
    json: () => Promise.resolve(body),
  } as unknown as Response
}

// ── Setup / teardown ─────────────────────────────────────────────────────────

let fetchSpy: ReturnType<typeof vi.fn>

beforeEach(() => {
  fetchSpy = vi.fn()
  vi.stubGlobal('fetch', fetchSpy)
  tokenStore.set(null)
})

afterEach(() => {
  tokenStore.set(null)
  vi.unstubAllGlobals()
  vi.restoreAllMocks()
})

// ── apiFetch: Authorization header behavior ──────────────────────────────────

describe('apiFetch Authorization header', () => {
  it('no stored token → fetch called without Authorization header', async () => {
    fetchSpy.mockResolvedValue(makeOkResponse({ result: 1 }))

    await apiFetch('/api/v1/test')

    const [, init] = fetchSpy.mock.calls[0] as [string, RequestInit]
    const headers = init.headers as Record<string, string>
    expect(headers['Authorization']).toBeUndefined()
  })

  it('stored token → fetch called with Authorization: Bearer <token>', async () => {
    fetchSpy.mockResolvedValue(makeOkResponse({ result: 1 }))
    tokenStore.set('abc')

    await apiFetch('/api/v1/test')

    const [, init] = fetchSpy.mock.calls[0] as [string, RequestInit]
    const headers = init.headers as Record<string, string>
    expect(headers['Authorization']).toBe('Bearer abc')
  })

  it('caller-supplied Authorization header wins over stored token', async () => {
    fetchSpy.mockResolvedValue(makeOkResponse({ result: 1 }))
    tokenStore.set('stored-token')

    await apiFetch('/api/v1/test', {
      headers: { Authorization: 'Bearer caller-token' },
    })

    const [, init] = fetchSpy.mock.calls[0] as [string, RequestInit]
    const headers = init.headers as Record<string, string>
    expect(headers['Authorization']).toBe('Bearer caller-token')
  })

  it('401 → AuthError thrown (regression)', async () => {
    fetchSpy.mockResolvedValue(makeErrorResponse(401))

    await expect(apiFetch('/api/v1/test')).rejects.toThrow(AuthError)
  })

  it('500 → APIError thrown (regression)', async () => {
    fetchSpy.mockResolvedValue(makeErrorResponse(500))

    await expect(apiFetch('/api/v1/test')).rejects.toThrow(APIError)
  })
})

// ── apiFetchVoid: Authorization header behavior ──────────────────────────────

describe('apiFetchVoid Authorization header', () => {
  it('no stored token → fetch called without Authorization header', async () => {
    fetchSpy.mockResolvedValue(makeOkResponse(undefined, 204))

    await apiFetchVoid('/api/v1/test')

    const [, init] = fetchSpy.mock.calls[0] as [string, RequestInit]
    const headers = init.headers as Record<string, string>
    expect(headers['Authorization']).toBeUndefined()
  })

  it('stored token → fetch called with Authorization: Bearer <token>', async () => {
    fetchSpy.mockResolvedValue(makeOkResponse(undefined, 204))
    tokenStore.set('xyz')

    await apiFetchVoid('/api/v1/test')

    const [, init] = fetchSpy.mock.calls[0] as [string, RequestInit]
    const headers = init.headers as Record<string, string>
    expect(headers['Authorization']).toBe('Bearer xyz')
  })

  it('caller-supplied Authorization header wins over stored token', async () => {
    fetchSpy.mockResolvedValue(makeOkResponse(undefined, 204))
    tokenStore.set('stored-token')

    await apiFetchVoid('/api/v1/test', {
      headers: { Authorization: 'Bearer caller-token' },
    })

    const [, init] = fetchSpy.mock.calls[0] as [string, RequestInit]
    const headers = init.headers as Record<string, string>
    expect(headers['Authorization']).toBe('Bearer caller-token')
  })

  it('401 → AuthError thrown (regression)', async () => {
    fetchSpy.mockResolvedValue(makeErrorResponse(401))

    await expect(apiFetchVoid('/api/v1/test')).rejects.toThrow(AuthError)
  })
})