-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathuse-analytics-query.test.ts
More file actions
280 lines (228 loc) · 9.36 KB
/
Copy pathuse-analytics-query.test.ts
File metadata and controls
280 lines (228 loc) · 9.36 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
import { renderHook, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, test, vi } from "vitest";
let lastConnectArgs: any = null;
const mockProcessArrowBuffer = vi.fn();
const mockFetchArrow = vi.fn();
const mockConnectSSE = vi.fn((args: any) => {
lastConnectArgs = args;
return () => {};
});
vi.mock("@/js", () => ({
connectSSE: (...args: unknown[]) => mockConnectSSE(...(args as [any])),
ArrowClient: {
fetchArrow: (...args: unknown[]) => mockFetchArrow(...args),
processArrowBuffer: (...args: unknown[]) => mockProcessArrowBuffer(...args),
},
}));
vi.mock("../use-query-hmr", () => ({
useQueryHMR: vi.fn(),
}));
import { useAnalyticsQuery } from "../use-analytics-query";
describe("useAnalyticsQuery", () => {
beforeEach(() => {
vi.clearAllMocks();
lastConnectArgs = null;
});
test("fetches an arrow message (warehouse statement id) via /arrow-result", async () => {
const fakeTable = { numRows: 1, schema: { fields: [] } };
const fakeBytes = new Uint8Array([1, 2, 3]);
mockFetchArrow.mockResolvedValueOnce(fakeBytes);
mockProcessArrowBuffer.mockResolvedValueOnce(fakeTable);
const { result } = renderHook(() =>
useAnalyticsQuery("q", null, { format: "ARROW_STREAM" }),
);
await lastConnectArgs.onMessage({
data: JSON.stringify({ type: "arrow", statement_id: "stmt-warehouse-1" }),
});
await waitFor(() => {
expect(result.current.data).toBe(fakeTable);
});
expect(mockFetchArrow).toHaveBeenCalledTimes(1);
expect(mockFetchArrow).toHaveBeenCalledWith(
"/api/analytics/arrow-result/stmt-warehouse-1",
);
expect(mockProcessArrowBuffer).toHaveBeenCalledWith(fakeBytes);
});
test("fetches an arrow message with synthetic inline- id through the same /arrow-result path", async () => {
// The client must treat inline and external-links responses uniformly —
// it never decodes base64 locally. The /arrow-result route on the
// server is the only place that knows which path the bytes came from.
const fakeTable = { numRows: 1, schema: { fields: [] } };
const fakeBytes = new Uint8Array([1, 2, 3, 4, 5]);
mockFetchArrow.mockResolvedValueOnce(fakeBytes);
mockProcessArrowBuffer.mockResolvedValueOnce(fakeTable);
const { result } = renderHook(() =>
useAnalyticsQuery("q", null, { format: "ARROW_STREAM" }),
);
await lastConnectArgs.onMessage({
data: JSON.stringify({
type: "arrow",
statement_id: "inline-abc-xyz",
}),
});
await waitFor(() => {
expect(result.current.data).toBe(fakeTable);
});
expect(mockFetchArrow).toHaveBeenCalledTimes(1);
expect(mockFetchArrow).toHaveBeenCalledWith(
"/api/analytics/arrow-result/inline-abc-xyz",
);
});
test("surfaces an error when the arrow fetch fails", async () => {
mockFetchArrow.mockRejectedValueOnce(new Error("network"));
const { result } = renderHook(() =>
useAnalyticsQuery("q", null, { format: "ARROW_STREAM" }),
);
await lastConnectArgs.onMessage({
data: JSON.stringify({ type: "arrow", statement_id: "stmt-1" }),
});
await waitFor(() => {
expect(result.current.error).toBe(
"Unable to load data, please try again",
);
});
expect(result.current.loading).toBe(false);
});
test("rejects the retired arrow_inline message type as schema-invalid", async () => {
// arrow_inline was the prior wire shape. The discriminated union no
// longer accepts it, so it falls through to the generic error/code
// branch — but critically, it must NEVER trigger ArrowClient calls.
const { result } = renderHook(() =>
useAnalyticsQuery("q", null, { format: "ARROW_STREAM" }),
);
await lastConnectArgs.onMessage({
data: JSON.stringify({ type: "arrow_inline", attachment: "AQID" }),
});
await waitFor(() => {
expect(
result.current.loading ||
result.current.error ||
result.current.data === null,
).toBeTruthy();
});
expect(mockProcessArrowBuffer).not.toHaveBeenCalled();
expect(mockFetchArrow).not.toHaveBeenCalled();
});
test("normalizes an empty result message (no data field) to []", async () => {
// The wire schema makes `data` optional — empty result sets may omit
// it. The hook must surface that as an explicit empty array rather
// than `undefined`, so callers can rely on `data` being either null
// (no message yet) or a value of the inferred result type.
const { result } = renderHook(() =>
useAnalyticsQuery("q", null, { format: "JSON_ARRAY" }),
);
await lastConnectArgs.onMessage({
data: JSON.stringify({ type: "result" }),
});
await waitFor(() => {
expect(result.current.data).toEqual([]);
});
expect(result.current.loading).toBe(false);
expect(result.current.error).toBeNull();
});
test("still handles type:result rows for JSON_ARRAY", async () => {
const { result } = renderHook(() =>
useAnalyticsQuery("q", null, { format: "JSON_ARRAY" }),
);
await lastConnectArgs.onMessage({
data: JSON.stringify({
type: "result",
data: [{ id: 1 }, { id: 2 }],
}),
});
await waitFor(() => {
expect(result.current.data).toEqual([{ id: 1 }, { id: 2 }]);
});
expect(mockProcessArrowBuffer).not.toHaveBeenCalled();
expect(mockFetchArrow).not.toHaveBeenCalled();
});
test("a malformed (non-JSON) SSE payload clears loading and surfaces an error — does not strand the hook in loading=true", async () => {
// A `JSON.parse` failure inside the SSE handler used to be swallowed
// by the outer catch with only a console.warn, leaving the hook
// permanently in `loading=true` with no error surfaced. The UI would
// spin forever. The handler now reports a user-facing error so the
// consumer can render a retry affordance.
const { result } = renderHook(() =>
useAnalyticsQuery("q", null, { format: "JSON_ARRAY" }),
);
await lastConnectArgs.onMessage({ data: "not-json{" });
await waitFor(() => {
expect(result.current.loading).toBe(false);
});
expect(result.current.error).toBe("Unable to load data, please try again");
expect(result.current.data).toBeNull();
});
test("a server error event carrying a structured errorCode + requestId exposes both on the hook return value", async () => {
// The SSE error broadcaster forwards `errorCode` (for UI branching)
// and `requestId` (for support triage — same id appears in the
// server-side logger.error line). The hook surfaces both so
// consumers can render "Error ref: <requestId>" alongside the
// human message and branch behavior on the stable errorCode.
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const { result } = renderHook(() =>
useAnalyticsQuery("q", null, { format: "ARROW_STREAM" }),
);
await lastConnectArgs.onMessage({
data: JSON.stringify({
type: "error",
error: "Server is at capacity, please retry",
code: "UPSTREAM_ERROR",
errorCode: "INLINE_ARROW_STASH_EXHAUSTED",
requestId: "11111111-2222-3333-4444-555555555555",
}),
});
await waitFor(() => {
expect(result.current.error).toBe("Server is at capacity, please retry");
});
expect(result.current.loading).toBe(false);
expect(result.current.errorCode).toBe("INLINE_ARROW_STASH_EXHAUSTED");
expect(result.current.requestId).toBe(
"11111111-2222-3333-4444-555555555555",
);
errorSpy.mockRestore();
});
test("does not refetch when params object is structurally equal across renders", () => {
const { rerender } = renderHook(
({ limit }: { limit: number }) =>
// biome-ignore lint/suspicious/noExplicitAny: typed registry not available in tests
useAnalyticsQuery("test_query" as any, { limit } as any),
{ initialProps: { limit: 10 } },
);
expect(mockConnectSSE).toHaveBeenCalledTimes(1);
rerender({ limit: 10 });
rerender({ limit: 10 });
rerender({ limit: 10 });
expect(mockConnectSSE).toHaveBeenCalledTimes(1);
});
test("does refetch when a param value actually changes", () => {
const { rerender } = renderHook(
({ limit }: { limit: number }) =>
// biome-ignore lint/suspicious/noExplicitAny: typed registry not available in tests
useAnalyticsQuery("test_query" as any, { limit } as any),
{ initialProps: { limit: 10 } },
);
expect(mockConnectSSE).toHaveBeenCalledTimes(1);
rerender({ limit: 20 });
expect(mockConnectSSE).toHaveBeenCalledTimes(2);
});
test("does not refetch when params is undefined across renders", () => {
const { rerender } = renderHook(() =>
// biome-ignore lint/suspicious/noExplicitAny: typed registry not available in tests
useAnalyticsQuery("test_query" as any),
);
expect(mockConnectSSE).toHaveBeenCalledTimes(1);
rerender();
rerender();
expect(mockConnectSSE).toHaveBeenCalledTimes(1);
});
test("treats two empty object literals as equal", () => {
const { rerender } = renderHook(() =>
// biome-ignore lint/suspicious/noExplicitAny: typed registry not available in tests
useAnalyticsQuery("test_query" as any, {} as any),
);
expect(mockConnectSSE).toHaveBeenCalledTimes(1);
rerender();
rerender();
expect(mockConnectSSE).toHaveBeenCalledTimes(1);
});
});