-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathcloud.component.spec.ts
More file actions
879 lines (747 loc) · 27.2 KB
/
Copy pathcloud.component.spec.ts
File metadata and controls
879 lines (747 loc) · 27.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
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
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { Router } from '@angular/router';
import { of, throwError, Subject } from 'rxjs';
import { ConfirmationService } from 'primeng/api';
import { CloudComponent } from './cloud.component';
import { CloudService } from '../../services/cloud.service';
import { UiToastService } from '../../core/services/ui-toast.service';
import { ScanJobDto } from '../../models/dtos/ScanJobDto';
import { SecureSendLinkDto } from '../../models/dtos/SecureSendLinkDto';
/**
* Exercises the folder virus-scan state machine end to end with a mocked
* CloudService and Jasmine's fake clock driving the poll timer.
*/
describe('CloudComponent virus scan', () => {
let component: CloudComponent;
let cloudMock: jasmine.SpyObj<CloudService>;
const runningJob: ScanJobDto = {
jobId: 'job-1',
path: '',
status: 'RUNNING',
filesScanned: 2,
infectedCount: 0,
};
const noopToast = {
success: () => {},
info: () => {},
warn: () => {},
error: () => {},
};
beforeEach(() => {
jasmine.clock().install();
cloudMock = jasmine.createSpyObj<CloudService>('CloudService', [
'startFolderScan',
'getScanJob',
]);
component = new CloudComponent(
cloudMock,
{} as never,
noopToast as never,
{} as never,
{} as never,
);
component.rootPath = '/root';
component.currentFolder = { path: '/root', name: 'root' } as never;
});
afterEach(() => jasmine.clock().uninstall());
it('polls until COMPLETED, then stops and exposes infected findings', () => {
cloudMock.startFolderScan.and.returnValue(of({ ...runningJob }));
const stillRunning: ScanJobDto = { ...runningJob, filesScanned: 3 };
const completed: ScanJobDto = {
jobId: 'job-1',
path: '',
status: 'COMPLETED',
filesScanned: 3,
infectedCount: 1,
findings: [{ path: 'a/evil.exe', verdict: 'INFECTED', detail: 'Eicar' }],
};
cloudMock.getScanJob.and.returnValues(of(stillRunning), of(completed));
component.scanCurrentFolder();
expect(component.scanning).toBeTrue();
expect(component.scanJob?.status).toBe('RUNNING');
jasmine.clock().tick(1200);
expect(component.scanning).toBeTrue();
jasmine.clock().tick(1200);
expect(component.scanning).toBeFalse();
expect(component.scanJob?.status).toBe('COMPLETED');
expect(component.scanInfectedFindings.length).toBe(1);
expect(component.scanNoThreats).toBeFalse();
const callsSoFar = cloudMock.getScanJob.calls.count();
jasmine.clock().tick(6000);
expect(cloudMock.getScanJob.calls.count()).toBe(callsSoFar);
});
it('detects a disabled scanner (every file errored) with a clear message', () => {
cloudMock.startFolderScan.and.returnValue(of({ ...runningJob }));
cloudMock.getScanJob.and.returnValue(
of({
jobId: 'job-1',
path: '',
status: 'COMPLETED',
filesScanned: 2,
infectedCount: 0,
findings: [
{
path: 'a.txt',
verdict: 'ERROR',
detail: 'virus scanning is disabled',
},
{
path: 'b.txt',
verdict: 'ERROR',
detail: 'virus scanning is disabled',
},
],
}),
);
component.scanCurrentFolder();
jasmine.clock().tick(1200);
expect(component.scanScannerUnavailable).toBeTrue();
expect(component.scanUnavailableMessage).toContain('turned off');
expect(component.scanNoThreats).toBeFalse();
});
it('treats an unreachable scanner as unavailable (no "disabled" detail)', () => {
cloudMock.startFolderScan.and.returnValue(of({ ...runningJob }));
cloudMock.getScanJob.and.returnValue(
of({
jobId: 'job-1',
path: '',
status: 'COMPLETED',
filesScanned: 1,
infectedCount: 0,
findings: [
{ path: 'a.txt', verdict: 'ERROR', detail: 'connection refused' },
],
}),
);
component.scanCurrentFolder();
jasmine.clock().tick(1200);
expect(component.scanScannerUnavailable).toBeTrue();
expect(component.scanUnavailableMessage).toContain('unavailable');
});
it('reports a clean scan as no threats', () => {
cloudMock.startFolderScan.and.returnValue(of({ ...runningJob }));
cloudMock.getScanJob.and.returnValue(
of({
jobId: 'job-1',
path: '',
status: 'COMPLETED',
filesScanned: 4,
infectedCount: 0,
findings: [],
}),
);
component.scanCurrentFolder();
jasmine.clock().tick(1200);
expect(component.scanNoThreats).toBeTrue();
expect(component.scanScannerUnavailable).toBeFalse();
expect(component.scanInfectedFindings.length).toBe(0);
});
it('surfaces a rate-limit (429) on start and never polls', () => {
cloudMock.startFolderScan.and.returnValue(
throwError(() => ({ status: 429 })),
);
component.scanCurrentFolder();
expect(component.scanning).toBeFalse();
expect(component.scanError).toContain('wait');
jasmine.clock().tick(6000);
expect(cloudMock.getScanJob).not.toHaveBeenCalled();
});
it('keeps the scan alive when polling is rate limited, and still completes', () => {
cloudMock.startFolderScan.and.returnValue(of({ ...runningJob }));
cloudMock.getScanJob.and.returnValues(
throwError(() => ({ status: 429 })),
of({ ...runningJob, status: 'COMPLETED', findings: [] }),
);
component.scanCurrentFolder();
jasmine.clock().tick(1200);
expect(component.scanning).toBeTrue();
expect(component.scanError).toBeUndefined();
jasmine.clock().tick(5000);
expect(component.scanning).toBeFalse();
expect(component.scanError).toBeUndefined();
expect(component.scanJob?.status).toBe('COMPLETED');
});
it('gives up on a persistently rate-limited scan without claiming it failed', () => {
cloudMock.startFolderScan.and.returnValue(of({ ...runningJob }));
cloudMock.getScanJob.and.returnValue(throwError(() => ({ status: 429 })));
component.scanCurrentFolder();
jasmine.clock().tick(1200);
jasmine.clock().tick(5000 * 5);
expect(component.scanning).toBeFalse();
expect(component.scanError).toContain('may still be running');
expect(cloudMock.getScanJob).toHaveBeenCalledTimes(6);
});
it('handles an expired job (404) during polling', () => {
cloudMock.startFolderScan.and.returnValue(of({ ...runningJob }));
cloudMock.getScanJob.and.returnValue(throwError(() => ({ status: 404 })));
component.scanCurrentFolder();
jasmine.clock().tick(1200);
expect(component.scanning).toBeFalse();
expect(component.scanError).toContain('no longer available');
});
it('stops polling once the dialog is closed mid-scan', () => {
cloudMock.startFolderScan.and.returnValue(of({ ...runningJob }));
cloudMock.getScanJob.and.returnValue(of({ ...runningJob }));
component.scanCurrentFolder();
jasmine.clock().tick(1200);
const calls = cloudMock.getScanJob.calls.count();
component.onScanDialogHide();
jasmine.clock().tick(6000);
expect(cloudMock.getScanJob.calls.count()).toBe(calls);
});
it('does not start polling if closed while the start request is in flight', () => {
const start$ = new Subject<ScanJobDto>();
cloudMock.startFolderScan.and.returnValue(start$.asObservable());
cloudMock.getScanJob.and.returnValue(of({ ...runningJob }));
component.scanCurrentFolder();
component.onScanDialogHide();
start$.next({ ...runningJob });
start$.complete();
jasmine.clock().tick(6000);
});
});
describe('CloudComponent Unsaved Changes Flow', () => {
let component: CloudComponent;
let cloudMock: jasmine.SpyObj<CloudService>;
let confirmMock: jasmine.SpyObj<ConfirmationService>;
let toastMock: jasmine.SpyObj<UiToastService>;
beforeEach(() => {
cloudMock = jasmine.createSpyObj<CloudService>('CloudService', [
'getFileContent',
'uploadFile',
'renameOrMoveFile',
'getFolderByPath',
'getFolderContent',
]);
cloudMock.getFolderByPath.and.returnValue(
of({ path: '/root', name: 'root', entries: [] } as any),
);
cloudMock.getFolderContent.and.returnValue(
of({ content: [], totalElements: 0, totalPages: 0, pageNumber: 0 }),
);
confirmMock = jasmine.createSpyObj<ConfirmationService>(
'ConfirmationService',
['confirm'],
);
toastMock = jasmine.createSpyObj<UiToastService>('UiToastService', [
'success',
'error',
]);
const sanitizerMock = {
bypassSecurityTrustHtml: (html: string) => html,
};
component = new CloudComponent(
cloudMock,
confirmMock,
toastMock as any,
{} as any,
sanitizerMock as any,
);
});
it('should track original content and not be dirty initially', () => {
expect(component.isEditorDirty).toBeFalse();
});
it('should not be dirty when file is opened and unchanged', () => {
component.showFileEditor = true;
component.originalFileContent = 'hello';
component.fileContent = 'hello';
component.originalFileName = 'a.txt';
component.newFileName = 'a.txt';
expect(component.isEditorDirty).toBeFalse();
});
it('should be dirty when file content is changed', () => {
component.showFileEditor = true;
component.originalFileContent = 'hello';
component.fileContent = 'hello world';
component.originalFileName = 'a.txt';
component.newFileName = 'a.txt';
expect(component.isEditorDirty).toBeTrue();
});
it('should be dirty when file name is changed', () => {
component.showFileEditor = true;
component.originalFileContent = 'hello';
component.fileContent = 'hello';
component.originalFileName = 'a.txt';
component.newFileName = 'b.txt';
expect(component.isEditorDirty).toBeTrue();
});
it('should prompt user on requestCloseFileEditor when dirty', () => {
component.showFileEditor = true;
component.originalFileContent = 'hello';
component.fileContent = 'hello world';
component.originalFileName = 'a.txt';
component.newFileName = 'a.txt';
component.requestCloseFileEditor();
expect(confirmMock.confirm).toHaveBeenCalled();
});
it('should not prompt user on requestCloseFileEditor when not dirty', () => {
component.showFileEditor = true;
component.originalFileContent = 'hello';
component.fileContent = 'hello';
component.originalFileName = 'a.txt';
component.newFileName = 'a.txt';
component.requestCloseFileEditor();
expect(confirmMock.confirm).not.toHaveBeenCalled();
expect(component.showFileEditor).toBeFalse();
});
it('should reset state and close editor upon successful save', async () => {
component.showFileEditor = true;
component.editingFile = {
path: '/a.txt',
name: 'a.txt',
size: 0,
mimeType: 'text/plain',
};
component.newFileName = 'a.txt';
component.fileContent = 'hello world';
component.originalFileContent = 'hello';
component.originalFileName = 'a.txt';
component.currentFolder = { path: '/root', name: 'root' } as any;
cloudMock.uploadFile.and.returnValue(of({} as any));
await component.saveFile();
expect(component.showFileEditor).toBeFalse();
expect(component.isEditorDirty).toBeFalse();
});
it('should return false in canDeactivate and prompt user when dirty', async () => {
component.showFileEditor = true;
component.originalFileContent = 'hello';
component.fileContent = 'hello world';
component.originalFileName = 'a.txt';
component.newFileName = 'a.txt';
confirmMock.confirm.and.callFake((config) => {
if (config.reject) config.reject();
return confirmMock;
});
const result = await component.canDeactivate();
expect(result).toBeFalse();
expect(confirmMock.confirm).toHaveBeenCalled();
});
it('should return true in canDeactivate and close editor when accepted', async () => {
component.showFileEditor = true;
component.originalFileContent = 'hello';
component.fileContent = 'hello world';
component.originalFileName = 'a.txt';
component.newFileName = 'a.txt';
confirmMock.confirm.and.callFake((config) => {
if (config.accept) config.accept();
return confirmMock;
});
const result = await component.canDeactivate();
expect(result).toBeTrue();
expect(confirmMock.confirm).toHaveBeenCalled();
expect(component.showFileEditor).toBeFalse();
});
describe('Markdown Workspace Mode', () => {
beforeEach(() => {
jasmine.clock().install();
});
afterEach(() => {
jasmine.clock().uninstall();
});
it('should generate document outline from content headings', () => {
component.fileContent =
'# Heading 1\nSome text\n## Heading 2\n### Heading 3';
component.updateOutline();
expect(component.outline.length).toBe(3);
expect(component.outline[0]).toEqual({ text: 'Heading 1', level: 1 });
expect(component.outline[1]).toEqual({ text: 'Heading 2', level: 2 });
expect(component.outline[2]).toEqual({ text: 'Heading 3', level: 3 });
});
it('should parse wikilinks to anchor tags during preview update', () => {
component.newFileName = 'doc.md';
component.fileContent =
'Check out [[another-doc]] and [[my folder/notes]].';
component.updatePreview();
const parsedHtml = component.previewHtml.toString();
expect(parsedHtml).toContain('data-target="another-doc"');
expect(parsedHtml).toContain('data-target="my folder/notes"');
});
it('should resolve wikilinks correctly if matching file exists', () => {
component.entries = [
{
kind: 'file',
name: 'target-note.md',
path: '/root/target-note.md',
size: 0,
mimeType: 'text/markdown',
} as any,
];
const fileRef = component.resolveWikilink('target-note');
expect(fileRef).not.toBeNull();
expect(fileRef?.name).toBe('target-note.md');
expect(fileRef?.path).toBe('/root/target-note.md');
const missingFileRef = component.resolveWikilink('non-existent');
expect(missingFileRef).toBeNull();
});
it('should handle click on wikilink and open matched file', () => {
spyOn(component, 'editFile');
component.entries = [
{
kind: 'file',
name: 'target-note.md',
path: '/root/target-note.md',
size: 0,
mimeType: 'text/markdown',
} as any,
];
const mockEvent = {
target: {
classList: {
contains: (cls: string) => cls === 'wikilink',
},
getAttribute: (attr: string) =>
attr === 'data-target' ? 'target-note' : null,
},
preventDefault: jasmine.createSpy('preventDefault'),
} as any;
component.handlePreviewClick(mockEvent);
expect(mockEvent.preventDefault).toHaveBeenCalled();
expect(component.editFile).toHaveBeenCalledWith({
path: '/root/target-note.md',
name: 'target-note.md',
size: 0,
mimeType: '',
});
});
it('should transition saveStatus through unsaved -> saving -> saved during autosave', async () => {
component.showFileEditor = true;
component.newFileName = 'note.md';
component.fileContent = 'new markdown';
component.originalFileContent = '';
component.originalFileName = 'note.md';
component.currentFolder = { path: '/root', name: 'root' } as any;
cloudMock.uploadFile.and.returnValue(of({} as any));
component.onContentChange();
expect(component.saveStatus).toBe('unsaved');
jasmine.clock().tick(2000);
// Wait for async autosave Promise to resolve
await component.autosaveFile();
expect(component.saveStatus).toBe('saved');
expect(component.originalFileContent).toBe('new markdown');
expect(component.isEditorDirty).toBeFalse();
});
});
});
describe('CloudComponent Secure Send Flow', () => {
let component: CloudComponent;
let fixture: ComponentFixture<CloudComponent>;
let cloudServiceSpy: jasmine.SpyObj<CloudService>;
let toastSpy: jasmine.SpyObj<UiToastService>;
beforeEach(async () => {
cloudServiceSpy = jasmine.createSpyObj('CloudService', [
'getRootFolder',
'getFolderByPath',
'getFolderContent',
'createSecureSendLink',
'listSecureSendLinks',
'revokeSecureSendLink',
'getStorageQuota',
]);
cloudServiceSpy.getRootFolder.and.returnValue(
of({ id: 'root', name: 'Root', path: '/' } as any),
);
cloudServiceSpy.getFolderContent.and.returnValue(
of({ content: [], totalElements: 0, totalPages: 0, page: 0 } as any),
);
cloudServiceSpy.getStorageQuota.and.returnValue(
of({ usedBytes: 500, totalBytes: 1000 }),
);
toastSpy = jasmine.createSpyObj('UiToastService', [
'success',
'error',
'info',
'warn',
]);
await TestBed.configureTestingModule({
imports: [
CloudComponent,
HttpClientTestingModule,
RouterTestingModule,
NoopAnimationsModule,
],
providers: [
{ provide: CloudService, useValue: cloudServiceSpy },
{ provide: UiToastService, useValue: toastSpy },
],
}).compileComponents();
fixture = TestBed.createComponent(CloudComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should open create share link dialog for a file', () => {
component.openCreateShareDialog('/file.txt', 'file.txt');
expect(component.selectedFileForShare).toEqual({
path: '/file.txt',
name: 'file.txt',
});
expect(component.showCreateShareDialog).toBeTrue();
expect(component.shareExpiryMinutes).toBe(1440);
});
it('should create a secure send link and open generated URL dialog on success', () => {
component.selectedFileForShare = { path: '/doc.pdf', name: 'doc.pdf' };
component.shareExpiryMinutes = 60;
component.sharePassword = 'pass';
const mockLink: SecureSendLinkDto = {
id: 's1',
filePath: '/doc.pdf',
fileName: 'doc.pdf',
shareUrl: 'http://localhost/share/s1',
expiresAt: '2026-07-21T00:00:00Z',
createdAt: '2026-07-20T00:00:00Z',
};
cloudServiceSpy.createSecureSendLink.and.returnValue(of(mockLink));
component.submitCreateShareLink();
expect(cloudServiceSpy.createSecureSendLink).toHaveBeenCalledWith(
'/doc.pdf',
60,
'pass',
);
expect(component.createdShareUrl).toBe('http://localhost/share/s1');
expect(component.showCreateShareDialog).toBeFalse();
expect(component.showGeneratedLinkDialog).toBeTrue();
expect(toastSpy.success).toHaveBeenCalledWith(
'Share link created',
'Link for "doc.pdf" created successfully.',
);
});
it('should handle rate limit error (HTTP 429) when creating share link', () => {
component.selectedFileForShare = { path: '/doc.pdf', name: 'doc.pdf' };
cloudServiceSpy.createSecureSendLink.and.returnValue(
throwError(() => ({ status: 429, message: 'Too Many Requests' })),
);
component.submitCreateShareLink();
expect(toastSpy.error).toHaveBeenCalledWith(
'Rate limit reached',
'Too many share links created. Please wait before trying again.',
);
});
it('should load active share links in dialog', () => {
const mockLinks: SecureSendLinkDto[] = [
{
id: 'link1',
filePath: '/a.txt',
fileName: 'a.txt',
expiresAt: '2026-07-25T00:00:00Z',
createdAt: '2026-07-20T00:00:00Z',
},
];
cloudServiceSpy.listSecureSendLinks.and.returnValue(of(mockLinks));
component.openSharedLinksDialog();
expect(component.showSharedLinksDialog).toBeTrue();
expect(component.sharedLinks).toEqual(mockLinks);
});
it('should revoke a share link and update UI state', () => {
const link: SecureSendLinkDto = {
id: 'link1',
filePath: '/a.txt',
fileName: 'a.txt',
expiresAt: '2026-07-25T00:00:00Z',
createdAt: '2026-07-20T00:00:00Z',
isRevoked: false,
};
cloudServiceSpy.revokeSecureSendLink.and.returnValue(of(void 0));
component.revokeShareLink(link);
expect(cloudServiceSpy.revokeSecureSendLink).toHaveBeenCalledWith('link1');
expect(link.isRevoked).toBeTrue();
expect(toastSpy.success).toHaveBeenCalledWith(
'Link revoked',
'Share link for "a.txt" was revoked.',
);
});
});
/**
* The unsaved-changes guard on the Cloud file editor: every exit path (Cancel,
* the dialog dismiss, and a full-page leave) must confirm before discarding
* edits, and a clean editor must close without a prompt.
*/
describe('CloudComponent unsaved-edit guard', () => {
let component: CloudComponent;
let confirmMock: jasmine.SpyObj<{ confirm: (config: unknown) => void }>;
beforeEach(() => {
confirmMock = jasmine.createSpyObj('ConfirmationService', ['confirm']);
component = new CloudComponent(
{} as never,
confirmMock as never,
{} as never,
{} as never,
{} as never,
);
});
// Open the editor on a file whose loaded state is not yet dirty.
function openEditor(content: string, fileName = 'note.txt'): void {
component.showFileEditor = true;
component.newFileName = fileName;
component.originalFileName = fileName;
component.fileContent = content;
component.originalFileContent = content;
}
function acceptLastConfirm(): void {
const config = confirmMock.confirm.calls.mostRecent().args[0] as {
accept: () => void;
};
config.accept();
}
it('closes without asking when the editor has no unsaved edits', () => {
openEditor('hello');
component.requestCloseFileEditor();
expect(confirmMock.confirm).not.toHaveBeenCalled();
expect(component.showFileEditor).toBeFalse();
});
it('asks before discarding, and only closes once Discard is confirmed', () => {
openEditor('hello');
component.fileContent = 'hello world'; // dirty
component.requestCloseFileEditor();
expect(confirmMock.confirm).toHaveBeenCalledTimes(1);
expect(component.showFileEditor).toBeTrue(); // stays open until confirmed
acceptLastConfirm();
expect(component.showFileEditor).toBeFalse();
expect(component.fileContent).toBe(''); // editor state fully reset
});
it('asks before discarding when only the file name changed', () => {
openEditor('hello', 'old.txt');
component.newFileName = 'new.txt';
component.requestCloseFileEditor();
expect(confirmMock.confirm).toHaveBeenCalledTimes(1);
expect(component.showFileEditor).toBeTrue();
});
it('reverses a dialog dismiss and confirms when there are unsaved edits', () => {
openEditor('hello');
component.fileContent = 'changed';
component.showFileEditor = false; // the dismiss already flipped visible off
component.onFileEditorHide();
expect(component.showFileEditor).toBeTrue(); // reopened
expect(confirmMock.confirm).toHaveBeenCalledTimes(1);
});
it('lets a clean dialog dismiss close with no prompt', () => {
openEditor('hello');
component.showFileEditor = false;
component.onFileEditorHide();
expect(confirmMock.confirm).not.toHaveBeenCalled();
expect(component.showFileEditor).toBeFalse();
});
it('blocks a full-page leave only while there are unsaved edits', () => {
openEditor('hello');
const clean = {
preventDefault: jasmine.createSpy('preventDefault'),
returnValue: '',
} as unknown as BeforeUnloadEvent;
component.warnBeforeUnload(clean);
expect(clean.preventDefault).not.toHaveBeenCalled();
component.fileContent = 'changed';
const dirty = {
preventDefault: jasmine.createSpy('preventDefault'),
returnValue: '',
} as unknown as BeforeUnloadEvent;
component.warnBeforeUnload(dirty);
expect(dirty.preventDefault).toHaveBeenCalled();
});
});
describe('CloudComponent Storage Quota', () => {
let component: CloudComponent;
let fixture: ComponentFixture<CloudComponent>;
let cloudServiceSpy: jasmine.SpyObj<CloudService>;
let toastSpy: jasmine.SpyObj<UiToastService>;
beforeEach(async () => {
cloudServiceSpy = jasmine.createSpyObj('CloudService', [
'getRootFolder',
'getFolderContent',
'getStorageQuota',
'uploadFile',
'deleteFile',
]);
toastSpy = jasmine.createSpyObj('UiToastService', [
'success',
'error',
'info',
]);
cloudServiceSpy.getRootFolder.and.returnValue(
of({
name: 'Root',
path: '/',
folders: [],
files: [],
lastModifiedAt: 0,
} as any),
);
cloudServiceSpy.getFolderContent.and.returnValue(
of({
content: [],
totalElements: 0,
totalPages: 1,
pageNumber: 0,
pageSize: 50,
} as any),
);
cloudServiceSpy.getStorageQuota.and.returnValue(
of({ usedBytes: 500, totalBytes: 1000 }),
);
await TestBed.configureTestingModule({
imports: [
CloudComponent,
HttpClientTestingModule,
RouterTestingModule,
NoopAnimationsModule,
],
providers: [
{ provide: CloudService, useValue: cloudServiceSpy },
{ provide: UiToastService, useValue: toastSpy },
{
provide: Router,
useValue: { navigate: jasmine.createSpy('navigate') },
},
ConfirmationService,
],
}).compileComponents();
fixture = TestBed.createComponent(CloudComponent);
component = fixture.componentInstance;
});
it('should initialize and load storage quota', () => {
fixture.detectChanges();
expect(component.storageQuota).toEqual({
usedBytes: 500,
totalBytes: 1000,
});
expect(component.quotaPercentage).toBe(50);
expect(component.usedSpaceLabel).toBe('500 Bytes');
expect(component.totalSpaceLabel).toBe('1000 Bytes');
expect(component.quotaStatusClass).toBe('quota-normal');
});
it('should set warning and danger status classes based on quota percentage', () => {
component.storageQuota = { usedBytes: 800, totalBytes: 1000 };
expect(component.quotaPercentage).toBe(80);
expect(component.quotaStatusClass).toBe('quota-warning');
component.storageQuota = { usedBytes: 950, totalBytes: 1000 };
expect(component.quotaPercentage).toBe(95);
expect(component.quotaStatusClass).toBe('quota-danger');
});
it('should detect quota-exceeded errors correctly', () => {
expect(component.isQuotaExceededError({ status: 413 })).toBeTrue();
expect(component.isQuotaExceededError({ status: 507 })).toBeTrue();
expect(
component.isQuotaExceededError({
error: { message: 'Storage quota exceeded' },
}),
).toBeTrue();
expect(
component.isQuotaExceededError({
message: 'User is out of space',
}),
).toBeTrue();
expect(
component.isQuotaExceededError({
status: 400,
message: 'Invalid format',
}),
).toBeFalse();
});
it('should hide storage quota widget when storage quota endpoint fails', () => {
cloudServiceSpy.getStorageQuota.and.returnValue(
throwError(() => new Error('Quota endpoint unavailable')),
);
component.loadStorageQuota();
expect(component.storageQuota).toBeUndefined();
});
});