forked from openedx/frontend-app-authoring
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCreateLibrary.test.tsx
More file actions
968 lines (792 loc) · 34.6 KB
/
CreateLibrary.test.tsx
File metadata and controls
968 lines (792 loc) · 34.6 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
import React from 'react';
import type MockAdapter from 'axios-mock-adapter';
import userEvent from '@testing-library/user-event';
import {
fireEvent,
initializeMocks,
render,
screen,
waitFor,
} from '@src/testUtils';
import studioHomeMock from '@src/studio-home/__mocks__/studioHomeMock';
import { getStudioHomeApiUrl } from '@src/studio-home/data/api';
import { getApiWaffleFlagsUrl } from '@src/data/api';
import { CreateLibrary } from '.';
import { getContentLibraryV2CreateApiUrl } from './data/api';
import { LibraryRestoreStatus } from './data/restoreConstants';
import messages from './messages';
const mockNavigate = jest.fn();
let axiosMock: MockAdapter;
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: () => mockNavigate,
}));
jest.mock('@src/generic/data/apiHooks', () => ({
...jest.requireActual('@src/generic/data/apiHooks'),
useOrganizationListData: () => ({
data: ['org1', 'org2', 'org3', 'org4', 'org5'],
isLoading: false,
}),
}));
const mockRestoreMutate = jest.fn();
let mockRestoreStatusData: any = {};
let mockRestoreMutationError: any = null;
let mockRestoreMutationPending = false;
jest.mock('./data/apiHooks', () => ({
...jest.requireActual('./data/apiHooks'),
useCreateLibraryRestore: () => ({
mutate: mockRestoreMutate,
error: mockRestoreMutationError,
isPending: mockRestoreMutationPending,
isError: !!mockRestoreMutationError,
}),
useGetLibraryRestoreStatus: () => ({
data: mockRestoreStatusData,
}),
}));
describe('<CreateLibrary />', () => {
beforeEach(() => {
axiosMock = initializeMocks().axiosMock;
axiosMock
.onGet(getApiWaffleFlagsUrl(undefined))
.reply(200, {});
// Reset restore mocks
mockRestoreMutate.mockReset();
mockRestoreStatusData = {};
mockRestoreMutationError = null;
mockRestoreMutationPending = false;
});
test('call api data with correct data', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
axiosMock.onPost(getContentLibraryV2CreateApiUrl()).reply(200, {
id: 'library-id',
});
render(<CreateLibrary />);
const titleInput = await screen.findByRole('textbox', { name: /library name/i });
await user.click(titleInput);
await user.type(titleInput, 'Test Library Name');
const orgInput = await screen.findByRole('combobox', { name: /organization/i });
await user.click(orgInput);
await user.type(orgInput, 'org1');
await user.tab();
const slugInput = await screen.findByRole('textbox', { name: /library id/i });
await user.click(slugInput);
await user.type(slugInput, 'test_library_slug');
fireEvent.click(await screen.findByRole('button', { name: 'Create' }));
await waitFor(() => {
expect(axiosMock.history.post.length).toBe(1);
expect(axiosMock.history.post[0].data).toBe(
'{"description":"","title":"Test Library Name","org":"org1","slug":"test_library_slug"}',
);
expect(mockNavigate).toHaveBeenCalledWith('/library/library-id');
});
});
test('cannot create new org unless allowed', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
axiosMock.onPost(getContentLibraryV2CreateApiUrl()).reply(200, {
id: 'library-id',
});
render(<CreateLibrary />);
const titleInput = await screen.findByRole('textbox', { name: /library name/i });
await user.click(titleInput);
await user.type(titleInput, 'Test Library Name');
// We cannot create a new org, and so we're restricted to the allowed list
const orgOptions = screen.getByTestId('autosuggest-iconbutton');
await user.click(orgOptions);
expect(screen.getByText('org1')).toBeInTheDocument();
['org2', 'org3', 'org4', 'org5'].forEach((org) => expect(screen.queryByText(org)).not.toBeInTheDocument());
const orgInput = await screen.findByRole('combobox', { name: /organization/i });
await user.click(orgInput);
await user.type(orgInput, 'NewOrg');
await user.tab();
const slugInput = await screen.findByRole('textbox', { name: /library id/i });
await user.click(slugInput);
await user.type(slugInput, 'test_library_slug');
fireEvent.click(await screen.findByRole('button', { name: 'Create' }));
await waitFor(() => {
expect(axiosMock.history.post.length).toBe(0);
});
expect(await screen.findByText('Required field.')).toBeInTheDocument();
});
test('can create new org if allowed', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, {
...studioHomeMock,
allow_to_create_new_org: true,
});
axiosMock.onPost(getContentLibraryV2CreateApiUrl()).reply(200, {
id: 'library-id',
});
render(<CreateLibrary />);
const titleInput = await screen.findByRole('textbox', { name: /library name/i });
await user.click(titleInput);
await user.type(titleInput, 'Test Library Name');
// We can create a new org, so we're also allowed to use any existing org
const orgOptions = screen.getByTestId('autosuggest-iconbutton');
await user.click(orgOptions);
['org1', 'org2', 'org3', 'org4', 'org5'].forEach((org) => expect(screen.queryByText(org)).toBeInTheDocument());
const orgInput = await screen.findByRole('combobox', { name: /organization/i });
await user.click(orgInput);
await user.type(orgInput, 'NewOrg');
await user.tab();
const slugInput = await screen.findByRole('textbox', { name: /library id/i });
await user.click(slugInput);
await user.type(slugInput, 'test_library_slug');
fireEvent.click(await screen.findByRole('button', { name: 'Create' }));
await waitFor(() => {
expect(axiosMock.history.post.length).toBe(1);
expect(axiosMock.history.post[0].data).toBe(
'{"description":"","title":"Test Library Name","org":"NewOrg","slug":"test_library_slug"}',
);
expect(mockNavigate).toHaveBeenCalledWith('/library/library-id');
});
});
test('show api error', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
axiosMock.onPost(getContentLibraryV2CreateApiUrl()).reply(400, {
field: 'Error message',
});
render(<CreateLibrary />);
const titleInput = await screen.findByRole('textbox', { name: /library name/i });
await user.click(titleInput);
await user.type(titleInput, 'Test Library Name');
const orgInput = await screen.findByTestId('autosuggest-textbox-input');
await user.click(orgInput);
await user.type(orgInput, 'org1');
await user.tab();
const slugInput = await screen.findByRole('textbox', { name: /library id/i });
await user.click(slugInput);
await user.type(slugInput, 'test_library_slug');
fireEvent.click(await screen.findByRole('button', { name: 'Create' }));
await waitFor(async () => {
expect(axiosMock.history.post.length).toBe(1);
expect(axiosMock.history.post[0].data).toBe(
'{"description":"","title":"Test Library Name","org":"org1","slug":"test_library_slug"}',
);
expect(mockNavigate).not.toHaveBeenCalled();
const errorMessage = 'Request failed with status code 400{ "field": "Error message" }';
expect(await screen.findByRole('alert')).toHaveTextContent(errorMessage);
});
});
test('cancel creating library navigates to libraries page', async () => {
render(<CreateLibrary />);
fireEvent.click(await screen.findByRole('button', { name: /cancel/i }));
await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledWith('/libraries');
});
});
test('calls handleCancel when used in modal', async () => {
const mockHandleCancel = jest.fn();
const mockHandlePostCreate = jest.fn();
render(
<CreateLibrary
showInModal
handleCancel={mockHandleCancel}
handlePostCreate={mockHandlePostCreate}
/>,
);
fireEvent.click(await screen.findByRole('button', { name: /cancel/i }));
await waitFor(() => {
expect(mockHandleCancel).toHaveBeenCalled();
expect(mockNavigate).not.toHaveBeenCalled();
});
});
test('calls handlePostCreate when used in modal and library is created', async () => {
const mockHandleCancel = jest.fn();
const mockHandlePostCreate = jest.fn();
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
axiosMock.onPost(getContentLibraryV2CreateApiUrl()).reply(200, {
id: 'library-id',
title: 'Test Library',
});
render(
<CreateLibrary
showInModal
handleCancel={mockHandleCancel}
handlePostCreate={mockHandlePostCreate}
/>,
);
const titleInput = await screen.findByRole('textbox', { name: /library name/i });
await user.click(titleInput);
await user.type(titleInput, 'Test Library Name');
const orgInput = await screen.findByRole('combobox', { name: /organization/i });
await user.click(orgInput);
await user.type(orgInput, 'org1');
await user.tab();
const slugInput = await screen.findByRole('textbox', { name: /library id/i });
await user.click(slugInput);
await user.type(slugInput, 'test_library_slug');
fireEvent.click(await screen.findByRole('button', { name: 'Create' }));
await waitFor(() => {
expect(mockHandlePostCreate).toHaveBeenCalledWith({
id: 'library-id',
title: 'Test Library',
});
expect(mockNavigate).not.toHaveBeenCalled();
});
});
describe('Archive Upload Functionality', () => {
test('shows create from archive button and switches to archive mode', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
render(<CreateLibrary />);
const createFromArchiveBtn = await screen.findByRole('button', { name: messages.createFromArchiveButton.defaultMessage });
expect(createFromArchiveBtn).toBeInTheDocument();
await user.click(createFromArchiveBtn);
// Should show dropzone after switching to archive mode
expect(screen.getByTestId('library-archive-dropzone')).toBeInTheDocument();
});
test('handles file upload and starts restore process', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
mockRestoreMutate.mockImplementation((_file: File, { onSuccess }: any) => {
onSuccess({ taskId: 'task-123' });
});
render(<CreateLibrary />);
// Switch to archive mode
const createFromArchiveBtn = await screen.findByRole('button', { name: messages.createFromArchiveButton.defaultMessage });
await user.click(createFromArchiveBtn);
// Create a mock file
const file = new File(['test content'], 'test-archive.zip', { type: 'application/zip' });
const dropzone = screen.getByTestId('library-archive-dropzone');
const input = dropzone.querySelector('input[type="file"]') as HTMLInputElement;
// Mock file selection
Object.defineProperty(input, 'files', {
value: [file],
writable: false,
});
// Trigger file change
fireEvent.change(input);
await waitFor(() => {
expect(mockRestoreMutate).toHaveBeenCalledWith(
file,
expect.objectContaining({
onSuccess: expect.any(Function),
onError: expect.any(Function),
}),
);
});
});
test('triggers onError callback when restore mutation fails during file upload', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
// Mock console.error to capture the call
const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => { });
// Mock the restore mutation to trigger onError callback immediately
mockRestoreMutate.mockImplementation((_file: File, { onError }: any) => {
const restoreError = new Error('Restore mutation failed');
// Call onError immediately to trigger the handleError(restoreError) line
onError(restoreError);
});
render(<CreateLibrary />);
// Switch to archive mode
const createFromArchiveBtn = await screen.findByRole('button', { name: messages.createFromArchiveButton.defaultMessage });
await user.click(createFromArchiveBtn);
// Upload a valid file that will trigger the restore process and its onError callback
const file = new File(['test content'], 'test-archive.zip', { type: 'application/zip' });
const dropzone = screen.getByTestId('library-archive-dropzone');
const input = dropzone.querySelector('input[type="file"]') as HTMLInputElement;
Object.defineProperty(input, 'files', {
value: [file],
writable: false,
});
fireEvent.change(input);
await waitFor(() => {
expect(mockRestoreMutate).toHaveBeenCalledWith(
file,
expect.objectContaining({
onSuccess: expect.any(Function),
onError: expect.any(Function),
}),
);
});
consoleSpy.mockRestore();
});
test('shows restore in progress alert when status is pending', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
// Set task ID so the restore status hook is enabled
const mockTaskId = 'test-task-123';
// Pre-set the restore status to pending
mockRestoreStatusData = {
state: LibraryRestoreStatus.Pending,
result: null,
error: null,
errorLog: null,
};
// Mock the mutation to return a task ID
mockRestoreMutate.mockImplementation((_file: File, { onSuccess }: any) => {
onSuccess({ taskId: mockTaskId });
});
render(<CreateLibrary />);
// Switch to archive mode
const createFromArchiveBtn = await screen.findByRole('button', { name: messages.createFromArchiveButton.defaultMessage });
await user.click(createFromArchiveBtn);
// Upload a file to trigger the restore process
const file = new File(['test content'], 'test-archive.zip', { type: 'application/zip' });
const dropzone = screen.getByTestId('library-archive-dropzone');
const input = dropzone.querySelector('input[type="file"]') as HTMLInputElement;
Object.defineProperty(input, 'files', {
value: [file],
writable: false,
});
fireEvent.change(input);
// Should show the restore in progress alert
await waitFor(() => {
expect(screen.getByText(messages.restoreInProgress.defaultMessage)).toBeInTheDocument();
});
});
test('shows success state with archive details after upload', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
const mockResult = {
learningPackageId: 123,
title: 'Test Archive Library',
org: 'TestOrg',
slug: 'test-archive',
key: 'TestOrg/test-archive',
archiveKey: 'archive-key',
containers: 5,
components: 15,
collections: 3,
sections: 8,
subsections: 12,
units: 20,
createdOnServer: 'test.com',
createdAt: '2025-01-01T10:00:00Z',
createdBy: {
username: 'testuser',
email: '[email protected]',
},
};
// Pre-set the restore status to succeeded
mockRestoreStatusData = {
state: LibraryRestoreStatus.Succeeded,
result: mockResult,
error: null,
errorLog: null,
};
// Mock the restore mutation to return a task ID
mockRestoreMutate.mockImplementation((_file: File, { onSuccess }: any) => {
onSuccess({ taskId: 'task-123' });
});
render(<CreateLibrary />);
// Switch to archive mode
const createFromArchiveBtn = await screen.findByRole('button', { name: messages.createFromArchiveButton.defaultMessage });
await user.click(createFromArchiveBtn);
// Upload a file to trigger the restore process
const file = new File(['test content'], 'test-archive.zip', { type: 'application/zip' });
const dropzone = screen.getByTestId('library-archive-dropzone');
const input = dropzone.querySelector('input[type="file"]') as HTMLInputElement;
Object.defineProperty(input, 'files', {
value: [file],
writable: false,
});
fireEvent.change(input);
// Wait for the restore to complete and archive details to be shown
await waitFor(() => {
expect(screen.getByText('Test Archive Library')).toBeInTheDocument();
expect(screen.getByText('TestOrg / test-archive')).toBeInTheDocument();
// Testing the archive details summary
expect(screen.getByText(/Contains 8 sections, 12 subsections, 20 units, 15 components/i)).toBeInTheDocument();
expect(screen.getByText(/Created on instance test.com/i)).toBeInTheDocument();
expect(screen.getByText(/by user [email protected]/i)).toBeInTheDocument();
});
});
test('shows success state without instance and user email information', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
const mockResult = {
learningPackageId: 123,
title: 'Test Archive Library',
org: 'TestOrg',
slug: 'test-archive',
key: 'TestOrg/test-archive',
archiveKey: 'archive-key',
containers: 5,
components: 15,
collections: 3,
sections: 8,
subsections: 12,
units: 20,
createdOnServer: null,
createdAt: '2025-01-01T10:00:00Z',
createdBy: null,
};
// Pre-set the restore status to succeeded
mockRestoreStatusData = {
state: LibraryRestoreStatus.Succeeded,
result: mockResult,
error: null,
errorLog: null,
};
// Mock the restore mutation to return a task ID
mockRestoreMutate.mockImplementation((_file: File, { onSuccess }: any) => {
onSuccess({ taskId: 'task-123' });
});
render(<CreateLibrary />);
// Switch to archive mode
const createFromArchiveBtn = await screen.findByRole('button', { name: messages.createFromArchiveButton.defaultMessage });
await user.click(createFromArchiveBtn);
// Upload a file to trigger the restore process
const file = new File(['test content'], 'test-archive.zip', { type: 'application/zip' });
const dropzone = screen.getByTestId('library-archive-dropzone');
const input = dropzone.querySelector('input[type="file"]') as HTMLInputElement;
Object.defineProperty(input, 'files', {
value: [file],
writable: false,
});
fireEvent.change(input);
// Wait for the restore to complete and archive details to be shown
await waitFor(() => {
// Testing the archive details summary without instance and user email
expect(screen.getByText(/Contains 8 sections, 12 subsections, 20 units, 15 components/i)).toBeInTheDocument();
expect(screen.queryByText(/Created on instance/i)).not.toBeInTheDocument();
expect(screen.queryByText(/by user/i)).not.toBeInTheDocument();
});
});
test('shows error state with error message and link after failed upload', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
// Pre-set the restore status to failed
mockRestoreStatusData = {
state: LibraryRestoreStatus.Failed,
result: null,
error: 'Library restore failed. See error log for details.',
errorLog: 'http://example.com/error.log',
};
// Mock the restore mutation to return a task ID
mockRestoreMutate.mockImplementation((_file: File, { onSuccess }: any) => {
onSuccess({ taskId: 'task-456' });
});
render(<CreateLibrary />);
// Switch to archive mode
const createFromArchiveBtn = await screen.findByRole('button', { name: messages.createFromArchiveButton.defaultMessage });
await user.click(createFromArchiveBtn);
// Upload a file to trigger the restore process
const file = new File(['test content'], 'test-archive.zip', { type: 'application/zip' });
const dropzone = screen.getByTestId('library-archive-dropzone');
const input = dropzone.querySelector('input[type="file"]') as HTMLInputElement;
Object.defineProperty(input, 'files', {
value: [file],
writable: false,
});
fireEvent.change(input);
// Wait for the error to be shown
await waitFor(() => {
expect(screen.getByText(messages.restoreError.defaultMessage)).toBeInTheDocument();
});
// Should show error log link
const errorLink = screen.getByText(messages.viewErrorLogText.defaultMessage);
expect(errorLink).toBeInTheDocument();
expect(errorLink.closest('a')).toHaveAttribute('href', 'http://example.com/error.log');
});
test('validates file types and shows error for invalid files', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
render(<CreateLibrary />);
// Switch to archive mode
const createFromArchiveBtn = await screen.findByRole('button', { name: messages.createFromArchiveButton.defaultMessage });
await user.click(createFromArchiveBtn);
// Try to upload a file with correct MIME type but wrong extension to trigger our custom validation
const file = new File(['test content'], 'test-file.doc', { type: 'application/zip' });
const dropzone = screen.getByTestId('library-archive-dropzone');
const input = dropzone.querySelector('input[type="file"]') as HTMLInputElement;
Object.defineProperty(input, 'files', {
value: [file],
writable: false,
});
fireEvent.change(input);
// Should not call restore mutation for invalid file
expect(mockRestoreMutate).not.toHaveBeenCalled();
// Should show error message for invalid file type (Dropzone shows generic error)
await waitFor(() => {
expect(screen.getByText(/A problem occured while uploading your file/i)).toBeInTheDocument();
});
});
test('shows archive preview only when all conditions are met', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
const mockResult = {
learningPackageId: 123,
title: 'Test Archive Library',
org: 'TestOrg',
slug: 'test-archive',
key: 'TestOrg/test-archive',
archiveKey: 'archive-key',
containers: 5,
components: 15,
collections: 3,
sections: 8,
subsections: 12,
units: 20,
createdOnServer: '2025-01-01T10:00:00Z',
createdAt: '2025-01-01T10:00:00Z',
createdBy: {
username: 'testuser',
email: '[email protected]',
},
};
render(<CreateLibrary />);
// Switch to archive mode
const createFromArchiveBtn = await screen.findByRole('button', { name: messages.createFromArchiveButton.defaultMessage });
await user.click(createFromArchiveBtn);
// Initially no archive preview should be shown (no uploaded file)
expect(screen.queryByText('Test Archive Library')).not.toBeInTheDocument();
// Pre-set the final restore status to succeeded
mockRestoreStatusData = {
state: LibraryRestoreStatus.Succeeded,
result: mockResult,
};
// Mock successful file upload
mockRestoreMutate.mockImplementation((_file: File, { onSuccess }: any) => {
onSuccess({ taskId: 'task-123' });
});
// Upload file
const file = new File(['test content'], 'test-archive.zip', { type: 'application/zip' });
const dropzone = screen.getByTestId('library-archive-dropzone');
const input = dropzone.querySelector('input[type="file"]') as HTMLInputElement;
Object.defineProperty(input, 'files', {
value: [file],
writable: false,
});
fireEvent.change(input);
// Now archive preview should be shown because:
// uploadedFile && restoreStatus?.state === LibraryRestoreStatus.Succeeded && restoreStatus.result
await waitFor(() => {
expect(screen.getByText('Test Archive Library')).toBeInTheDocument();
expect(screen.getByText('TestOrg / test-archive')).toBeInTheDocument();
});
});
test('creates library from archive with learning package ID', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
axiosMock.onPost(getContentLibraryV2CreateApiUrl()).reply(200, {
id: 'library-from-archive-id',
});
const mockResult = {
learningPackageId: 456, // Fixed: use camelCase to match actual API response
title: 'Restored Library',
org: 'RestoredOrg',
slug: 'restored-lib',
key: 'RestoredOrg/restored-lib',
archiveKey: 'archive-key', // Fixed: use camelCase
containers: 3,
components: 10,
collections: 2,
sections: 5,
subsections: 8,
units: 15,
createdOnServer: '2025-01-01T12:00:00Z', // Fixed: use camelCase
createdAt: '2025-01-01T12:00:00Z',
createdBy: { // Fixed: use camelCase
username: 'restoreuser',
email: '[email protected]',
},
};
mockRestoreStatusData = {
state: LibraryRestoreStatus.Succeeded,
result: mockResult,
error: null,
errorLog: null,
};
render(<CreateLibrary />);
// Switch to archive mode
const createFromArchiveBtn = await screen.findByRole('button', { name: messages.createFromArchiveButton.defaultMessage });
await user.click(createFromArchiveBtn);
// Fill in form fields
const titleInput = await screen.findByRole('textbox', { name: /library name/i });
await user.click(titleInput);
await user.type(titleInput, 'New Library from Archive');
const orgInput = await screen.findByRole('combobox', { name: /organization/i });
await user.click(orgInput);
await user.type(orgInput, 'org1');
await user.tab();
const slugInput = await screen.findByRole('textbox', { name: /library id/i });
await user.click(slugInput);
await user.type(slugInput, 'new_library_slug');
// Submit form
fireEvent.click(await screen.findByRole('button', { name: /create/i }));
await waitFor(() => {
expect(axiosMock.history.post.length).toBe(1);
const postData = JSON.parse(axiosMock.history.post[0].data);
expect(postData).toEqual({
description: '',
title: 'New Library from Archive',
org: 'org1',
slug: 'new_library_slug',
learning_package: 456, // Should include the learning_package_id from restore
});
expect(mockNavigate).toHaveBeenCalledWith('/library/library-from-archive-id');
});
});
test('handles restore mutation error', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
mockRestoreMutationError = new Error('Upload failed');
render(<CreateLibrary />);
// Switch to archive mode
const createFromArchiveBtn = await screen.findByRole('button', { name: messages.createFromArchiveButton.defaultMessage });
await user.click(createFromArchiveBtn);
// Should show error alert with the specific error message
expect(screen.getByText('Upload failed')).toBeInTheDocument();
});
test('shows generic error when no specific error message available', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
mockRestoreMutationError = {}; // Error without message
render(<CreateLibrary />);
// Switch to archive mode
const createFromArchiveBtn = await screen.findByRole('button', { name: messages.createFromArchiveButton.defaultMessage });
await user.click(createFromArchiveBtn);
// Should show generic error message
expect(screen.getByText(messages.genericErrorMessage.defaultMessage)).toBeInTheDocument();
});
test('includes learning_package field when creating from successful archive restore', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
axiosMock.onPost(getContentLibraryV2CreateApiUrl()).reply(200, {
id: 'library-from-archive-id',
});
// Set up successful restore state with learningPackageId
mockRestoreStatusData = {
state: LibraryRestoreStatus.Succeeded,
result: {
learningPackageId: 789,
title: 'Archive Library',
org: 'ArchiveOrg',
slug: 'archive-slug',
key: 'ArchiveOrg/archive-slug',
archiveKey: 'test-archive-key',
containers: 2,
components: 8,
collections: 1,
sections: 4,
subsections: 6,
units: 10,
createdOnServer: '2025-01-01T15:00:00Z',
createdAt: '2025-01-01T15:00:00Z',
createdBy: {
username: 'archiveuser',
email: '[email protected]',
},
},
error: null,
errorLog: null,
};
render(<CreateLibrary />);
// Switch to archive mode
const createFromArchiveBtn = await screen.findByRole('button', { name: messages.createFromArchiveButton.defaultMessage });
await user.click(createFromArchiveBtn);
// Fill in form fields
const titleInput = await screen.findByRole('textbox', { name: /library name/i });
await user.type(titleInput, 'My New Library');
const orgInput = await screen.findByRole('combobox', { name: /organization/i });
await user.click(orgInput);
await user.type(orgInput, 'org1');
await user.tab();
const slugInput = await screen.findByRole('textbox', { name: /library id/i });
await user.type(slugInput, 'my_new_library');
// Submit the form - this should trigger the code path that includes learning_package
fireEvent.click(await screen.findByRole('button', { name: /create/i }));
await waitFor(() => {
expect(axiosMock.history.post.length).toBe(1);
const postData = JSON.parse(axiosMock.history.post[0].data);
// Verify that the learning_package field is included with the correct value
expect(postData).toEqual({
description: '',
title: 'My New Library',
org: 'org1',
slug: 'my_new_library',
learning_package: 789, // Tests: submitData.learning_package = restoreStatus.result.learningPackageId
});
});
});
test('does not include learning_package when creating from archive but restore failed', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
axiosMock.onPost(getContentLibraryV2CreateApiUrl()).reply(200, {
id: 'library-from-failed-restore-id',
});
// Set up failed restore state
mockRestoreStatusData = {
state: LibraryRestoreStatus.Failed,
result: null,
error: 'Restore failed',
errorLog: null,
};
render(<CreateLibrary />);
// Switch to archive mode
const createFromArchiveBtn = await screen.findByRole('button', { name: messages.createFromArchiveButton.defaultMessage });
await user.click(createFromArchiveBtn);
// Fill in form fields
const titleInput = await screen.findByRole('textbox', { name: /library name/i });
await user.type(titleInput, 'Library from Failed Restore');
const orgInput = await screen.findByRole('combobox', { name: /organization/i });
await user.click(orgInput);
await user.type(orgInput, 'org1');
await user.tab();
const slugInput = await screen.findByRole('textbox', { name: /library id/i });
await user.type(slugInput, 'failed_restore_lib');
// Submit the form - this should NOT include learning_package since restore failed
fireEvent.click(await screen.findByRole('button', { name: /create/i }));
await waitFor(() => {
expect(axiosMock.history.post.length).toBe(1);
const postData = JSON.parse(axiosMock.history.post[0].data);
// Verify that learning_package field is NOT included since restore failed
expect(postData).toEqual({
description: '',
title: 'Library from Failed Restore',
org: 'org1',
slug: 'failed_restore_lib',
});
expect(postData).not.toHaveProperty('learning_package');
});
});
test('does not include learning_package when creating from archive but result is null', async () => {
const user = userEvent.setup();
axiosMock.onGet(getStudioHomeApiUrl()).reply(200, studioHomeMock);
axiosMock.onPost(getContentLibraryV2CreateApiUrl()).reply(200, {
id: 'library-from-null-result-id',
});
// Set up successful restore state but with null result
mockRestoreStatusData = {
state: LibraryRestoreStatus.Succeeded,
result: null,
error: null,
errorLog: null,
};
render(<CreateLibrary />);
// Switch to archive mode
const createFromArchiveBtn = await screen.findByRole('button', { name: messages.createFromArchiveButton.defaultMessage });
await user.click(createFromArchiveBtn);
// Fill in form fields
const titleInput = await screen.findByRole('textbox', { name: /library name/i });
await user.type(titleInput, 'Library with Null Result');
const orgInput = await screen.findByRole('combobox', { name: /organization/i });
await user.click(orgInput);
await user.type(orgInput, 'org1');
await user.tab();
const slugInput = await screen.findByRole('textbox', { name: /library id/i });
await user.type(slugInput, 'null_result_lib');
// Submit the form - this should NOT include learning_package since result is null
fireEvent.click(await screen.findByRole('button', { name: /create/i }));
await waitFor(() => {
expect(axiosMock.history.post.length).toBe(1);
const postData = JSON.parse(axiosMock.history.post[0].data);
// Verify that learning_package field is NOT included since result is null
expect(postData).toEqual({
description: '',
title: 'Library with Null Result',
org: 'org1',
slug: 'null_result_lib',
});
expect(postData).not.toHaveProperty('learning_package');
});
});
});
});