-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathobjectBulkActionDispatch.test.tsx
More file actions
222 lines (195 loc) · 8.34 KB
/
Copy pathobjectBulkActionDispatch.test.tsx
File metadata and controls
222 lines (195 loc) · 8.34 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
/**
* 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.
*/
/**
* A view's `bulkActions` name must reach the ActionRunner as a real action
* DEF, applied to every selected record (objectui#3002).
*
* Before this, `bulkActions: ['push_down']` dispatched the action NAME in the
* runner's `type` slot — `{ type: 'push_down', params: { records } }` — which
* matches no built-in type and no handler, so it fell through the runner's
* schema fallback (green success toast pre-#2996, a loud failure after it).
* Either way the action never ran, and the button carried none of the def's
* label / icon / params: `bulkActionDefs` was passed through from view JSON
* verbatim, never resolved against `objectDef.actions`.
*
* Naming the action in the view is the ONLY way to declare a bulk action —
* spec 17 retired `action.bulkEnabled` as a tombstone (framework#4054) and
* prescribes exactly this. See `resolveBulkActions`.
*
* These drive the REAL ObjectGrid through a real ActionProvider and assert the
* user-visible outcome: selecting rows and clicking the button issues one
* request per selected record.
*/
import { describe, it, expect, vi, beforeEach, afterEach, beforeAll } from 'vitest';
import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react';
import '@testing-library/jest-dom';
import React from 'react';
vi.mock('@object-ui/permissions', () => ({
usePermissions: () => ({ isLoaded: false, checkField: () => true, getObjectApiOperations: () => undefined }),
}));
import { ObjectGrid } from '../ObjectGrid';
import { registerAllFields } from '@object-ui/fields';
import { ActionProvider } from '@object-ui/react';
registerAllFields();
beforeAll(() => {
if (!Element.prototype.scrollIntoView) {
Element.prototype.scrollIntoView = vi.fn() as any;
}
});
const OBJECT = 'os_prod_plan';
const ROWS = [
{ id: 'r1', name: 'Plan A' },
{ id: 'r2', name: 'Plan B' },
];
/**
* The object's declared action. The label is deliberately NOT the humanization
* of the name ("Push Down"), so an assertion on it distinguishes the resolved
* def from the by-name path — which could only ever render
* `formatActionLabel`.
*/
const PUSH_DOWN = {
name: 'push_down',
label: '下推',
type: 'api',
target: '/api/v1/plans/push',
recordIdParam: 'planId',
};
let fetchMock: ReturnType<typeof vi.fn>;
function renderGrid(opts: {
objectActions?: unknown[];
schema?: Record<string, unknown>;
handlers?: Record<string, any>;
}) {
const dataSource: any = {
find: vi.fn(async () => ({ data: ROWS.map(r => ({ ...r })), total: ROWS.length, hasMore: false, pageSize: 50 })),
getObjectSchema: async (name: string) => ({
name,
fields: { id: { type: 'text' }, name: { type: 'text', label: 'Name' } },
...(opts.objectActions ? { actions: opts.objectActions } : {}),
}),
};
const schema: any = {
type: 'object-grid',
objectName: OBJECT,
columns: [{ field: 'name', label: 'Name' }],
pagination: { pageSize: 50 },
...opts.schema,
};
render(
<ActionProvider handlers={opts.handlers ?? {}}>
<ObjectGrid schema={schema} dataSource={dataSource} />
</ActionProvider>,
);
return dataSource;
}
/** Render, wait for rows + the async schema fetch, then select every row. */
async function renderAndSelectAll(opts: Parameters<typeof renderGrid>[0]) {
const ds = renderGrid(opts);
await waitFor(() => expect(screen.getByText('Plan A')).toBeInTheDocument());
// The derivation depends on `getObjectSchema`, so an assertion taken before
// it lands would read the pre-fetch (underived) state.
await waitFor(() => expect(document.querySelector('thead [role="checkbox"]')).toBeTruthy());
fireEvent.click(document.querySelector('thead [role="checkbox"]') as HTMLElement);
return ds;
}
beforeEach(() => {
fetchMock = vi.fn().mockResolvedValue({
ok: true,
status: 200,
statusText: 'OK',
headers: { get: () => 'application/json' },
json: async () => ({ success: true }),
});
vi.stubGlobal('fetch', fetchMock);
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
describe('view-declared bulk actions (objectui#3002)', () => {
it('renders the declared action label, not the humanized name', async () => {
await renderAndSelectAll({
objectActions: [PUSH_DOWN],
schema: { bulkActions: ['push_down'] },
});
const button = await screen.findByTestId('bulk-action-push_down');
// The object action's own label, not `formatActionLabel('push_down')`.
expect(button).toHaveTextContent('下推');
});
it('surfaces nothing for an object action the view never names', async () => {
// `action.bulkEnabled` is a spec-17 tombstone, so there is no object-level
// opt-in: an unnamed action must not reach the selection bar.
renderGrid({ objectActions: [{ ...PUSH_DOWN, bulkEnabled: true }] });
await waitFor(() => expect(screen.getByText('Plan A')).toBeInTheDocument());
expect(screen.queryByTestId('bulk-action-push_down')).not.toBeInTheDocument();
});
it('issues one request per selected record instead of no-opping', async () => {
await renderAndSelectAll({
objectActions: [PUSH_DOWN],
schema: { bulkActions: ['push_down'] },
});
fireEvent.click(await screen.findByTestId('bulk-action-push_down'));
// No params on this action → the dialog opens straight on confirm.
fireEvent.click(await screen.findByRole('button', { name: 'Run' }));
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/plans/push');
// Each dispatch carries ITS OWN record under `_rowRecord` — the same
// row-context key the list_item path attaches, which is what lets the
// host's api handler perform `recordIdParam` injection unchanged.
const sentIds = fetchMock.mock.calls
.map(c => JSON.parse((c[1] as any).body)._rowRecord.id)
.sort();
expect(sentIds).toEqual(['r1', 'r2']);
});
it('reports per-record failures instead of counting them as successes', async () => {
fetchMock.mockResolvedValue({
ok: false,
status: 422,
statusText: 'Unprocessable Entity',
headers: { get: () => 'application/json' },
json: async () => ({ error: 'precondition not met' }),
});
await renderAndSelectAll({
objectActions: [PUSH_DOWN],
schema: { bulkActions: ['push_down'] },
});
fireEvent.click(await screen.findByTestId('bulk-action-push_down'));
fireEvent.click(await screen.findByRole('button', { name: 'Run' }));
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
// The result panel attributes a failure to each record — a runAction that
// resolved regardless would report "Succeeded 2 / 2", the #2960 lie in bulk
// form (and exactly what `operation: 'custom'` did before it could run).
await waitFor(() => expect(screen.getByText(/Succeeded 0 \/ 2/)).toBeInTheDocument());
expect(screen.getByTestId('bulk-error-row-r1')).toHaveTextContent('HTTP 422');
expect(screen.getByTestId('bulk-error-row-r2')).toBeInTheDocument();
// A promoted def re-dispatches for one record, so the row keeps its Retry.
expect(screen.getByTestId('bulk-error-retry-r1')).toBeInTheDocument();
});
it('renders one button for a repeated name', async () => {
await renderAndSelectAll({
objectActions: [PUSH_DOWN],
schema: { bulkActions: ['push_down', 'push_down'] },
});
await waitFor(() => expect(screen.getAllByTestId('bulk-action-push_down')).toHaveLength(1));
});
it('keeps an unresolvable name alongside the promoted defs', async () => {
// A name the object never declared may still have a runner handler
// registered under it; hiding it because some OTHER def exists dropped
// half the bar's buttons.
const handler = vi.fn(async () => ({ success: true }));
await renderAndSelectAll({
objectActions: [PUSH_DOWN],
schema: { bulkActions: ['push_down', 'crm_only_handler'] },
handlers: { crm_only_handler: handler },
});
expect(await screen.findByTestId('bulk-action-push_down')).toBeInTheDocument();
const legacy = await screen.findByTestId('bulk-action-crm_only_handler');
fireEvent.click(legacy);
await waitFor(() => expect(handler).toHaveBeenCalledTimes(1));
});
});