-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathuseConsoleActionRuntime.test.tsx
More file actions
437 lines (375 loc) · 17 KB
/
Copy pathuseConsoleActionRuntime.test.tsx
File metadata and controls
437 lines (375 loc) · 17 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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* Focused coverage for the shared console action runtime (#1605) — the wiring
* extracted from ObjectView so PageView can mount it too. We exercise the
* authenticated handlers directly (regression coverage for ObjectView, which
* delegates to them) and end-to-end through the provider + an `action:button`'s
* `useAction()` consumer (PageView action execution).
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, screen, fireEvent, waitFor, renderHook, act } from '@testing-library/react';
import React from 'react';
const navigateSpy = vi.fn();
vi.mock('react-router-dom', () => ({ useNavigate: () => navigateSpy }));
const authFetchSpy = vi.fn();
vi.mock('@object-ui/auth', () => ({
useAuth: () => ({ user: { id: 'u1', name: 'User', image: null }, activeOrganization: null }),
createAuthenticatedFetch: () => authFetchSpy,
}));
vi.mock('@object-ui/i18n', () => ({
useObjectLabel: () => ({
fieldLabel: (_o: any, _n: any, l: any) => l,
fieldOptionLabel: (_o: any, _f: any, _v: any, l: any) => l,
actionParamText: (_o: any, _a: any, _p: any, _attr: any, fallback: any) => fallback,
actionParamOptionLabel: (_o: any, _a: any, _p: any, _v: any, fallback: any) => fallback,
actionDescription: (_o: any, _a: any, fallback: any) => fallback,
}),
}));
// The dialogs/flow-runner are not exercised here — keep them as inert stubs so
// the hook module imports cheaply.
vi.mock('../../views/ActionConfirmDialog', () => ({ ActionConfirmDialog: () => null }));
vi.mock('../../views/ActionParamDialog', () => ({ ActionParamDialog: () => null }));
vi.mock('../../views/ActionResultDialog', () => ({ ActionResultDialog: () => null }));
vi.mock('../../views/FlowRunner', () => ({ FlowRunner: () => null }));
import { useConsoleActionRuntime, ConsoleActionRuntimeProvider } from '../useConsoleActionRuntime';
import { useAction, usePageVariables, PageVariablesProvider, PageVariableActionBridge } from '@object-ui/react';
beforeEach(() => {
authFetchSpy.mockReset();
navigateSpy.mockReset();
});
describe('useConsoleActionRuntime — authenticated handlers', () => {
it('apiHandler calls an absolute endpoint via the authenticated fetch and refreshes', async () => {
authFetchSpy.mockResolvedValue({ ok: true, json: async () => ({ id: 'env_1' }) });
const onRefresh = vi.fn();
const { result } = renderHook(() =>
useConsoleActionRuntime({ dataSource: {}, objects: [], onRefresh }),
);
let res: any;
await act(async () => {
res = await result.current.apiHandler({
type: 'api', name: 'createEnv', target: '/api/v1/environments', params: { name: 'prod' },
} as any);
});
expect(authFetchSpy).toHaveBeenCalledTimes(1);
const [url, init] = authFetchSpy.mock.calls[0];
expect(String(url)).toContain('/api/v1/environments');
expect(init.method).toBe('POST');
expect(JSON.parse(init.body)).toMatchObject({ name: 'prod' });
expect(res).toMatchObject({ success: true, data: { id: 'env_1' } });
expect(onRefresh).toHaveBeenCalledTimes(1);
});
it('apiHandler surfaces a failed response and does not refresh', async () => {
authFetchSpy.mockResolvedValue({ ok: false, status: 403, json: async () => ({ error: 'Forbidden' }) });
const onRefresh = vi.fn();
const { result } = renderHook(() =>
useConsoleActionRuntime({ dataSource: {}, objects: [], onRefresh }),
);
let res: any;
await act(async () => {
res = await result.current.apiHandler({ type: 'api', name: 'x', target: '/api/v1/x' } as any);
});
expect(res).toEqual({ success: false, error: 'Forbidden' });
expect(onRefresh).not.toHaveBeenCalled();
});
it('apiHandler merges bodyExtra into the dataSource update payload (pure-confirmation action)', async () => {
// A pure-confirmation action carries no params array; its mutation lives in
// `bodyExtra`. Without merging it, `fields` is empty and the update below is
// skipped — the confirmation "succeeds" but nothing is persisted.
const updateSpy = vi.fn().mockResolvedValue(undefined);
const onRefresh = vi.fn();
const { result } = renderHook(() =>
useConsoleActionRuntime({
dataSource: { update: updateSpy } as any,
objects: [],
objectName: 'work_order',
onRefresh,
}),
);
await act(async () => {
await result.current.apiHandler({
type: 'api', name: 'close', // non-absolute target → dataSource branch
params: { recordId: 'wo_1' },
bodyExtra: { status: 'closed', closed_at: '2026-06-18' },
} as any);
});
expect(updateSpy).toHaveBeenCalledTimes(1);
expect(updateSpy).toHaveBeenCalledWith('work_order', 'wo_1', { status: 'closed', closed_at: '2026-06-18' });
});
it('serverActionHandler targets /actions/global/<name> when no object is bound (page scope)', async () => {
authFetchSpy.mockResolvedValue({ ok: true, json: async () => ({ success: true, data: {} }) });
const { result } = renderHook(() =>
useConsoleActionRuntime({ dataSource: {}, objects: [] /* no objectName */ }),
);
let res: any;
await act(async () => {
res = await result.current.serverActionHandler({ type: 'script', name: 'provision' } as any);
});
expect(String(authFetchSpy.mock.calls[0][0])).toContain('/api/v1/actions/global/provision');
expect(res).toMatchObject({ success: true });
});
it('exposes ActionProvider props with the api/flow/script/modal handlers wired', () => {
const { result } = renderHook(() =>
useConsoleActionRuntime({ dataSource: {}, objects: [], objectName: 'inv' }),
);
const props = result.current.actionProviderProps;
expect(props.context.objectName).toBe('inv');
expect(Object.keys(props.handlers).sort()).toEqual(['api', 'flow', 'modal', 'script']);
expect(typeof props.onConfirm).toBe('function');
expect(typeof props.onParamCollection).toBe('function');
});
});
describe('flowHandler — list_toolbar selection fallback', () => {
// Toolbar-invoked flow actions carry no `_rowRecord` (that's a list_item /
// row-menu concept). The grid publishes its checkbox selection into the
// shared ActionRunner context as `selectedRecords`; with exactly one row
// selected the flow must receive that row's id as recordId, otherwise a
// record-bound flow node fails ("Update requires an ID or options.multi=true").
it('uses the single selected row from the runner context as recordId', async () => {
authFetchSpy.mockResolvedValue({ ok: true, json: async () => ({ success: true, data: {} }) });
const { result } = renderHook(() =>
useConsoleActionRuntime({ dataSource: {}, objects: [], objectName: 'inv' }),
);
let res: any;
await act(async () => {
res = await result.current.flowHandler(
{ type: 'flow', name: 'showcase_bulk_reassign', target: 'showcase_reassign_wizard' } as any,
{ selectedRecords: [{ id: 'rec_42', name: 'Acme' }] } as any,
);
});
expect(res).toMatchObject({ success: true });
const [url, init] = authFetchSpy.mock.calls[0];
expect(String(url)).toContain('/api/v1/automation/showcase_reassign_wizard/trigger');
const body = JSON.parse(init.body);
expect(body.recordId).toBe('rec_42');
expect(body.params.recordId).toBe('rec_42');
});
it('blocks with an error (no trigger call) when multiple rows are selected', async () => {
const { result } = renderHook(() =>
useConsoleActionRuntime({ dataSource: {}, objects: [] }),
);
let res: any;
await act(async () => {
res = await result.current.flowHandler(
{ type: 'flow', target: 'showcase_reassign_wizard' } as any,
{ selectedRecords: [{ id: 'a' }, { id: 'b' }] } as any,
);
});
expect(res.success).toBe(false);
expect(res.error).toMatch(/single record/i);
expect(authFetchSpy).not.toHaveBeenCalled();
});
it('an explicit _rowRecord (list_item invocation) still wins over the selection', async () => {
authFetchSpy.mockResolvedValue({ ok: true, json: async () => ({ success: true, data: {} }) });
const { result } = renderHook(() =>
useConsoleActionRuntime({ dataSource: {}, objects: [] }),
);
await act(async () => {
await result.current.flowHandler(
{ type: 'flow', target: 'f', params: { _rowRecord: { id: 'row_1' } } } as any,
{ selectedRecords: [{ id: 'other_1' }, { id: 'other_2' }] } as any,
);
});
expect(JSON.parse(authFetchSpy.mock.calls[0][1].body).recordId).toBe('row_1');
});
it('end-to-end: selection published via updateContext reaches the flow trigger', async () => {
authFetchSpy.mockResolvedValue({ ok: true, json: async () => ({ success: true, data: {} }) });
// Mirrors the real wiring: ObjectGrid calls `updateContext({ selectedRecords })`
// on the shared runner; the toolbar button then executes the flow action.
function Probe() {
const { execute, updateContext } = useAction();
return (
<button
onClick={() => {
updateContext({ selectedRecords: [{ id: 'sel_1' }] });
void execute({ type: 'flow', name: 'showcase_bulk_reassign', target: 'showcase_reassign_wizard' } as any);
}}
>
run-flow
</button>
);
}
render(
<ConsoleActionRuntimeProvider dataSource={{}} objects={[]}>
<Probe />
</ConsoleActionRuntimeProvider>,
);
fireEvent.click(screen.getByText('run-flow'));
await waitFor(() => expect(authFetchSpy).toHaveBeenCalled());
const [url, init] = authFetchSpy.mock.calls[0];
expect(String(url)).toContain('/api/v1/automation/showcase_reassign_wizard/trigger');
expect(JSON.parse(init.body).recordId).toBe('sel_1');
});
});
describe('serverActionHandler — list_toolbar selection fallback', () => {
it('uses the single selected row from the runner context as recordId', async () => {
authFetchSpy.mockResolvedValue({ ok: true, json: async () => ({ success: true, data: {} }) });
const { result } = renderHook(() =>
useConsoleActionRuntime({ dataSource: {}, objects: [], objectName: 'inv' }),
);
let res: any;
await act(async () => {
res = await result.current.serverActionHandler(
{ type: 'script', name: 'archive' } as any,
{ selectedRecords: [{ id: 'rec_7' }] } as any,
);
});
expect(res).toMatchObject({ success: true });
const [url, init] = authFetchSpy.mock.calls[0];
expect(String(url)).toContain('/api/v1/actions/inv/archive');
expect(JSON.parse(init.body).recordId).toBe('rec_7');
});
it('honors a custom recordIdField when resolving from the selection', async () => {
authFetchSpy.mockResolvedValue({ ok: true, json: async () => ({ success: true, data: {} }) });
const { result } = renderHook(() =>
useConsoleActionRuntime({ dataSource: {}, objects: [], objectName: 'inv' }),
);
await act(async () => {
await result.current.serverActionHandler(
{ type: 'script', name: 'archive', recordIdField: 'code' } as any,
{ selectedRecords: [{ id: 'rec_7', code: 'INV-001' }] } as any,
);
});
expect(JSON.parse(authFetchSpy.mock.calls[0][1].body).recordId).toBe('INV-001');
});
it('blocks with an error (no API call) when multiple rows are selected', async () => {
const { result } = renderHook(() =>
useConsoleActionRuntime({ dataSource: {}, objects: [], objectName: 'inv' }),
);
let res: any;
await act(async () => {
res = await result.current.serverActionHandler(
{ type: 'script', name: 'archive' } as any,
{ selectedRecords: [{ id: 'a' }, { id: 'b' }] } as any,
);
});
expect(res.success).toBe(false);
expect(res.error).toMatch(/single record/i);
expect(authFetchSpy).not.toHaveBeenCalled();
});
});
describe('ConsoleActionRuntimeProvider — page-level action execution', () => {
function Probe() {
const { execute } = useAction();
return (
<button onClick={() => execute({ type: 'api', name: 'createEnv', target: '/api/v1/environments' } as any)}>
run
</button>
);
}
it('an action:button consumer executes an api action through the runtime and triggers refresh', async () => {
authFetchSpy.mockResolvedValue({ ok: true, json: async () => ({}) });
const onRefresh = vi.fn();
render(
<ConsoleActionRuntimeProvider dataSource={{}} objects={[]} onRefresh={onRefresh}>
<Probe />
</ConsoleActionRuntimeProvider>,
);
fireEvent.click(screen.getByText('run'));
await waitFor(() => expect(authFetchSpy).toHaveBeenCalled());
expect(String(authFetchSpy.mock.calls[0][0])).toContain('/api/v1/environments');
await waitFor(() => expect(onRefresh).toHaveBeenCalled());
});
});
// ---------------------------------------------------------------------------
// Gap 2 — page-variable → submit bridge. apiHandler resolves `{{page.<var>}}`
// tokens in the request body against the live page-variable snapshot that
// PageVariableActionBridge publishes into the action context. This is the
// data-entry half of SDUI pages: an input writes a page variable, a submit
// button posts it.
// ---------------------------------------------------------------------------
describe('apiHandler — page-variable submit bridge', () => {
it('resolves {{page.<var>}} tokens in params from context.pageVariables (type-preserving)', async () => {
authFetchSpy.mockResolvedValue({ ok: true, json: async () => ({ ok: true }) });
const { result } = renderHook(() =>
useConsoleActionRuntime({ dataSource: {}, objects: [] }),
);
await act(async () => {
await result.current.apiHandler(
{
type: 'api',
name: 'onboard',
target: '/api/v1/cloud/onboarding/complete',
params: {
workspace_name: '{{page.workspaceName}}',
seats: '{{page.seats}}',
label: 'ws-{{page.subdomain}}',
},
} as any,
{ pageVariables: { workspaceName: 'Acme', seats: 5, subdomain: 'acme' } } as any,
);
});
const body = JSON.parse(authFetchSpy.mock.calls[0][1].body);
expect(body.workspace_name).toBe('Acme');
expect(body.seats).toBe(5); // whole-value token preserves the number type
expect(body.label).toBe('ws-acme'); // embedded token is string-interpolated
});
it('resolves {{page.<var>}} tokens in bodyExtra as well', async () => {
authFetchSpy.mockResolvedValue({ ok: true, json: async () => ({}) });
const { result } = renderHook(() =>
useConsoleActionRuntime({ dataSource: {}, objects: [] }),
);
await act(async () => {
await result.current.apiHandler(
{ type: 'api', name: 'x', target: '/api/v1/x', bodyExtra: { src: '{{page.subdomain}}' } } as any,
{ pageVariables: { subdomain: 'acme' } } as any,
);
});
expect(JSON.parse(authFetchSpy.mock.calls[0][1].body).src).toBe('acme');
});
it('passes tokens through verbatim when no pageVariables context is present (back-compat)', async () => {
authFetchSpy.mockResolvedValue({ ok: true, json: async () => ({}) });
const { result } = renderHook(() =>
useConsoleActionRuntime({ dataSource: {}, objects: [] }),
);
await act(async () => {
await result.current.apiHandler(
{ type: 'api', name: 'x', target: '/api/v1/x', params: { a: '{{page.missing}}' } } as any,
);
});
expect(JSON.parse(authFetchSpy.mock.calls[0][1].body).a).toBe('{{page.missing}}');
});
});
describe('PageVariableActionBridge — end-to-end submit loop', () => {
function FormProbe() {
const { setVariable } = usePageVariables();
const { execute } = useAction();
return (
<>
<button onClick={() => setVariable('workspaceName', 'Acme')}>type</button>
<button
onClick={() =>
void execute({
type: 'api',
name: 'onboard',
target: '/api/v1/cloud/onboarding/complete',
params: { workspace_name: '{{page.workspaceName}}' },
} as any)
}
>
submit
</button>
</>
);
}
it('input → page variable → submit posts the resolved value', async () => {
authFetchSpy.mockResolvedValue({ ok: true, json: async () => ({}) });
render(
<ConsoleActionRuntimeProvider dataSource={{}} objects={[]}>
<PageVariablesProvider definitions={[{ name: 'workspaceName', type: 'string', source: 'ws' }]}>
<PageVariableActionBridge />
<FormProbe />
</PageVariablesProvider>
</ConsoleActionRuntimeProvider>,
);
fireEvent.click(screen.getByText('type')); // writes page variable → bridge publishes snapshot
fireEvent.click(screen.getByText('submit')); // executes api action → apiHandler resolves token
await waitFor(() => expect(authFetchSpy).toHaveBeenCalled());
expect(JSON.parse(authFetchSpy.mock.calls[0][1].body).workspace_name).toBe('Acme');
});
});