forked from openedx/frontend-app-authoring
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLibrarySectionSubsectionPage.test.tsx
More file actions
413 lines (364 loc) · 18 KB
/
LibrarySectionSubsectionPage.test.tsx
File metadata and controls
413 lines (364 loc) · 18 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
import userEvent from '@testing-library/user-event';
import type MockAdapter from 'axios-mock-adapter';
import { QueryClient } from '@tanstack/react-query';
import { act } from 'react';
import {
initializeMocks,
fireEvent,
render,
screen,
waitFor,
} from '../../testUtils';
import {
getLibraryContainerApiUrl,
getLibraryContainerChildrenApiUrl,
} from '../data/api';
import {
mockContentLibrary,
mockXBlockFields,
mockGetContainerMetadata,
mockGetContainerChildren,
mockLibraryBlockMetadata,
} from '../data/api.mocks';
import { mockContentSearchConfig, mockGetBlockTypes, mockSearchResult } from '../../search-manager/data/api.mock';
import { mockClipboardEmpty } from '../../generic/data/api.mock';
import LibraryLayout from '../LibraryLayout';
import { ToastActionData } from '../../generic/toast-context';
import mockResult from '../__mocks__/subsection-single.json';
import { ContainerType } from '../../generic/key-utils';
const path = '/library/:libraryId/*';
const libraryTitle = mockContentLibrary.libraryData.title;
let axiosMock: MockAdapter;
let queryClient: QueryClient;
let mockShowToast: (message: string, action?: ToastActionData | undefined) => void;
mockClipboardEmpty.applyMock();
mockGetContainerMetadata.applyMock();
mockGetContainerChildren.applyMock();
mockContentSearchConfig.applyMock();
mockGetBlockTypes.applyMock();
mockContentLibrary.applyMock();
mockXBlockFields.applyMock();
mockLibraryBlockMetadata.applyMock();
const searchFilterfn = (requestData: any) => {
const queryFilter = requestData?.queries[0]?.filter?.[1];
const subsectionId = queryFilter?.split('usage_key IN ["')[1].split('"]')[0];
switch (subsectionId) {
case mockGetContainerMetadata.subsectionIdLoading:
return new Promise<any>(() => {});
case mockGetContainerMetadata.subsectionIdError:
return Promise.reject(new Error('Not found'));
default:
return mockResult;
}
};
mockSearchResult(mockResult, searchFilterfn);
const verticalSortableListCollisionDetection = jest.fn();
jest.mock('../../generic/DraggableList/verticalSortableList', () => ({
...jest.requireActual('../../generic/DraggableList/verticalSortableList'),
// Since jsdom (used by jest) does not support getBoundingClientRect function
// which is required for drag-n-drop calculations, we mock closestCorners fn
// from dnd-kit to return collided elements as per the test. This allows us to
// test all drag-n-drop handlers.
verticalSortableListCollisionDetection: () => verticalSortableListCollisionDetection(),
}));
describe('<LibrarySectionPage / LibrarySubsectionPage />', () => {
beforeEach(() => {
({ axiosMock, mockShowToast, queryClient } = initializeMocks());
});
afterEach(() => {
jest.clearAllMocks();
axiosMock.restore();
});
const renderLibrarySectionPage = (
containerId?: string,
libraryId?: string,
cType: ContainerType = ContainerType.Section,
childId?: string,
) => {
const libId = libraryId || mockContentLibrary.libraryId;
const defaultId = cType === ContainerType.Section
? mockGetContainerMetadata.sectionId
: mockGetContainerMetadata.subsectionId;
const cId = containerId || defaultId;
render(<LibraryLayout />, {
path,
routerProps: {
initialEntries: [childId
? `/library/${libId}/${cType}/${cId}/${childId}`
: `/library/${libId}/${cType}/${cId}`,
],
},
});
};
[
ContainerType.Section,
ContainerType.Subsection,
].forEach((cType) => {
const childType = cType === ContainerType.Section
? ContainerType.Subsection
: ContainerType.Unit;
let typeNamespace = 'lct';
if (cType === ContainerType.Unit) {
typeNamespace = 'lb';
}
it(`shows the spinner before the query is complete in ${cType} page`, async () => {
// This mock will never return data about the collection (it loads forever):
const cId = cType === ContainerType.Section
? mockGetContainerMetadata.sectionIdLoading
: mockGetContainerMetadata.subsectionIdLoading;
renderLibrarySectionPage(cId, undefined, cType);
const spinner = screen.getByRole('status');
expect(spinner.textContent).toEqual('Loading...');
});
it(`shows an error component if no ${cType} returned`, async () => {
// This mock will simulate incorrect section id
const cId = cType === ContainerType.Section
? mockGetContainerMetadata.sectionIdError
: mockGetContainerMetadata.subsectionIdError;
renderLibrarySectionPage(cId, undefined, cType);
const errorMessage = 'Not found';
expect(await screen.findByRole('alert')).toHaveTextContent(errorMessage);
});
it(`shows ${cType} data`, async () => {
const cId = cType === ContainerType.Section
? mockGetContainerMetadata.sectionId
: mockGetContainerMetadata.subsectionId;
renderLibrarySectionPage(cId, undefined, cType);
expect((await screen.findAllByText(libraryTitle))[0]).toBeInTheDocument();
// Container title -- on main page + sidebar
expect((await screen.findAllByText(`Test ${cType}`))[0]).toBeInTheDocument();
// Container info button shown
expect(await screen.findByRole('button', { name: new RegExp(`${cType} Info`, 'i') })).toBeInTheDocument();
// Reorder children buttons shown
expect((await screen.findAllByRole('button', { name: 'Drag to reorder' })).length).toEqual(3);
// Check all children components are rendered only once.
expect(await screen.findByText(`${childType} block 0`)).toBeInTheDocument();
expect(await screen.findByText(`${childType} block 1`)).toBeInTheDocument();
expect(await screen.findByText(`${childType} block 2`)).toBeInTheDocument();
// Check no Preview tab is shown
expect(screen.queryByText('Preview')).not.toBeInTheDocument();
});
it(`shows ${cType} data with no children`, async () => {
const cId = cType === ContainerType.Section
? mockGetContainerMetadata.sectionIdEmpty
: mockGetContainerMetadata.subsectionIdEmpty;
renderLibrarySectionPage(cId, undefined, cType);
expect((await screen.findAllByText(libraryTitle))[0]).toBeInTheDocument();
// Container title -- rendered on main page + sidebar
expect((await screen.findAllByText(`Test ${cType}`))[0]).toBeInTheDocument();
// Container info button shown
expect(await screen.findByRole('button', { name: new RegExp(`${cType} Info`, 'i') })).toBeInTheDocument();
// Check "no children" text is rendered.
expect(await screen.findByText(`This ${cType} is empty`)).toBeInTheDocument();
// Check no Preview tab is shown
expect(screen.queryByText('Preview')).not.toBeInTheDocument();
});
it(`can rename ${cType}`, async () => {
const cId = cType === ContainerType.Section
? mockGetContainerMetadata.sectionId
: mockGetContainerMetadata.subsectionId;
renderLibrarySectionPage(cId, undefined, cType);
expect((await screen.findAllByText(libraryTitle))[0]).toBeInTheDocument();
expect((await screen.findAllByText(`Test ${cType}`))[0]).toBeInTheDocument();
const editContainerTitleButton = (await screen.findAllByRole(
'button',
{ name: /edit/i },
))[0]; // 0 is the Section/Subsection Title, 1 is the first child on the list
fireEvent.click(editContainerTitleButton);
const url = getLibraryContainerApiUrl(cId);
axiosMock.onPatch(url).reply(200);
expect(await screen.findByRole('textbox', { name: /text input/i })).toBeInTheDocument();
const textBox = await screen.findByRole('textbox', { name: /text input/i });
expect(textBox).toBeInTheDocument();
fireEvent.change(textBox, { target: { value: `New ${cType} Title` } });
fireEvent.keyDown(textBox, { key: 'Enter', code: 'Enter', charCode: 13 });
await waitFor(() => {
expect(axiosMock.history.patch[0].url).toEqual(url);
});
expect(axiosMock.history.patch[0].data).toEqual(JSON.stringify({ display_name: `New ${cType} Title` }));
expect(textBox).not.toBeInTheDocument();
expect(mockShowToast).toHaveBeenCalledWith('Container updated successfully.');
});
it(`show error if renaming ${cType} fails`, async () => {
const cId = cType === ContainerType.Section
? mockGetContainerMetadata.sectionId
: mockGetContainerMetadata.subsectionId;
renderLibrarySectionPage(cId, undefined, cType);
expect((await screen.findAllByText(libraryTitle))[0]).toBeInTheDocument();
expect((await screen.findAllByText(`Test ${cType}`))[0]).toBeInTheDocument();
const editContainerTitleButton = (await screen.findAllByRole(
'button',
{ name: /edit/i },
))[0]; // 0 is the Section/subsection Title, 1 is the first child on the list
fireEvent.click(editContainerTitleButton);
const url = getLibraryContainerApiUrl(cId);
axiosMock.onPatch(url).reply(400);
await waitFor(() => {
expect(screen.getByRole('textbox', { name: /text input/i })).toBeInTheDocument();
});
const textBox = screen.getByRole('textbox', { name: /text input/i });
expect(textBox).toBeInTheDocument();
fireEvent.change(textBox, { target: { value: `New ${cType} Title` } });
fireEvent.keyDown(textBox, { key: 'Enter', code: 'Enter', charCode: 13 });
await waitFor(() => {
expect(axiosMock.history.patch[0].url).toEqual(url);
});
expect(axiosMock.history.patch[0].data).toEqual(JSON.stringify({ display_name: `New ${cType} Title` }));
expect(textBox).not.toBeInTheDocument();
expect(mockShowToast).toHaveBeenCalledWith('Failed to update container.');
});
it(`should preview child in sidebar by clicking ${childType} on ${cType} page`, async () => {
const childId = `lct:org1:Demo_course:${childType}:${childType}-0`;
const url = getLibraryContainerApiUrl(childId);
axiosMock.onPatch(url).reply(200);
renderLibrarySectionPage(undefined, undefined, cType);
// Wait loading of the children
const child = await screen.findByText(`${childType} block 0`);
// No Preview tab is shown yet
expect(screen.queryByText('Preview')).not.toBeInTheDocument();
// Select the child
fireEvent.click(child);
expect((await screen.findAllByText(`${childType} block 0`)).length === 2);
// Because the Preview show/hide is dependent on the selected item
// being in the URL, and because our test router doesn't change
// paths, we have to explicitly navigate to the child page to check
// the Preview tab is shown. Boo.
renderLibrarySectionPage(undefined, undefined, cType, childId);
expect((await screen.findAllByText(`${childType} block 0`)).length === 2);
expect(await screen.findByText('Preview')).toBeInTheDocument();
});
it(`should rename child by clicking edit icon besides name in ${cType} page`, async () => {
const mockSetQueryData = jest.spyOn(queryClient, 'setQueryData');
const url = getLibraryContainerApiUrl(`${typeNamespace}:org1:Demo_course_generated:${childType}:${childType}-0`);
axiosMock.onPatch(url).reply(200);
renderLibrarySectionPage(undefined, undefined, cType);
// Wait loading of the children
await screen.findByText(`${childType} block 0`);
const editButton = (await screen.findAllByRole(
'button',
{ name: /edit/i },
))[1]; // 0 is the Section Title, 1 is the first subsection on the list
fireEvent.click(editButton);
expect(await screen.findByRole('textbox', { name: /text input/i })).toBeInTheDocument();
const textBox = await screen.findByRole('textbox', { name: /text input/i });
expect(textBox).toBeInTheDocument();
fireEvent.change(textBox, { target: { value: `New ${childType} Title` } });
fireEvent.keyDown(textBox, { key: 'Enter', code: 'Enter', charCode: 13 });
await waitFor(() => {
expect(axiosMock.history.patch.length).toEqual(1);
});
expect(axiosMock.history.patch[0].url).toEqual(url);
expect(axiosMock.history.patch[0].data).toStrictEqual(JSON.stringify({
display_name: `New ${childType} Title`,
}));
expect(textBox).not.toBeInTheDocument();
expect(mockShowToast).toHaveBeenCalledWith('Container updated successfully.');
expect(mockSetQueryData).toHaveBeenCalledTimes(1);
});
it(`should show error while updating child name in ${cType} page`, async () => {
const url = getLibraryContainerApiUrl(`${typeNamespace}:org1:Demo_course_generated:${childType}:${childType}-0`);
axiosMock.onPatch(url).reply(400);
renderLibrarySectionPage(undefined, undefined, cType);
// Wait loading of the children
await screen.findByText(`${childType} block 0`);
const editButton = screen.getAllByRole(
'button',
{ name: /edit/i },
)[1]; // 0 is the Section Title, 1 is the first subsection on the list
fireEvent.click(editButton);
expect(await screen.findByRole('textbox', { name: /text input/i })).toBeInTheDocument();
const textBox = await screen.findByRole('textbox', { name: /text input/i });
expect(textBox).toBeInTheDocument();
fireEvent.change(textBox, { target: { value: `New ${childType} Title` } });
fireEvent.keyDown(textBox, { key: 'Enter', code: 'Enter', charCode: 13 });
await waitFor(() => {
expect(axiosMock.history.patch.length).toEqual(1);
});
expect(axiosMock.history.patch[0].url).toEqual(url);
expect(axiosMock.history.patch[0].data).toStrictEqual(JSON.stringify({
display_name: `New ${childType} Title`,
}));
expect(textBox).not.toBeInTheDocument();
expect(mockShowToast).toHaveBeenCalledWith('Failed to update container.');
});
it(`should call update order api on dragging children in ${cType} page`, async () => {
const cId = cType === ContainerType.Section
? mockGetContainerMetadata.sectionId
: mockGetContainerMetadata.subsectionId;
renderLibrarySectionPage(cId, undefined, cType);
const firstDragHandle = (await screen.findAllByRole('button', { name: 'Drag to reorder' }))[0];
axiosMock
.onPatch(getLibraryContainerChildrenApiUrl(cId))
.reply(200);
verticalSortableListCollisionDetection.mockReturnValue([{
id: `${typeNamespace}:org1:Demo_course_generated:${childType}:${childType}-1----1`,
}]);
await act(async () => {
fireEvent.keyDown(firstDragHandle, { code: 'Space' });
});
setTimeout(() => fireEvent.keyDown(firstDragHandle, { code: 'Space' }));
await waitFor(() => expect(mockShowToast).toHaveBeenLastCalledWith('Order updated'));
});
it(`should cancel update order api on cancelling dragging component in ${cType} page`, async () => {
const cId = cType === ContainerType.Section
? mockGetContainerMetadata.sectionId
: mockGetContainerMetadata.subsectionId;
renderLibrarySectionPage(cId, undefined, cType);
const firstDragHandle = (await screen.findAllByRole('button', { name: 'Drag to reorder' }))[0];
axiosMock
.onPatch(getLibraryContainerChildrenApiUrl(cId))
.reply(200);
verticalSortableListCollisionDetection.mockReturnValue([{
id: `${typeNamespace}:org1:Demo_course_generated:${childType}:${childType}-1----1`,
}]);
await act(async () => {
fireEvent.keyDown(firstDragHandle, { code: 'Space' });
});
setTimeout(() => fireEvent.keyDown(firstDragHandle, { code: 'Escape' }));
await waitFor(() => expect(mockShowToast).not.toHaveBeenLastCalledWith('Order updated'));
});
it(`should show toast error message on update order failure in ${cType} page`, async () => {
const cId = cType === ContainerType.Section
? mockGetContainerMetadata.sectionId
: mockGetContainerMetadata.subsectionId;
renderLibrarySectionPage(cId, undefined, cType);
const firstDragHandle = (await screen.findAllByRole('button', { name: 'Drag to reorder' }))[0];
axiosMock
.onPatch(getLibraryContainerChildrenApiUrl(cId))
.reply(500);
verticalSortableListCollisionDetection.mockReturnValue([{
id: `${typeNamespace}:org1:Demo_course_generated:${childType}:${childType}-1----1`,
}]);
await act(async () => {
fireEvent.keyDown(firstDragHandle, { code: 'Space' });
});
setTimeout(() => fireEvent.keyDown(firstDragHandle, { code: 'Space' }));
await waitFor(() => expect(mockShowToast).toHaveBeenLastCalledWith('Failed to update children order'));
});
it(`should open ${childType} page on double click`, async () => {
renderLibrarySectionPage(undefined, undefined, cType);
const child = await screen.findByText(`${childType} block 0`);
// Trigger double click. Find the child card as the parent element
userEvent.click(child.parentElement!.parentElement!.parentElement!, undefined, { clickCount: 2 });
expect((await screen.findAllByText(new RegExp(`${childType} block 0`, 'i')))[0]).toBeInTheDocument();
expect(await screen.findByRole('button', { name: new RegExp(`${childType} Info`, 'i') })).toBeInTheDocument();
});
it(`should open manage tags on click tag count in ${cType} page`, async () => {
const cId = cType === ContainerType.Section
? mockGetContainerMetadata.sectionId
: mockGetContainerMetadata.subsectionId;
renderLibrarySectionPage(cId, undefined, cType);
// check all children components are rendered.
expect((await screen.findAllByText(`${childType} block 0`))[0]).toBeInTheDocument();
expect((await screen.findAllByText(`${childType} block 1`))[0]).toBeInTheDocument();
expect((await screen.findAllByText(`${childType} block 2`))[0]).toBeInTheDocument();
const tagCountButton = screen.getAllByRole('button', { name: '0' })[0];
fireEvent.click(tagCountButton);
expect(await screen.findByTestId('library-sidebar')).toBeInTheDocument();
await waitFor(
() => expect(screen.getByRole('tab', { name: /manage/i })).toHaveClass('active'),
{ timeout: 300 },
);
});
});
});