-
Notifications
You must be signed in to change notification settings - Fork 6.8k
Expand file tree
/
Copy pathAppConfigContext.test.tsx
More file actions
306 lines (244 loc) · 8.76 KB
/
AppConfigContext.test.tsx
File metadata and controls
306 lines (244 loc) · 8.76 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import { describe, it, expect, beforeEach, vi, afterEach } from "vitest";
import { waitFor, renderHook, act } from "@testing-library/react";
import {
AppConfigProvider,
useAppConfig,
} from "@app/contexts/AppConfigContext";
import apiClient from "@app/services/apiClient";
import { ReactNode } from "react";
// Mock apiClient
vi.mock("@app/services/apiClient");
describe("AppConfigContext", () => {
beforeEach(() => {
vi.clearAllMocks();
// Mock window.location.pathname
Object.defineProperty(window, "location", {
value: { pathname: "/" },
writable: true,
});
});
afterEach(() => {
vi.restoreAllMocks();
});
const wrapper = ({ children }: { children: ReactNode }) => (
<AppConfigProvider>{children}</AppConfigProvider>
);
/**
* Helper to mock API responses for app-config and info-status
*/
const mockApiResponses = (config: any, delay = 0) => {
vi.mocked(apiClient.get).mockImplementation(async (url: string) => {
if (delay > 0) {
await new Promise((resolve) => setTimeout(resolve, delay));
}
if (url === "/api/v1/config/app-config") {
return { status: 200, data: config };
}
if (url === "/api/v1/info/status") {
return { status: 200, data: { status: "UP" } };
}
return { status: 404, data: {} };
});
};
it("should fetch and provide app config on non-auth pages", async () => {
const mockConfig = {
enableLogin: false,
appNameNavbar: "Stirling PDF",
languages: ["en-US", "en-GB"],
};
// Use a small delay to ensure we can catch the loading state
mockApiResponses(mockConfig, 10);
const { result } = renderHook(() => useAppConfig(), { wrapper });
// Initially loading
expect(result.current.loading).toBe(true);
expect(result.current.config).toBeNull();
await waitFor(
() => {
expect(result.current.loading).toBe(false);
expect(result.current.config).toEqual(mockConfig);
expect(result.current.error).toBeNull();
},
{ timeout: 1000 },
);
expect(apiClient.get).toHaveBeenCalledWith("/api/v1/config/app-config", {
suppressErrorToast: true,
skipAuthRedirect: true,
});
});
it("should skip fetch on auth pages and use default config", async () => {
// Mock being on login page
Object.defineProperty(window, "location", {
value: { pathname: "/login" },
writable: true,
});
const { result } = renderHook(() => useAppConfig(), { wrapper });
await waitFor(() => {
expect(result.current.loading).toBe(false);
expect(result.current.config).toEqual({ enableLogin: true });
});
// Should NOT call API on auth pages
expect(apiClient.get).not.toHaveBeenCalled();
});
it("should handle 401 error gracefully", async () => {
const mockError = Object.assign(new Error("Unauthorized"), {
response: { status: 401, data: {} },
});
vi.mocked(apiClient.get).mockRejectedValue(mockError);
const { result } = renderHook(() => useAppConfig(), { wrapper });
await waitFor(() => {
expect(result.current.loading).toBe(false);
expect(result.current.config).toEqual({ enableLogin: true });
// 401 should be handled gracefully, error may be null or set
});
});
it("should handle network errors", async () => {
const errorMessage = "Network error occurred";
const mockError = new Error(errorMessage);
// Network errors don't have response property
// Mock rejection for all retry attempts (default is 0 retries in test if not specified,
// but the component might still catch it)
vi.mocked(apiClient.get).mockRejectedValue(mockError);
const { result } = renderHook(() => useAppConfig(), { wrapper });
await waitFor(() => {
expect(result.current.loading).toBe(false);
expect(result.current.config).toEqual({ enableLogin: true });
expect(result.current.error).toBe(errorMessage);
});
});
it("should skip fetch on signup page", async () => {
Object.defineProperty(window, "location", {
value: { pathname: "/signup" },
writable: true,
});
const { result } = renderHook(() => useAppConfig(), { wrapper });
await waitFor(() => {
expect(result.current.loading).toBe(false);
expect(result.current.config).toEqual({ enableLogin: true });
});
expect(apiClient.get).not.toHaveBeenCalled();
});
it("should skip fetch on auth callback page", async () => {
Object.defineProperty(window, "location", {
value: { pathname: "/auth/callback" },
writable: true,
});
const { result } = renderHook(() => useAppConfig(), { wrapper });
await waitFor(() => {
expect(result.current.loading).toBe(false);
expect(result.current.config).toEqual({ enableLogin: true });
});
expect(apiClient.get).not.toHaveBeenCalled();
});
it("should skip fetch on invite accept page", async () => {
Object.defineProperty(window, "location", {
value: { pathname: "/invite/abc123" },
writable: true,
});
const { result } = renderHook(() => useAppConfig(), { wrapper });
await waitFor(() => {
expect(result.current.loading).toBe(false);
expect(result.current.config).toEqual({ enableLogin: true });
});
expect(apiClient.get).not.toHaveBeenCalled();
});
it("should refetch config when jwt-available event is triggered", async () => {
const initialConfig = {
enableLogin: true,
appNameNavbar: "Stirling PDF",
};
const updatedConfig = {
enableLogin: true,
appNameNavbar: "Stirling PDF",
isAdmin: true,
enableAnalytics: true,
};
// Setup implementation to return different configs on subsequent calls
let callCount = 0;
vi.mocked(apiClient.get).mockImplementation(async (url: string) => {
if (url === "/api/v1/config/app-config") {
callCount++;
return {
status: 200,
data: callCount === 1 ? initialConfig : updatedConfig,
};
}
return { status: 200, data: { status: "UP" } };
});
const { result } = renderHook(() => useAppConfig(), { wrapper });
await waitFor(() => {
expect(result.current.config).toEqual(initialConfig);
});
// Trigger jwt-available event wrapped in act
await act(async () => {
window.dispatchEvent(new CustomEvent("jwt-available"));
// Wait a tick for event handler to run
await new Promise((resolve) => setTimeout(resolve, 0));
});
await waitFor(() => {
expect(result.current.config).toEqual(updatedConfig);
});
// 2 logical fetches * 2 calls each = 4 total calls
expect(apiClient.get).toHaveBeenCalledTimes(4);
});
it("should provide refetch function", async () => {
const mockConfig = {
enableLogin: false,
appNameNavbar: "Test App",
};
mockApiResponses(mockConfig);
const { result } = renderHook(() => useAppConfig(), { wrapper });
await waitFor(() => {
expect(result.current.config).toEqual(mockConfig);
});
// Call refetch wrapped in act
await act(async () => {
await result.current.refetch();
});
// 2 logical fetches * 2 calls each = 4 total calls
expect(apiClient.get).toHaveBeenCalledTimes(4);
});
it("should not fetch twice without force flag", async () => {
const mockConfig = {
enableLogin: false,
};
mockApiResponses(mockConfig);
const { result } = renderHook(() => useAppConfig(), { wrapper });
await waitFor(() => {
expect(result.current.config).toEqual(mockConfig);
});
// Should only be called twice (one logical fetch = /app-config + /info/status)
expect(apiClient.get).toHaveBeenCalledTimes(2);
});
it("should handle initial config prop", async () => {
const initialConfig = {
enableLogin: false,
appNameNavbar: "Initial App",
};
mockApiResponses({ ...initialConfig, fromApi: true });
const customWrapper = ({ children }: { children: ReactNode }) => (
<AppConfigProvider initialConfig={initialConfig}>
{children}
</AppConfigProvider>
);
const { result } = renderHook(() => useAppConfig(), {
wrapper: customWrapper,
});
// With blocking mode (default), should still fetch even with initial config
await waitFor(() => {
expect(result.current.loading).toBe(false);
});
// Should still make API call
expect(apiClient.get).toHaveBeenCalled();
});
it("should use suppressErrorToast for all config requests", async () => {
const mockConfig = { enableLogin: true };
mockApiResponses(mockConfig);
renderHook(() => useAppConfig(), { wrapper });
await waitFor(() => {
expect(apiClient.get).toHaveBeenCalledWith("/api/v1/config/app-config", {
suppressErrorToast: true,
skipAuthRedirect: true,
});
});
});
});