forked from openedx/frontend-app-authoring
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLibraryAuthoringPage.test.tsx
More file actions
1144 lines (929 loc) · 45 KB
/
LibraryAuthoringPage.test.tsx
File metadata and controls
1144 lines (929 loc) · 45 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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { getConfig } from '@edx/frontend-platform';
import fetchMock from 'fetch-mock-jest';
import { Helmet } from 'react-helmet';
import {
fireEvent,
initializeMocks,
render,
screen,
waitFor,
within,
} from '@src/testUtils';
import studioHomeMock from '@src/studio-home/__mocks__/studioHomeMock';
import { mockGetMigrationStatus } from '@src/data/api.mocks';
import mockEmptyResult from '@src/search-modal/__mocks__/empty-search-result.json';
import { mockContentSearchConfig } from '@src/search-manager/data/api.mock';
import { getStudioHomeApiUrl } from '@src/studio-home/data/api';
import mockResult from './__mocks__/library-search.json';
import {
mockContentLibrary,
mockGetCollectionMetadata,
mockGetContainerMetadata,
mockGetLibraryTeam,
mockXBlockFields,
} from './data/api.mocks';
import { LibraryLayout } from '.';
import { getLibraryCollectionsApiUrl, getLibraryContainersApiUrl } from './data/api';
let axiosMock;
let mockShowToast;
mockGetCollectionMetadata.applyMock();
mockGetContainerMetadata.applyMock();
mockContentSearchConfig.applyMock();
mockContentLibrary.applyMock();
mockGetLibraryTeam.applyMock();
mockXBlockFields.applyMock();
mockGetMigrationStatus.applyMock();
const searchEndpoint = 'http://mock.meilisearch.local/multi-search';
/**
* Returns 0 components from the search query.
*/
const returnEmptyResult = (_url, req) => {
const requestData = JSON.parse(req.body?.toString() ?? '');
const query = requestData?.queries[0]?.q ?? '';
// We have to replace the query (search keywords) in the mock results with the actual query,
// because otherwise we may have an inconsistent state that causes more queries and unexpected results.
mockEmptyResult.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
mockEmptyResult.results[0]?.hits.forEach((hit) => {
hit._formatted = { ...hit };
});
return mockEmptyResult;
};
const path = '/library/:libraryId/*';
const libraryTitle = mockContentLibrary.libraryData.title;
describe('<LibraryAuthoringPage />', () => {
beforeAll(() => {
jest.useFakeTimers();
});
beforeEach(async () => {
const mocks = initializeMocks();
axiosMock = mocks.axiosMock;
mockShowToast = mocks.mockShowToast;
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
// The Meilisearch client-side API uses fetch, not Axios.
fetchMock.mockReset();
fetchMock.post(searchEndpoint, (_url, req) => {
const requestData = JSON.parse((req.body ?? '') as string);
const query = requestData?.queries[0]?.q ?? '';
// 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.
const newMockResult = { ...mockResult };
newMockResult.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
newMockResult.results[0]?.hits.forEach((hit) => {
hit._formatted = { ...hit };
});
return newMockResult;
});
});
afterAll(() => {
jest.useRealTimers();
});
const renderLibraryPage = async () => {
render(<LibraryLayout />, { path, params: { libraryId: mockContentLibrary.libraryId } });
// Ensure the search endpoint is called:
// Call 1: To fetch searchable/filterable/sortable library data
await waitFor(() => {
expect(fetchMock).toHaveFetchedTimes(1, searchEndpoint, 'post');
});
};
it('shows the spinner before the query is complete', () => {
// This mock will never return data about the library (it loads forever):
const libraryId = mockContentLibrary.libraryIdThatNeverLoads;
render(<LibraryLayout />, { path, params: { libraryId } });
const spinner = screen.getByRole('status');
expect(spinner.textContent).toEqual('Loading...');
});
it('shows an error component if no library returned', async () => {
// This mock will simulate a 404 error:
const libraryId = mockContentLibrary.library404;
render(<LibraryLayout />, { path, params: { libraryId } });
expect(await screen.findByTestId('notFoundAlert')).toBeInTheDocument();
});
it('shows library data', async () => {
await renderLibraryPage();
expect(await screen.findByText('Content library')).toBeInTheDocument();
expect((await screen.findAllByText(libraryTitle))[0]).toBeInTheDocument();
const browserTabTitle = Helmet.peek().title.join('');
const siteName = getConfig().SITE_NAME;
expect(browserTabTitle).toEqual(`${libraryTitle} | ${siteName}`);
expect(screen.queryByText('You have not added any content to this library yet.')).not.toBeInTheDocument();
expect(screen.getAllByText('Recently Modified').length).toEqual(1);
expect((await screen.findAllByText('Introduction to Testing'))[0]).toBeInTheDocument();
// Search box should not have focus on page load
const searchBox = screen.getByRole('searchbox');
expect(searchBox).not.toHaveFocus();
// Navigate to the components tab
fireEvent.click(screen.getByRole('tab', { name: 'Components' }));
// "Recently Modified" default sort shown
expect(screen.getAllByText('Recently Modified').length).toEqual(1);
// Navigate to the collections tab
fireEvent.click(screen.getByRole('tab', { name: 'Collections' }));
// "Recently Modified" default sort shown
expect(screen.getAllByText('Recently Modified').length).toEqual(1);
expect(screen.queryByText('There are 10 components in this library')).not.toBeInTheDocument();
expect((await screen.findAllByText('Collection 1'))[0]).toBeInTheDocument();
// Go back to Home tab
// This step is necessary to avoid the url change leak to other tests
fireEvent.click(screen.getByRole('tab', { name: 'All Content' }));
expect(screen.getAllByText('Recently Modified').length).toEqual(1);
});
it('shows a library without components and collections', async () => {
fetchMock.post(searchEndpoint, returnEmptyResult, { overwriteRoutes: true });
await renderLibraryPage();
expect(await screen.findByText('Content library')).toBeInTheDocument();
expect((await screen.findAllByText(libraryTitle))[0]).toBeInTheDocument();
fireEvent.click(screen.getByRole('tab', { name: 'Collections' }));
expect(await screen.findByText('You have not added any collections to this library yet.')).toBeInTheDocument();
// Open Create collection modal
const addCollectionButton = screen.getByRole('button', { name: /add collection/i });
fireEvent.click(addCollectionButton);
const collectionModalHeading = await screen.findByRole('heading', { name: /new collection/i });
expect(collectionModalHeading).toBeInTheDocument();
// Click on Cancel button
const cancelButton = screen.getByRole('button', { name: /cancel/i });
fireEvent.click(cancelButton);
expect(collectionModalHeading).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('tab', { name: 'All Content' }));
expect(await screen.findByText('You have not added any content to this library yet.')).toBeInTheDocument();
const addComponentButton = screen.getByRole('button', { name: /add component/i });
fireEvent.click(addComponentButton);
expect(screen.getByText(/add content/i)).toBeInTheDocument();
});
it('shows the new content button', async () => {
await renderLibraryPage();
expect(await screen.findByRole('heading')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /new/i })).toBeInTheDocument();
expect(screen.queryByText('Read Only')).not.toBeInTheDocument();
});
it('shows an empty read-only library, without a "create component" button', async () => {
// Use a library mock that is read-only:
const libraryId = mockContentLibrary.libraryIdReadOnly;
// Update search mock so it returns no results:
fetchMock.post(searchEndpoint, returnEmptyResult, { overwriteRoutes: true });
render(<LibraryLayout />, { path, params: { libraryId } });
await waitFor(() => {
expect(fetchMock).toHaveFetchedTimes(1, searchEndpoint, 'post');
});
expect(await screen.findByText('Content library')).toBeInTheDocument();
expect(screen.getByText('You have not added any content to this library yet.')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /add component/i })).not.toBeInTheDocument();
expect(screen.getByText('Read Only')).toBeInTheDocument();
});
it('show a library without search results', async () => {
// Update search mock so it returns no results:
fetchMock.post(searchEndpoint, returnEmptyResult, { overwriteRoutes: true });
await renderLibraryPage();
expect(await screen.findByText('Content library')).toBeInTheDocument();
expect((await screen.findAllByText(libraryTitle))[0]).toBeInTheDocument();
await waitFor(() => {
expect(fetchMock).toHaveFetchedTimes(1, searchEndpoint, 'post');
});
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(await screen.findByText('No matching components found in this library.')).toBeInTheDocument();
// Navigate to the components tab
const componentsTab = screen.getByRole('tab', { name: 'Components' });
fireEvent.click(componentsTab);
expect(componentsTab).toHaveAttribute('aria-selected', 'true');
expect(await screen.findByText('No matching components found in this library.')).toBeInTheDocument();
// Navigate to the collections tab
const collectionsTab = screen.getByRole('tab', { name: 'Collections' });
fireEvent.click(collectionsTab);
expect(collectionsTab).toHaveAttribute('aria-selected', 'true');
expect(await screen.findByText('No matching collections found in this library.')).toBeInTheDocument();
// Navigate to the units tab
const unitsTab = screen.getByRole('tab', { name: 'Units' });
fireEvent.click(unitsTab);
expect(unitsTab).toHaveAttribute('aria-selected', 'true');
expect(await screen.findByText('No matching components found in this library.')).toBeInTheDocument();
// Navigate to the subsections tab
const subsectionsTab = screen.getByRole('tab', { name: 'Subsections' });
fireEvent.click(subsectionsTab);
expect(subsectionsTab).toHaveAttribute('aria-selected', 'true');
expect(await screen.findByText('No matching components found in this library.')).toBeInTheDocument();
// Navigate to the subsections tab
const sectionsTab = screen.getByRole('tab', { name: 'Sections' });
fireEvent.click(sectionsTab);
expect(sectionsTab).toHaveAttribute('aria-selected', 'true');
expect(await screen.findByText('No matching components found in this library.')).toBeInTheDocument();
// Go back to Home tab
// This step is necessary to avoid the url change leak to other tests
fireEvent.click(screen.getByRole('tab', { name: 'All Content' }));
});
it('should open and close new content sidebar', async () => {
await renderLibraryPage();
expect(await screen.findByRole('heading')).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 Library Info by default', async () => {
await renderLibraryPage();
expect(await screen.findByText('Content library')).toBeInTheDocument();
expect((await screen.findAllByText(libraryTitle))[0]).toBeInTheDocument();
expect((await screen.findAllByText(libraryTitle))[1]).toBeInTheDocument();
expect(screen.getByText('Draft')).toBeInTheDocument();
expect(screen.getByText('(Never Published)')).toBeInTheDocument();
// Draft saved on date:
expect(screen.getByText('July 22, 2024')).toBeInTheDocument();
expect(screen.getByText(mockContentLibrary.libraryData.org)).toBeInTheDocument();
// Updated:
expect(screen.getByText('July 20, 2024')).toBeInTheDocument();
// Created:
expect(screen.getByText('June 26, 2024')).toBeInTheDocument();
});
it('should close and open Library Info', async () => {
await renderLibraryPage();
expect(await screen.findByText('Content library')).toBeInTheDocument();
expect((await screen.findAllByText(libraryTitle))[0]).toBeInTheDocument();
expect((await screen.findAllByText(libraryTitle))[1]).toBeInTheDocument();
// Open by default; close the library info sidebar
const closeButton = screen.getByRole('button', { name: /close/i });
fireEvent.click(closeButton);
expect(screen.queryByText('Draft')).not.toBeInTheDocument();
expect(screen.queryByText('(Never Published)')).not.toBeInTheDocument();
// Open library info sidebar with 'Library info' button
const libraryInfoButton = screen.getByRole('button', { name: /library info/i });
fireEvent.click(libraryInfoButton);
expect(screen.getByText('Draft')).toBeInTheDocument();
expect(screen.getByText('(Never Published)')).toBeInTheDocument();
// Close library info sidebar with 'Library info' button
fireEvent.click(libraryInfoButton);
expect(screen.queryByText('Draft')).not.toBeInTheDocument();
expect(screen.queryByText('(Never Published)')).not.toBeInTheDocument();
});
it('should show Library Team button in Library Info that opens the Library Team modal', async () => {
await renderLibraryPage();
const manageAccess = await screen.findByRole('button', { name: /Manage Access/i });
expect(manageAccess).not.toBeDisabled();
fireEvent.click(manageAccess);
expect(await screen.findByRole('heading', { name: 'Library Team' })).toBeInTheDocument();
});
it('should not show "Library Team" button in Library Info to users who cannot edit the library', async () => {
const libraryId = mockContentLibrary.libraryIdReadOnly;
render(<LibraryLayout />, { path, params: { libraryId } });
const manageAccess = screen.queryByRole('button', { name: /Library Team/i });
expect(manageAccess).not.toBeInTheDocument();
});
it('sorts library components', async () => {
await renderLibraryPage();
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 = screen.getByRole('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(),
});
});
}, 10000);
it('should open, close and re-open the component sidebar', async () => {
const mockResult0 = { ...mockResult }.results[0].hits[0];
const displayName = 'Introduction to Testing';
expect(mockResult0.display_name).toStrictEqual(displayName);
await renderLibraryPage();
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());
fireEvent.click((await screen.findAllByText(displayName))[0]);
await waitFor(() => expect(screen.queryByTestId('library-sidebar')).toBeInTheDocument());
});
it('should open component sidebar, showing manage tab on clicking add to collection menu item - component', async () => {
const mockResult0 = { ...mockResult }.results[0].hits[0];
const displayName = 'Introduction to Testing';
expect(mockResult0.display_name).toStrictEqual(displayName);
await renderLibraryPage();
await waitFor(() => expect(screen.getAllByTestId('component-card-menu-toggle').length).toBeGreaterThan(0));
// Open menu
fireEvent.click((await screen.findAllByTestId('component-card-menu-toggle'))[0]);
// Click add to collection
fireEvent.click(screen.getByRole('button', { name: 'Add to collection' }));
const sidebar = screen.getByTestId('library-sidebar');
const { getByRole, findByText } = within(sidebar);
expect(await findByText(displayName)).toBeInTheDocument();
jest.advanceTimersByTime(300);
expect(getByRole('tab', { selected: true })).toHaveTextContent('Manage');
const closeButton = getByRole('button', { name: /close/i });
fireEvent.click(closeButton);
await waitFor(() => expect(screen.queryByTestId('library-sidebar')).not.toBeInTheDocument());
});
it('should open component sidebar, showing manage tab on clicking add to collection menu item - unit', async () => {
const displayName = 'Test Unit';
await renderLibraryPage();
await waitFor(() => expect(screen.getAllByTestId('container-card-menu-toggle').length).toBeGreaterThan(0));
// Open menu
fireEvent.click((await screen.findAllByTestId('container-card-menu-toggle'))[0]);
// Click add to collection
fireEvent.click(screen.getByRole('button', { name: 'Add to collection' }));
const sidebar = screen.getByTestId('library-sidebar');
const { getByRole, findByText } = within(sidebar);
expect(await findByText(displayName)).toBeInTheDocument();
jest.advanceTimersByTime(300);
expect(getByRole('tab', { selected: true })).toHaveTextContent('Manage');
const closeButton = getByRole('button', { name: /close/i });
fireEvent.click(closeButton);
await waitFor(() => expect(screen.queryByTestId('library-sidebar')).not.toBeInTheDocument());
});
it('should open and close the collection sidebar', async () => {
await renderLibraryPage();
// Click on the first collection
fireEvent.click(await screen.findByText('Collection 1'));
const sidebar = screen.getByTestId('library-sidebar');
const { getByRole, getByText } = within(sidebar);
// The mock data for the sidebar has a title of "Test Collection"
await waitFor(() => expect(getByText('Test Collection')).toBeInTheDocument());
const closeButton = getByRole('button', { name: /close/i });
fireEvent.click(closeButton);
await waitFor(() => expect(screen.queryByTestId('library-sidebar')).not.toBeInTheDocument());
});
it('should open and close the unit sidebar', async () => {
await renderLibraryPage();
// Click on the first unit
fireEvent.click(await screen.findByText('Test Unit'));
const sidebar = screen.getByTestId('library-sidebar');
const { getByRole, getByText } = within(sidebar);
// The mock data for the sidebar has a title of "Test Unit"
await waitFor(() => expect(getByText('Test Unit')).toBeInTheDocument());
const closeButton = getByRole('button', { name: /close/i });
fireEvent.click(closeButton);
await waitFor(() => expect(screen.queryByTestId('library-sidebar')).not.toBeInTheDocument());
});
it('should preserve the tab while switching from a component to a collection', async () => {
await renderLibraryPage();
// Click on the first collection
fireEvent.click(await screen.findByText('Collection 1'));
// Click on the Details tab
fireEvent.click(screen.getByRole('tab', { name: 'Details' }));
// Change to a component
fireEvent.click((await screen.findAllByText('Introduction to Testing'))[0]);
// Check that the Details tab is still selected
expect(screen.getByRole('tab', { name: 'Details' })).toHaveAttribute('aria-selected', 'true');
// Click on the Previews tab
fireEvent.click(screen.getByRole('tab', { name: 'Preview' }));
// Switch back to the collection
fireEvent.click(await screen.findByText('Collection 1'));
// The Details (default) tab should be selected because the collection does not have a Preview tab
expect(screen.getByRole('tab', { name: 'Details' })).toHaveAttribute('aria-selected', 'true');
});
const problemTypes = {
'Multiple Choice': 'choiceresponse',
Checkboxes: 'multiplechoiceresponse',
'Numerical Input': 'numericalresponse',
Dropdown: 'optionresponse',
'Text Input': 'stringresponse',
};
it.each(Object.keys(problemTypes))('can filter by capa problem type (%s)', async (submenuText) => {
await renderLibraryPage();
// Ensure the search endpoint is called
await waitFor(() => {
expect(fetchMock).toHaveFetchedTimes(1, searchEndpoint, 'post');
});
const filterButton = screen.getByRole('button', { name: /type/i });
fireEvent.click(filterButton);
const problemFilterCheckbox = screen.getByRole('checkbox', { name: /problem/i });
const problemFilterMenuItem = problemFilterCheckbox.parentElement; // div.pgn__menu-item
const showProbTypesSubmenuBtn = problemFilterMenuItem!.querySelector(
'button[aria-label="Open problem types filters"]',
);
expect(showProbTypesSubmenuBtn).not.toBeNull();
fireEvent.click(showProbTypesSubmenuBtn!);
const submenu = screen.getByText(submenuText);
expect(submenu).toBeInTheDocument();
fireEvent.click(submenu);
await waitFor(() => {
expect(fetchMock).toHaveBeenLastCalledWith(searchEndpoint, {
body: expect.stringContaining(`content.problem_types = ${problemTypes[submenuText]}`),
method: 'POST',
headers: expect.anything(),
});
});
fireEvent.click(submenu);
await waitFor(() => {
expect(fetchMock).toHaveBeenLastCalledWith(searchEndpoint, {
body: expect.not.stringContaining(`content.problem_types = ${problemTypes[submenuText]}`),
method: 'POST',
headers: expect.anything(),
});
});
});
it('can filter by block type', async () => {
await renderLibraryPage();
// Ensure the search endpoint is called
await waitFor(() => {
expect(fetchMock).toHaveFetchedTimes(1, searchEndpoint, 'post');
});
const filterButton = screen.getByRole('button', { name: /type/i });
fireEvent.click(filterButton);
// Validate click on Problem type
const problemMenu = screen.getAllByText('Problem')[0];
expect(problemMenu).toBeInTheDocument();
fireEvent.click(problemMenu);
await waitFor(() => {
expect(fetchMock).toHaveBeenLastCalledWith(searchEndpoint, {
body: expect.stringContaining('block_type = problem'),
method: 'POST',
headers: expect.anything(),
});
});
fireEvent.click(problemMenu);
await waitFor(() => {
expect(fetchMock).toHaveBeenLastCalledWith(searchEndpoint, {
body: expect.not.stringContaining('block_type = problem'),
method: 'POST',
headers: expect.anything(),
});
});
// Validate clear filters
fireEvent.click(problemMenu);
const clearFitlersButton = screen.getByText('Clear Filters');
fireEvent.click(clearFitlersButton);
await waitFor(() => {
expect(fetchMock).toHaveBeenLastCalledWith(searchEndpoint, {
body: expect.not.stringContaining('block_type = problem'),
method: 'POST',
headers: expect.anything(),
});
});
});
it('has an empty type filter when there are no results', async () => {
fetchMock.post(searchEndpoint, returnEmptyResult, { overwriteRoutes: true });
await renderLibraryPage();
const filterButton = screen.getByRole('button', { name: /type/i });
fireEvent.click(filterButton);
expect(screen.getByText(/no matching components/i)).toBeInTheDocument();
});
it('should create a collection', async () => {
await renderLibraryPage();
const title = 'This is a Test';
const description = 'This is the description of the Test';
const url = getLibraryCollectionsApiUrl(mockContentLibrary.libraryId);
axiosMock.onPost(url).reply(200, {
id: '1',
slug: 'this-is-a-test',
title,
description,
});
expect(await screen.findByRole('heading')).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 collection Modal
const sidebar = screen.getByTestId('library-sidebar');
const newCollectionButton = within(sidebar).getAllByRole('button', { name: /collection/i })[0];
fireEvent.click(newCollectionButton);
const collectionModalHeading = await screen.findByRole('heading', { name: /new collection/i });
expect(collectionModalHeading).toBeInTheDocument();
// Click on Cancel button
const cancelButton = screen.getByRole('button', { name: /cancel/i });
fireEvent.click(cancelButton);
expect(collectionModalHeading).not.toBeInTheDocument();
// Open new collection modal again and create a collection
fireEvent.click(newCollectionButton);
const createButton = screen.getByRole('button', { name: /create/i });
const nameField = screen.getByRole('textbox', { name: /name your collection/i });
const descriptionField = screen.getByRole('textbox', { name: /add a description \(optional\)/i });
fireEvent.change(nameField, { target: { value: title } });
fireEvent.change(descriptionField, { target: { value: description } });
fireEvent.click(createButton);
// Check success toast
await waitFor(() => expect(axiosMock.history.post.length).toBe(1));
expect(axiosMock.history.post[0].url).toBe(url);
expect(axiosMock.history.post[0].data).toContain(`"title":"${title}"`);
expect(axiosMock.history.post[0].data).toContain(`"description":"${description}"`);
expect(mockShowToast).toHaveBeenCalledWith('Collection created successfully');
});
it('should show validations in create collection', async () => {
await renderLibraryPage();
const title = 'This is a Test';
const description = 'This is the description of the Test';
const url = getLibraryCollectionsApiUrl(mockContentLibrary.libraryId);
axiosMock.onPost(url).reply(200, {
id: '1',
slug: 'this-is-a-test',
title,
description,
});
expect(await screen.findByRole('heading')).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 collection Modal
const sidebar = screen.getByTestId('library-sidebar');
const newCollectionButton = within(sidebar).getAllByRole('button', { name: /collection/i })[0];
fireEvent.click(newCollectionButton);
const collectionModalHeading = await screen.findByRole('heading', { name: /new collection/i });
expect(collectionModalHeading).toBeInTheDocument();
const nameField = screen.getByRole('textbox', { name: /name your collection/i });
fireEvent.focus(nameField);
fireEvent.blur(nameField);
// Click on create with an empty name
const createButton = screen.getByRole('button', { name: /create/i });
fireEvent.click(createButton);
expect(await screen.findByText(/collection name is required/i)).toBeInTheDocument();
});
it('should show error on create collection', async () => {
await renderLibraryPage();
const title = 'This is a Test';
const description = 'This is the description of the Test';
const url = getLibraryCollectionsApiUrl(mockContentLibrary.libraryId);
axiosMock.onPost(url).reply(500);
expect(await screen.findByRole('heading')).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 collection Modal
const sidebar = screen.getByTestId('library-sidebar');
const newCollectionButton = within(sidebar).getAllByRole('button', { name: /collection/i })[0];
fireEvent.click(newCollectionButton);
const collectionModalHeading = await screen.findByRole('heading', { name: /new collection/i });
expect(collectionModalHeading).toBeInTheDocument();
// Create a normal collection
const createButton = screen.getByRole('button', { name: /create/i });
const nameField = screen.getByRole('textbox', { name: /name your collection/i });
const descriptionField = screen.getByRole('textbox', { name: /add a description \(optional\)/i });
fireEvent.change(nameField, { target: { value: title } });
fireEvent.change(descriptionField, { target: { value: description } });
fireEvent.click(createButton);
// Check error toast
await waitFor(() => expect(axiosMock.history.post.length).toBe(1));
expect(mockShowToast).toHaveBeenCalledWith('There is an error when creating the library collection');
});
test.each([
{
label: 'should create a unit',
containerType: 'unit',
},
{
label: 'should create a section',
containerType: 'section',
},
{
label: 'should create a subsection',
containerType: 'subsection',
},
])('$label', async ({ containerType }) => {
await renderLibraryPage();
const title = `This is a Test ${containerType}`;
const url = getLibraryContainersApiUrl(mockContentLibrary.libraryId);
axiosMock.onPost(url).reply(200, {
id: `lct:org:libId:${containerType}:1`,
slug: 'this-is-a-test',
title,
});
expect(await screen.findByRole('heading')).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 container 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();
// Click on Cancel button
const cancelButton = screen.getByRole('button', { name: /cancel/i });
fireEvent.click(cancelButton);
expect(containerModalHeading).not.toBeInTheDocument();
// Open new container modal again and create a container
fireEvent.click(newContainerButton);
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: title } });
fireEvent.click(createButton);
// Check success
await waitFor(() => expect(axiosMock.history.post.length).toBe(1));
expect(axiosMock.history.post[0].url).toBe(url);
expect(axiosMock.history.post[0].data).toContain(`"display_name":"${title}"`);
expect(axiosMock.history.post[0].data).toContain(`"container_type":"${containerType}"`);
expect(mockShowToast).toHaveBeenCalledWith(
expect.stringMatching(new RegExp(`${containerType} created successfully`, 'i')),
);
});
test.each([
{
label: 'should show validations in create unit',
containerType: 'unit',
},
{
label: 'should show validations in create section',
containerType: 'section',
},
{
label: 'should show validations in create subsection',
containerType: 'subsection',
},
])('$label', async ({ containerType }) => {
await renderLibraryPage();
const title = `This is a Test ${containerType}`;
const url = getLibraryContainersApiUrl(mockContentLibrary.libraryId);
axiosMock.onPost(url).reply(200, {
id: '1',
slug: 'this-is-a-test',
title,
});
expect(await screen.findByRole('heading')).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 container 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();
const nameField = screen.getByRole('textbox', { name: new RegExp(`name your ${containerType}`, 'i') });
fireEvent.focus(nameField);
fireEvent.blur(nameField);
// Click on create with an empty name
const createButton = screen.getByRole('button', { name: /create/i });
fireEvent.click(createButton);
expect(await screen.findByText(new RegExp(`${containerType} name is required`, 'i'))).toBeInTheDocument();
});
test.each([
{
label: 'should show error on create unit',
containerType: 'unit',
},
{
label: 'should show error on create section',
containerType: 'section',
},
{
label: 'should show error on create subsection',
containerType: 'subsection',
},
])('$label', async ({ containerType }) => {
await renderLibraryPage();
const displayName = `This is a Test ${containerType}`;
const url = getLibraryContainersApiUrl(mockContentLibrary.libraryId);
axiosMock.onPost(url).reply(500);
expect(await screen.findByRole('heading')).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 container 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();
// Create a container
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: displayName } });
fireEvent.click(createButton);
// Check error toast
await waitFor(() => expect(axiosMock.history.post.length).toBe(1));
expect(mockShowToast).toHaveBeenCalledWith(
expect.stringMatching(new RegExp(`There is an error when creating the library ${containerType}`, 'i')),
);
});
it('shows a single block when usageKey query param is set', async () => {
render(<LibraryLayout />, {
path,
routerProps: {
initialEntries: [
`/library/${mockContentLibrary.libraryId}/components?usageKey=${mockXBlockFields.usageKeyHtml}`,
],
},
});
await waitFor(() => {
expect(fetchMock).toHaveBeenLastCalledWith(searchEndpoint, {
body: expect.stringContaining(mockXBlockFields.usageKeyHtml),
headers: expect.anything(),
method: 'POST',
});
});
expect(screen.queryByPlaceholderText('Displaying single block, clear filters to search')).toBeInTheDocument();
const { displayName } = mockXBlockFields.dataHtml;
const sidebar = screen.getByTestId('library-sidebar');
const { getByText } = within(sidebar);
// should display the component with passed param: usageKey in the sidebar
expect(getByText(displayName)).toBeInTheDocument();
// clear usageKey filter
const clearFitlersButton = screen.getByRole('button', { name: /clear filters/i });
fireEvent.click(clearFitlersButton);
await waitFor(() => {
expect(fetchMock).toHaveBeenLastCalledWith(searchEndpoint, {
body: expect.not.stringContaining(mockXBlockFields.usageKeyHtml),
method: 'POST',
headers: expect.anything(),
});
});
});
it('filters by publish status', async () => {
await renderLibraryPage();
// Open the publish status filter dropdown
const filterButton = screen.getByRole('button', { name: /publish status/i });
fireEvent.click(filterButton);
// Test each publish status filter option
const publishedCheckbox = screen.getByRole('checkbox', { name: /^published \d+$/i });
const modifiedCheckbox = screen.getByRole('checkbox', { name: /^modified since publish \d+$/i });
const neverPublishedCheckbox = screen.getByRole('checkbox', { name: /^never published \d+$/i });
// Verify initial state - no clear filters button
expect(screen.queryByRole('button', { name: /clear filters/i })).not.toBeInTheDocument();
// Test Published filter
fireEvent.click(publishedCheckbox);
// Wait for both the API call and the UI update
await waitFor(() => {
// Check that the API was called with the correct filter
expect(fetchMock).toHaveBeenLastCalledWith(searchEndpoint, {
body: expect.stringContaining('"publish_status = published"'),
method: 'POST',