-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.test.ts
More file actions
237 lines (209 loc) · 7.18 KB
/
Copy pathclient.test.ts
File metadata and controls
237 lines (209 loc) · 7.18 KB
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/**
* Tests for the axios client (interceptor with refresh-on-401).
*
* Important: ToastContext.getGlobalShowToast() is mocked so that 4xx/5xx
* responses don't try to access the global toast (which is null in pure
* unit tests). MSW intercepts axios since axios uses XHR/fetch under the hood.
*/
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest'
import { http, HttpResponse } from 'msw'
import { server } from '@/test/server'
import { setCookie, getCookie, deleteCookie } from '@/utils/cookies'
// Mock the toast getter so error-toasts don't crash with `toast is null`.
vi.mock('@/context/ToastContext', () => ({
getGlobalShowToast: () => null,
}))
// Mock window.location.href setter so we can observe the redirect.
const locationStub = {
_href: 'http://localhost:3000/',
assign: vi.fn(),
}
Object.defineProperty(window, 'location', {
configurable: true,
value: locationStub,
})
Object.defineProperty(locationStub, 'href', {
configurable: true,
get() {
return this._href
},
set(value: string) {
this._href = value
},
})
let apiClient: typeof import('./client').default
beforeEach(async () => {
// Fresh import so previous interceptors don't pile up.
vi.resetModules()
apiClient = (await import('./client')).default
// Clean cookies between tests.
deleteCookie('accessToken')
deleteCookie('refreshToken')
locationStub._href = 'http://localhost:3000/'
})
afterEach(() => {
vi.clearAllMocks()
})
describe('apiClient request interceptor', () => {
it('adds Authorization header when accessToken cookie exists', async () => {
setCookie('accessToken', 'my-token', 1)
let capturedAuth: string | null = null
server.use(
http.get('/api/echo', ({ request }) => {
capturedAuth = request.headers.get('authorization')
return HttpResponse.json({ ok: true })
})
)
await apiClient.get('/echo')
expect(capturedAuth).toBe('Bearer my-token')
})
it('does NOT add Authorization header when no accessToken cookie', async () => {
let capturedAuth: string | null = null
server.use(
http.get('/api/echo', ({ request }) => {
capturedAuth = request.headers.get('authorization')
return HttpResponse.json({ ok: true })
})
)
await apiClient.get('/echo')
expect(capturedAuth).toBeNull()
})
})
describe('apiClient response interceptor — refresh flow', () => {
it('refreshes the access token on 401 and retries the original request', async () => {
setCookie('accessToken', 'expired-token', 1)
setCookie('refreshToken', 'good-refresh', 30)
let attempt = 0
let refreshCount = 0
server.use(
http.get('/api/secret', () => {
attempt += 1
if (attempt === 1) {
return HttpResponse.json({ detail: 'expired' }, { status: 401 })
}
return HttpResponse.json({ ok: true, attempt })
}),
http.post('/api/auth/refresh', () => {
refreshCount += 1
return HttpResponse.json({
access_token: 'fresh-access',
refresh_token: 'fresh-refresh',
token_type: 'bearer',
})
})
)
const response = await apiClient.get('/secret')
expect(response.status).toBe(200)
expect(response.data).toMatchObject({ ok: true })
expect(refreshCount).toBe(1)
// accessToken cookie was updated to the fresh one.
expect(getCookie('accessToken')).toBe('fresh-access')
})
it('redirects to /login when refresh token is missing', async () => {
setCookie('accessToken', 'expired', 1)
// No refreshToken cookie
server.use(
http.get('/api/secret', () =>
HttpResponse.json({ detail: 'expired' }, { status: 401 })
)
)
await expect(apiClient.get('/secret')).rejects.toBeDefined()
expect(locationStub._href).toBe('/login')
})
it('redirects to /login when refresh itself returns an error', async () => {
setCookie('accessToken', 'expired', 1)
setCookie('refreshToken', 'bad-refresh', 30)
server.use(
http.get('/api/secret', () =>
HttpResponse.json({ detail: 'expired' }, { status: 401 })
),
http.post('/api/auth/refresh', () =>
HttpResponse.json({ detail: 'bad refresh' }, { status: 401 })
)
)
await expect(apiClient.get('/secret')).rejects.toBeDefined()
expect(locationStub._href).toBe('/login')
expect(getCookie('accessToken')).toBeNull()
expect(getCookie('refreshToken')).toBeNull()
})
it('does not retry if request already has _retry flag', async () => {
setCookie('accessToken', 'expired', 1)
setCookie('refreshToken', 'good', 30)
let refreshCount = 0
server.use(
http.get('/api/secret', () =>
HttpResponse.json({ detail: 'expired' }, { status: 401 })
),
http.post('/api/auth/refresh', () => {
refreshCount += 1
return HttpResponse.json({
access_token: 'fresh',
refresh_token: 'fresh',
token_type: 'bearer',
})
})
)
// Mark request as already retried — should bypass the refresh path.
await expect(
apiClient.get('/secret', {
// @ts-expect-error _retry is an internal flag we explicitly want
_retry: true,
})
).rejects.toBeDefined()
// Refresh shouldn't have been called because _retry was preset, AND the
// 401 with _retry doesn't enter the refresh branch.
expect(refreshCount).toBe(0)
})
it('non-401 errors bubble up without triggering refresh', async () => {
setCookie('accessToken', 'good', 1)
setCookie('refreshToken', 'good', 30)
let refreshCount = 0
server.use(
http.get('/api/secret', () =>
HttpResponse.json({ detail: 'forbidden' }, { status: 403 })
),
http.post('/api/auth/refresh', () => {
refreshCount += 1
return HttpResponse.json({})
})
)
await expect(apiClient.get('/secret')).rejects.toBeDefined()
expect(refreshCount).toBe(0)
})
it('handles parallel 401 requests without crashing', async () => {
setCookie('accessToken', 'expired', 1)
setCookie('refreshToken', 'good', 30)
const seen: string[] = []
let refreshCount = 0
server.use(
http.get('/api/secret', ({ request }) => {
const auth = request.headers.get('authorization') ?? ''
seen.push(auth)
if (auth.includes('fresh')) {
return HttpResponse.json({ ok: true })
}
return HttpResponse.json({ detail: 'expired' }, { status: 401 })
}),
http.post('/api/auth/refresh', () => {
refreshCount += 1
return HttpResponse.json({
access_token: 'fresh',
refresh_token: 'fresh',
token_type: 'bearer',
})
})
)
const results = await Promise.all([
apiClient.get('/secret'),
apiClient.get('/secret'),
apiClient.get('/secret'),
])
// All three requests eventually succeed.
for (const r of results) expect(r.status).toBe(200)
// Refresh was called at least once. The current implementation has no
// mutex, so multiple parallel refreshes are possible; we assert the
// contract that the number is bounded by the number of in-flight 401s.
expect(refreshCount).toBeGreaterThanOrEqual(1)
expect(refreshCount).toBeLessThanOrEqual(3)
})
})