Skip to content

Commit 0bb51f4

Browse files
committed
test(console): pin the cascade line on the row and record-page delete confirmations
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibvGtYbnKXjz3iks1AW
1 parent 53c15e0 commit 0bb51f4

4 files changed

Lines changed: 488 additions & 0 deletions

File tree

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#28472 — the console list's row Delete (and the selection's)
11+
* names the objects the delete cascades into, from the served
12+
* `cascadeDeleteObjects`, by label.
13+
*
14+
* The list's `objectDef` comes from the list read, which never serves the key,
15+
* so the hook reads the by-name schema the adapter carries it on
16+
* (`dataSource.getObjectSchema`). The data source here hands back exactly what
17+
* the adapter would: a schema with the served list attached under its symbol.
18+
* Strings are read from the packs by KEY under a real `I18nProvider`.
19+
*/
20+
21+
import * as React from 'react';
22+
import { describe, it, expect, vi, afterEach } from 'vitest';
23+
import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react';
24+
import { MemoryRouter } from 'react-router-dom';
25+
import { I18nProvider } from '@object-ui/i18n';
26+
import { builtInLocales } from '@object-ui/i18n/locales';
27+
import { attachCascadeDeleteObjects, type ConfirmationHandler } from '@object-ui/core';
28+
29+
vi.mock('sonner', () => ({
30+
toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }),
31+
}));
32+
33+
import { useObjectActions } from '../useObjectActions';
34+
35+
type Pack = {
36+
objectActions: { deleteConfirm: string; deleteCascade: string };
37+
console: { objectView: { bulkDeleteConfirm_other: string } };
38+
};
39+
const EN = builtInLocales.en as unknown as Pack;
40+
const ZH = builtInLocales.zh as unknown as Pack;
41+
const fill = (template: string, vars: Record<string, string | number>) =>
42+
template.replace(/\{\{(\w+)\}\}/g, (_m, k: string) => String(vars[k]));
43+
44+
const LEAD = { name: 'crm_lead', label: 'Lead', fields: { name: { type: 'text' } } };
45+
const LABELS: Record<string, string> = { crm_campaign_member: 'Campaign Member' };
46+
const objectLabelOf = (name: string) => LABELS[name] ?? name;
47+
48+
function Harness({ dataSource, onConfirm }: { dataSource: any; onConfirm: ConfirmationHandler }) {
49+
const actions = useObjectActions({
50+
objectName: LEAD.name,
51+
objectLabel: LEAD.label,
52+
objectDef: LEAD,
53+
dataSource,
54+
onConfirm,
55+
objectLabelOf,
56+
});
57+
return (
58+
<>
59+
<button onClick={() => void actions.deleteRecord('l1', { id: 'l1', name: 'Ada' })}>row-delete</button>
60+
<button onClick={() => void actions.deleteRecords([{ id: 'a' }, { id: 'b' }])}>bulk-delete</button>
61+
</>
62+
);
63+
}
64+
65+
/** Mount with a data source whose by-name schema read answers `served`. */
66+
function mount(served: unknown, language: 'en' | 'zh' = 'en') {
67+
const getObjectSchema = vi.fn(async () =>
68+
served === 'throw'
69+
? Promise.reject(new Error('offline'))
70+
: attachCascadeDeleteObjects(structuredClone(LEAD), served),
71+
);
72+
const dataSource = { delete: vi.fn(async () => ({})), getObjectSchema };
73+
const onConfirm = vi.fn<ConfirmationHandler>(async () => false);
74+
render(
75+
<I18nProvider config={{ defaultLanguage: language, detectBrowserLanguage: false }} persistLanguage={false}>
76+
<MemoryRouter initialEntries={['/apps/crm/crm_lead']}>
77+
<Harness dataSource={dataSource} onConfirm={onConfirm} />
78+
</MemoryRouter>
79+
</I18nProvider>,
80+
);
81+
return { onConfirm, getObjectSchema, dataSource };
82+
}
83+
84+
async function askedMessage(onConfirm: ReturnType<typeof vi.fn>, button: string): Promise<string> {
85+
fireEvent.click(screen.getByText(button));
86+
await waitFor(() => expect(onConfirm).toHaveBeenCalledTimes(1));
87+
return onConfirm.mock.calls[0][0] as string;
88+
}
89+
90+
afterEach(() => {
91+
cleanup();
92+
vi.clearAllMocks();
93+
});
94+
95+
describe('console row Delete names the cascade objects (objectstack#28472)', () => {
96+
it('a served list of one object adds one line naming its label', async () => {
97+
const { onConfirm, getObjectSchema } = mount(['crm_campaign_member']);
98+
const message = await askedMessage(onConfirm, 'row-delete');
99+
expect(getObjectSchema).toHaveBeenCalledWith('crm_lead');
100+
expect(message).toBe(
101+
`${EN.objectActions.deleteConfirm} ${fill(EN.objectActions.deleteCascade, { objects: 'Campaign Member' })}`,
102+
);
103+
expect(message).not.toContain('crm_campaign_member');
104+
});
105+
106+
it('the same line in zh', async () => {
107+
const { onConfirm } = mount(['crm_campaign_member'], 'zh');
108+
const message = await askedMessage(onConfirm, 'row-delete');
109+
expect(ZH.objectActions.deleteCascade).not.toBe(EN.objectActions.deleteCascade);
110+
expect(message).toBe(
111+
`${ZH.objectActions.deleteConfirm} ${fill(ZH.objectActions.deleteCascade, { objects: 'Campaign Member' })}`,
112+
);
113+
});
114+
115+
it('a served empty list adds nothing', async () => {
116+
const { onConfirm } = mount([]);
117+
expect(await askedMessage(onConfirm, 'row-delete')).toBe(EN.objectActions.deleteConfirm);
118+
});
119+
120+
it('no served list adds nothing and keeps today\'s text', async () => {
121+
const { onConfirm } = mount(undefined);
122+
expect(await askedMessage(onConfirm, 'row-delete')).toBe(EN.objectActions.deleteConfirm);
123+
});
124+
125+
it('a failed schema read adds nothing and still asks', async () => {
126+
const { onConfirm, dataSource } = mount('throw');
127+
expect(await askedMessage(onConfirm, 'row-delete')).toBe(EN.objectActions.deleteConfirm);
128+
expect(dataSource.delete).not.toHaveBeenCalled();
129+
});
130+
131+
it('a selection gains the same line after the batch question', async () => {
132+
const { onConfirm } = mount(['crm_campaign_member']);
133+
const message = await askedMessage(onConfirm, 'bulk-delete');
134+
expect(message).toBe(
135+
`${fill(EN.console.objectView.bulkDeleteConfirm_other, { count: 2 })} ${fill(EN.objectActions.deleteCascade, { objects: 'Campaign Member' })}`,
136+
);
137+
});
138+
});
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#28472 — the record page's Delete confirmation names the objects
11+
* the delete cascades into, from the served `cascadeDeleteObjects`, by label.
12+
*
13+
* The page's `objectDef` is the list read's entry, which never serves the key,
14+
* so the page reads the by-name schema the adapter carries it on
15+
* (`dataSource.getObjectSchema`); the data source here answers exactly what
16+
* the adapter would. The REAL `ActionConfirmDialog` opens, and its body is
17+
* read. Strings are read from the packs by KEY.
18+
*/
19+
20+
import * as React from 'react';
21+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
22+
import { render, screen, waitFor, fireEvent, cleanup, within } from '@testing-library/react';
23+
import '@testing-library/jest-dom';
24+
import { MemoryRouter } from 'react-router-dom';
25+
import { builtInLocales } from '@object-ui/i18n/locales';
26+
import { attachCascadeDeleteObjects } from '@object-ui/core';
27+
28+
vi.mock('@object-ui/auth', async (importOriginal) => ({
29+
...(await importOriginal<Record<string, unknown>>()),
30+
useAuth: () => ({ user: { id: 'u1', name: 'Ada', image: null }, activeOrganization: null }),
31+
createAuthenticatedFetch: () => vi.fn(),
32+
}));
33+
34+
vi.mock('@object-ui/collaboration', async (importOriginal) => ({
35+
...(await importOriginal<Record<string, unknown>>()),
36+
useRecordPresence: () => [],
37+
PresenceAvatars: () => null,
38+
}));
39+
40+
vi.mock('sonner', () => ({
41+
toast: Object.assign(vi.fn(), {
42+
success: vi.fn(),
43+
error: vi.fn(),
44+
info: vi.fn(),
45+
warning: vi.fn(),
46+
loading: vi.fn(),
47+
dismiss: vi.fn(),
48+
}),
49+
}));
50+
51+
vi.mock('./ActionParamDialog', () => ({ ActionParamDialog: () => null }));
52+
vi.mock('./ActionResultDialog', () => ({ ActionResultDialog: () => null }));
53+
vi.mock('./FlowRunner', () => ({ FlowRunner: () => null }));
54+
vi.mock('./MetadataInspector', () => ({
55+
MetadataPanel: () => null,
56+
useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }),
57+
}));
58+
59+
import { I18nProvider } from '@object-ui/i18n';
60+
import { MetadataCtx } from '@object-ui/react';
61+
import { RecordDetailView } from './RecordDetailView';
62+
63+
const OBJECT_NAME = 'crm_lead';
64+
const RECORD_ID = 'rec-lead-1';
65+
66+
type Pack = {
67+
detail: { delete: string; moreActions: string };
68+
objectActions: { deleteConfirm: string; deleteCascade: string };
69+
};
70+
const EN = builtInLocales.en as unknown as Pack;
71+
const fill = (template: string, vars: Record<string, string>) =>
72+
template.replace(/\{\{(\w+)\}\}/g, (_m, k: string) => vars[k]);
73+
74+
const LEAD = {
75+
name: OBJECT_NAME,
76+
label: 'Lead',
77+
managedBy: 'platform',
78+
fields: { id: { type: 'text', label: 'Id' }, name: { type: 'text', label: 'Name' } },
79+
};
80+
const CAMPAIGN_MEMBER = {
81+
name: 'crm_campaign_member',
82+
label: 'Campaign Member',
83+
managedBy: 'platform',
84+
fields: { name: { type: 'text', label: 'Name' } },
85+
};
86+
const OBJECTS = [LEAD, CAMPAIGN_MEMBER];
87+
88+
const METADATA = {
89+
objects: OBJECTS,
90+
pages: [],
91+
loading: false,
92+
error: null,
93+
refresh: async () => {},
94+
invalidate: () => {},
95+
ensureType: async () => [],
96+
getItem: async () => null,
97+
getItemsByType: () => [],
98+
} as any;
99+
100+
/** A data source whose by-name schema read answers `served`, as the adapter would. */
101+
function makeDataSource(served: unknown) {
102+
return {
103+
find: vi.fn(async () => ({ data: [] })),
104+
findOne: vi.fn(async () => ({ id: RECORD_ID, name: 'Ada' })),
105+
create: vi.fn(async () => ({})),
106+
update: vi.fn(async () => ({})),
107+
delete: vi.fn(async () => ({})),
108+
getObjectSchema: vi.fn(async (name: string) =>
109+
name === OBJECT_NAME ? attachCascadeDeleteObjects(structuredClone(LEAD), served) : null,
110+
),
111+
} as any;
112+
}
113+
114+
async function openDeleteConfirm(served: unknown): Promise<HTMLElement> {
115+
const dataSource = makeDataSource(served);
116+
render(
117+
<I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }} persistLanguage={false}>
118+
<MemoryRouter initialEntries={[`/apps/crm/${OBJECT_NAME}/${RECORD_ID}`]}>
119+
<MetadataCtx.Provider value={METADATA}>
120+
<RecordDetailView
121+
dataSource={dataSource}
122+
objects={OBJECTS}
123+
onEdit={() => {}}
124+
objectNameOverride={OBJECT_NAME}
125+
recordIdOverride={RECORD_ID}
126+
/>
127+
</MetadataCtx.Provider>
128+
</MemoryRouter>
129+
</I18nProvider>,
130+
);
131+
await waitFor(() => expect(dataSource.findOne).toHaveBeenCalled());
132+
await waitFor(() => expect(document.querySelector('[role="toolbar"]')).toBeTruthy());
133+
const trigger = screen.getByRole('button', { name: EN.detail.moreActions });
134+
fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false, pointerType: 'mouse' });
135+
await waitFor(() => expect(screen.getByRole('menu')).toBeInTheDocument());
136+
const item = screen
137+
.getAllByRole('menuitem')
138+
.find((el) => (el.textContent ?? '').trim() === EN.detail.delete);
139+
expect(item).toBeTruthy();
140+
fireEvent.click(item!);
141+
const dialog = await screen.findByRole('alertdialog');
142+
expect(dataSource.delete).not.toHaveBeenCalled();
143+
return dialog;
144+
}
145+
146+
/** The dialog body: the description under the title. */
147+
function body(dialog: HTMLElement): string {
148+
const heading = within(dialog).getByRole('heading');
149+
const description = heading.parentElement?.querySelector('p');
150+
return (description?.textContent ?? '').trim();
151+
}
152+
153+
beforeEach(() => {
154+
cleanup();
155+
vi.stubGlobal(
156+
'fetch',
157+
vi.fn(async () =>
158+
new Response(JSON.stringify({ data: [] }), {
159+
status: 200,
160+
headers: { 'content-type': 'application/json' },
161+
}),
162+
),
163+
);
164+
});
165+
166+
afterEach(() => {
167+
vi.unstubAllGlobals();
168+
vi.clearAllMocks();
169+
});
170+
171+
describe('record page Delete names the cascade objects (objectstack#28472)', () => {
172+
it('a served list of one object adds one line naming its label', async () => {
173+
const dialog = await openDeleteConfirm(['crm_campaign_member']);
174+
expect(body(dialog)).toBe(
175+
`${EN.objectActions.deleteConfirm} ${fill(EN.objectActions.deleteCascade, { objects: 'Campaign Member' })}`,
176+
);
177+
});
178+
179+
it('a served empty list adds nothing', async () => {
180+
const dialog = await openDeleteConfirm([]);
181+
expect(body(dialog)).toBe(EN.objectActions.deleteConfirm);
182+
});
183+
184+
it('no served list adds nothing and keeps today\'s text', async () => {
185+
const dialog = await openDeleteConfirm(undefined);
186+
expect(body(dialog)).toBe(EN.objectActions.deleteConfirm);
187+
});
188+
});

0 commit comments

Comments
 (0)