forked from openedx/frontend-app-authoring
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLibraryCollectionPage.test.tsx
More file actions
497 lines (408 loc) · 20.2 KB
/
LibraryCollectionPage.test.tsx
File metadata and controls
497 lines (408 loc) · 20.2 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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
import fetchMock from 'fetch-mock-jest';
import { cloneDeep } from 'lodash';
import MockAdapter from 'axios-mock-adapter/types';
import {
fireEvent,
initializeMocks,
render,
screen,
waitFor,
within,
} from '../../testUtils';
import mockResult from '../__mocks__/collection-search.json';
import {
mockContentLibrary,
mockXBlockFields,
mockGetCollectionMetadata,
mockGetContainerMetadata,
} from '../data/api.mocks';
import { mockContentSearchConfig, mockGetBlockTypes } from '../../search-manager/data/api.mock';
import { mockClipboardEmpty } from '../../generic/data/api.mock';
import { LibraryLayout } from '..';
import { ContentTagsDrawer } from '../../content-tags-drawer';
import {
getLibraryCollectionItemsApiUrl,
getLibraryContainersApiUrl,
} from '../data/api';
let axiosMock: MockAdapter;
let mockShowToast;
mockClipboardEmpty.applyMock();
mockGetCollectionMetadata.applyMock();
mockContentSearchConfig.applyMock();
mockGetBlockTypes.applyMock();
mockContentLibrary.applyMock();
mockXBlockFields.applyMock();
mockGetContainerMetadata.applyMock();
const searchEndpoint = 'http://mock.meilisearch.local/multi-search';
const path = '/library/:libraryId/*';
const libraryTitle = mockContentLibrary.libraryData.title;
const mockCollection = {
collectionId: mockResult.results[0].hits[5].block_id,
collectionNeverLoads: mockGetCollectionMetadata.collectionIdLoading,
collectionNoComponents: 'collection-no-components',
collectionEmpty: mockGetCollectionMetadata.collectionIdError,
};
const { title } = mockGetCollectionMetadata.collectionData;
jest.mock('../../content-tags-drawer/ContentTagsDrawer', () => jest.fn(() => <div>Mocked ContentTagsDrawer</div>));
describe('<LibraryCollectionPage />', () => {
beforeEach(() => {
const mocks = initializeMocks();
axiosMock = mocks.axiosMock;
mockShowToast = mocks.mockShowToast;
fetchMock.mockReset();
// The Meilisearch client-side API uses fetch, not Axios.
fetchMock.post(searchEndpoint, (_url, req) => {
const requestData = JSON.parse((req.body ?? '') as string);
const query = requestData?.queries[0]?.q ?? '';
const mockResultCopy = cloneDeep(mockResult);
// We have to replace the query (search keywords) in the mock results with the actual query,
// because otherwise Instantsearch will update the UI and change the query,
// leading to unexpected results in the test cases.
mockResultCopy.results[0].query = query;
// And fake the required '_formatted' fields; it contains the highlighting <mark>...</mark> around matched words
// eslint-disable-next-line no-underscore-dangle, no-param-reassign
mockResultCopy.results[0]?.hits.forEach((hit) => { hit._formatted = { ...hit }; });
const collectionQueryId = requestData?.queries[0]?.filter?.[2]?.split('collections.key = "')[1].split('"')[0];
switch (collectionQueryId) {
case mockCollection.collectionNeverLoads:
return new Promise<any>(() => {});
case mockCollection.collectionEmpty:
mockResultCopy.results[0].hits = [];
mockResultCopy.results[0].totalHits = 0;
break;
case mockCollection.collectionNoComponents:
mockResultCopy.results[0].hits = [];
mockResultCopy.results[0].totalHits = 0;
mockResultCopy.results[1].facetDistribution.block_type = {};
break;
default:
break;
}
return mockResultCopy;
});
});
const renderLibraryCollectionPage = async (collectionId?: string, libraryId?: string) => {
const libId = libraryId || mockContentLibrary.libraryId;
const colId = collectionId || mockCollection.collectionId;
render(<LibraryLayout />, {
path,
routerProps: {
initialEntries: [`/library/${libId}/collection/${colId}`],
},
});
if (![mockCollection.collectionNeverLoads, mockCollection.collectionEmpty].includes(colId)) {
await waitFor(() => { expect(fetchMock).toHaveFetchedTimes(1, searchEndpoint, 'post'); });
}
};
it('shows the spinner before the query is complete', async () => {
// This mock will never return data about the collection (it loads forever):
await renderLibraryCollectionPage(mockCollection.collectionNeverLoads);
const spinner = screen.getByRole('status');
expect(spinner.textContent).toEqual('Loading...');
});
it('shows an error component if no collection returned', async () => {
// This mock will simulate incorrect collection id
await renderLibraryCollectionPage(mockCollection.collectionEmpty);
const errorMessage = 'Mocked request failed with status code 404{ "detail": "Not found." }';
expect(await screen.findByRole('alert')).toHaveTextContent(errorMessage);
});
it('shows collection data', async () => {
await renderLibraryCollectionPage();
expect(await screen.findByText('All Collections')).toBeInTheDocument();
expect((await screen.findAllByText(libraryTitle))[0]).toBeInTheDocument();
expect((await screen.findAllByText(title))[0]).toBeInTheDocument();
// "Recently Modified" sort shown
expect(screen.getAllByText('Recently Modified').length).toEqual(1);
expect((await screen.findAllByText('Introduction to Testing'))[0]).toBeInTheDocument();
// Content header with count
expect(await screen.findByText('Content (5)')).toBeInTheDocument();
});
it('shows a collection without associated components', async () => {
await renderLibraryCollectionPage(mockCollection.collectionNoComponents);
expect(await screen.findByText('All Collections')).toBeInTheDocument();
expect((await screen.findAllByText(libraryTitle))[0]).toBeInTheDocument();
expect((await screen.findAllByText(title))[0]).toBeInTheDocument();
expect((await screen.findAllByText('This collection is currently empty.')).length).toEqual(2);
const addComponentButton = screen.getAllByRole('button', { name: /new/i })[1];
fireEvent.click(addComponentButton);
expect(screen.getByText(/add content/i)).toBeInTheDocument();
});
it('shows the new content button', async () => {
await renderLibraryCollectionPage();
expect(await screen.findByText('All Collections')).toBeInTheDocument();
expect(await screen.findByText('Content (5)')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /new/i })).toBeInTheDocument();
expect(screen.queryByText('Read Only')).not.toBeInTheDocument();
});
it('shows an empty read-only library collection, with the new button disabled', async () => {
// Use a library mock that is read-only:
const libraryId = mockContentLibrary.libraryIdReadOnly;
// Update search mock so it returns no results:
await renderLibraryCollectionPage(mockCollection.collectionNoComponents, libraryId);
expect(await screen.findByText('All Collections')).toBeInTheDocument();
// Show in the collection page and in the sidebar
expect(screen.getAllByText('This collection is currently empty.').length).toEqual(2);
expect(screen.queryByRole('button', { name: /new/i })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /new/i })).toBeDisabled();
expect(screen.getByText('Read Only')).toBeInTheDocument();
});
it('show a collection without search results', async () => {
// Update search mock so it returns no results:
await renderLibraryCollectionPage(mockCollection.collectionNoComponents);
expect(await screen.findByText('All Collections')).toBeInTheDocument();
expect((await screen.findAllByText(libraryTitle))[0]).toBeInTheDocument();
expect((await screen.findAllByText(title))[0]).toBeInTheDocument();
fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'noresults' } });
// Ensure the search endpoint is called again, only once more since the recently modified call
// should not be impacted by the search
await waitFor(() => { expect(fetchMock).toHaveFetchedTimes(2, searchEndpoint, 'post'); });
expect(screen.queryByText('No matching components found in this collection.')).toBeInTheDocument();
});
it('should open and close new content sidebar', async () => {
await renderLibraryCollectionPage();
expect(await screen.findByText('All Collections')).toBeInTheDocument();
expect(screen.queryByText(/add content/i)).not.toBeInTheDocument();
const newButton = screen.getByRole('button', { name: /new/i });
fireEvent.click(newButton);
expect(screen.getByText(/add content/i)).toBeInTheDocument();
const closeButton = screen.getByRole('button', { name: /close/i });
fireEvent.click(closeButton);
expect(screen.queryByText(/add content/i)).not.toBeInTheDocument();
});
it('should open collection Info by default', async () => {
const expectedCollectionUsageKey = 'lib-collection:Axim:TEST:my-first-collection';
await renderLibraryCollectionPage();
expect(await screen.findByText('All Collections')).toBeInTheDocument();
expect((await screen.findAllByText(libraryTitle))[0]).toBeInTheDocument();
expect((await screen.findAllByText(title))[0]).toBeInTheDocument();
expect((await screen.findAllByText(title))[1]).toBeInTheDocument();
expect(screen.getByText('Manage')).toBeInTheDocument();
expect(screen.getByText('Details')).toBeInTheDocument();
expect(screen.getByText('Mocked ContentTagsDrawer')).toBeInTheDocument();
expect(ContentTagsDrawer).toHaveBeenCalledWith(
expect.objectContaining({
id: expectedCollectionUsageKey,
}),
{},
);
});
it('should close and open Collection Info', async () => {
const expectedCollectionUsageKey = 'lib-collection:Axim:TEST:my-first-collection';
await renderLibraryCollectionPage();
expect(await screen.findByText('All Collections')).toBeInTheDocument();
expect((await screen.findAllByText(libraryTitle))[0]).toBeInTheDocument();
expect((await screen.findAllByText(title))[0]).toBeInTheDocument();
expect((await screen.findAllByText(title))[1]).toBeInTheDocument();
const collectionInfoBtn = screen.getByRole('button', { name: /collection info/i });
// Open by default; click 'Collection info' button to close
fireEvent.click(collectionInfoBtn);
expect(screen.queryByText('Draft')).not.toBeInTheDocument();
expect(screen.queryByText('(Never Published)')).not.toBeInTheDocument();
// Open library info sidebar with 'Collection info' button
fireEvent.click(collectionInfoBtn);
expect(screen.getByText('Manage')).toBeInTheDocument();
expect(screen.getByText('Details')).toBeInTheDocument();
expect(screen.getByText('Mocked ContentTagsDrawer')).toBeInTheDocument();
expect(ContentTagsDrawer).toHaveBeenCalledWith(
expect.objectContaining({
id: expectedCollectionUsageKey,
}),
{},
);
});
it('sorts collection components', async () => {
await renderLibraryCollectionPage();
expect(await screen.findByTitle('Sort search results')).toBeInTheDocument();
const testSortOption = (async (optionText, sortBy, isDefault) => {
// Open the drop-down menu
fireEvent.click(screen.getByTitle('Sort search results'));
// Click the option with the given text
// Since the sort drop-down also shows the selected sort
// option in its toggle button, we need to make sure we're
// clicking on the last one found.
const options = screen.getAllByText(optionText);
expect(options.length).toBeGreaterThan(0);
fireEvent.click(options[options.length - 1]);
let bodyText;
// Did the search happen with the expected sort option?
if (Array.isArray(sortBy)) {
bodyText = `"sort":[${sortBy.map(item => `"${item}"`).join(',')}]`;
} else {
bodyText = sortBy ? `"sort":["${sortBy}"]` : '"sort":[]';
}
await waitFor(() => {
expect(fetchMock).toHaveBeenLastCalledWith(searchEndpoint, {
body: expect.stringContaining(bodyText),
method: 'POST',
headers: expect.anything(),
});
});
// Is the sort option stored in the query string?
// Note: we can't easily check this at the moment with <MemoryRouter>
// const searchText = isDefault ? '' : `?sort=${encodeURIComponent(sortBy)}`;
// expect(window.location.href).toEqual(searchText);
// Is the selected sort option shown in the toggle button (if not default)
// as well as in the drop-down menu?
expect(screen.getAllByText(optionText).length).toEqual(isDefault ? 1 : 2);
});
await testSortOption('Title, A-Z', 'display_name:asc', false);
await testSortOption('Title, Z-A', 'display_name:desc', false);
await testSortOption('Newest', 'created:desc', false);
await testSortOption('Oldest', 'created:asc', false);
// Sorting by Recently Published also sorts unpublished components by recently modified
await testSortOption('Recently Published', ['last_published:desc', 'modified:desc'], false);
// Re-selecting the previous sort option resets sort to default "Recently Modified"
await testSortOption('Recently Published', 'modified:desc', true);
expect(screen.getAllByText('Recently Modified').length).toEqual(2);
// Enter a keyword into the search box
const searchBox = await screen.findByRole('searchbox');
fireEvent.change(searchBox, { target: { value: 'words to find' } });
// Default sort option changes to "Most Relevant"
expect((await screen.findAllByText('Most Relevant')).length).toEqual(2);
await waitFor(() => {
expect(fetchMock).toHaveBeenLastCalledWith(searchEndpoint, {
body: expect.stringContaining('"sort":[]'),
method: 'POST',
headers: expect.anything(),
});
});
});
it('should open and close the component sidebar', async () => {
const mockResult0 = mockResult.results[0].hits[0];
const displayName = 'Introduction to Testing';
expect(mockResult0.display_name).toStrictEqual(displayName);
await renderLibraryCollectionPage();
fireEvent.click((await screen.findAllByText(displayName))[0]);
const sidebar = screen.getByTestId('library-sidebar');
const { getByRole, getByText } = within(sidebar);
await waitFor(() => expect(getByText(displayName)).toBeInTheDocument());
const closeButton = getByRole('button', { name: /close/i });
fireEvent.click(closeButton);
await waitFor(() => expect(screen.queryByTestId('library-sidebar')).not.toBeInTheDocument());
});
it('has an empty type filter when there are no results', async () => {
await renderLibraryCollectionPage(mockCollection.collectionNoComponents);
const filterButton = screen.getByRole('button', { name: /type/i });
fireEvent.click(filterButton);
expect(screen.getByText(/no matching components/i)).toBeInTheDocument();
});
it('should remove component from collection and hides sidebar', async () => {
const url = getLibraryCollectionItemsApiUrl(
mockContentLibrary.libraryId,
mockCollection.collectionId,
);
axiosMock.onDelete(url).reply(204);
const displayName = 'Introduction to Testing';
await renderLibraryCollectionPage();
// open sidebar
fireEvent.click(await screen.findByText(displayName));
await waitFor(() => expect(screen.queryByTestId('library-sidebar')).toBeInTheDocument());
const menuBtns = await screen.findAllByRole('button', { name: 'Component actions menu' });
// open menu
fireEvent.click(menuBtns[0]);
fireEvent.click(await screen.findByText('Remove from collection'));
await waitFor(() => {
expect(axiosMock.history.delete.length).toEqual(1);
});
expect(mockShowToast).toHaveBeenCalledWith('Item successfully removed');
// Should close sidebar as component was removed
await waitFor(() => expect(screen.queryByTestId('library-sidebar')).not.toBeInTheDocument());
});
it('should show error when remove component from collection', async () => {
const url = getLibraryCollectionItemsApiUrl(
mockContentLibrary.libraryId,
mockCollection.collectionId,
);
axiosMock.onDelete(url).reply(404);
await renderLibraryCollectionPage();
const menuBtns = await screen.findAllByRole('button', { name: 'Component actions menu' });
// open menu
fireEvent.click(menuBtns[0]);
fireEvent.click(await screen.findByText('Remove from collection'));
await waitFor(() => {
expect(axiosMock.history.delete.length).toEqual(1);
});
expect(mockShowToast).toHaveBeenCalledWith('Failed to remove item');
});
it('should remove unit from collection and hides sidebar', async () => {
const url = getLibraryCollectionItemsApiUrl(
mockContentLibrary.libraryId,
mockCollection.collectionId,
);
axiosMock.onDelete(url).reply(204);
const displayName = 'Test Unit';
await renderLibraryCollectionPage();
// Wait for the unit cards to load
await waitFor(() => expect(screen.getAllByTestId('container-card-menu-toggle').length).toBeGreaterThan(0));
// open sidebar
fireEvent.click(await screen.findByText(displayName));
await waitFor(() => expect(screen.queryByTestId('library-sidebar')).toBeInTheDocument());
// Open menu
fireEvent.click((await screen.findAllByTestId('container-card-menu-toggle'))[0]);
// Click remove to collection
fireEvent.click(screen.getByRole('button', { name: 'Remove from collection' }));
await waitFor(() => {
expect(axiosMock.history.delete.length).toEqual(1);
});
expect(mockShowToast).toHaveBeenCalledWith('Item successfully removed');
// Should close sidebar as component was removed
await waitFor(() => expect(screen.queryByTestId('library-sidebar')).not.toBeInTheDocument());
});
test.each([
{
label: 'should create a unit inside a collection',
containerType: 'unit',
},
{
label: 'should create a section inside a collection',
containerType: 'section',
},
{
label: 'should create a subsection inside a collection',
containerType: 'subsection',
},
])('$label', async ({ containerType }) => {
await renderLibraryCollectionPage();
const containerTitle = `This is a Test ${containerType}`;
const containerId = `lct:org:libId:${containerType}:1`;
const containerUrl = getLibraryContainersApiUrl(mockContentLibrary.libraryId);
axiosMock.onPost(containerUrl).reply(200, {
id: containerId,
slug: 'this-is-a-test',
title: containerTitle,
});
const collectionUrl = getLibraryCollectionItemsApiUrl(
mockContentLibrary.libraryId,
mockCollection.collectionId,
);
axiosMock.onPatch(collectionUrl).reply(200);
expect(await screen.findByRole('heading', { name: /Test Collection/i })).toBeInTheDocument();
expect(screen.queryByText(/add content/i)).not.toBeInTheDocument();
// Open Add content sidebar
const newButton = screen.getByRole('button', { name: /new/i });
fireEvent.click(newButton);
expect(screen.getByText(/add content/i)).toBeInTheDocument();
// Open New unit Modal
const sidebar = screen.getByTestId('library-sidebar');
const newContainerButton = within(sidebar).getAllByRole('button', { name: new RegExp(containerType, 'i') })[0];
fireEvent.click(newContainerButton);
const containerModalHeading = await screen.findByRole('heading', { name: new RegExp(`new ${containerType}`, 'i') });
expect(containerModalHeading).toBeInTheDocument();
// Fill the form
const createButton = screen.getByRole('button', { name: /create/i });
const nameField = screen.getByRole('textbox', { name: new RegExp(`name your ${containerType}`, 'i') });
fireEvent.change(nameField, { target: { value: containerTitle } });
fireEvent.click(createButton);
// Check success
await waitFor(() => expect(axiosMock.history.post.length).toBe(1));
// Check that the unit was created
expect(axiosMock.history.post[0].url).toBe(containerUrl);
expect(axiosMock.history.post[0].data).toContain(`"display_name":"${containerTitle}"`);
expect(axiosMock.history.post[0].data).toContain(`"container_type":"${containerType}"`);
expect(mockShowToast).toHaveBeenCalledWith(expect.stringMatching(new RegExp(`${containerType} created successfully`, 'i')));
// Check that the unit was added to the collection
expect(axiosMock.history.patch.length).toBe(1);
expect(axiosMock.history.patch[0].url).toBe(collectionUrl);
expect(axiosMock.history.patch[0].data).toContain(`"usage_keys":["${containerId}"]`);
});
});