-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathsectionPicker_tests.tsx
More file actions
956 lines (805 loc) · 43.6 KB
/
sectionPicker_tests.tsx
File metadata and controls
956 lines (805 loc) · 43.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
import * as sinon from "sinon";
import {Clipper} from "../../../scripts/clipperUI/frontEndGlobals";
import {Status} from "../../../scripts/clipperUI/status";
import {OneNoteApiUtils} from "../../../scripts/clipperUI/oneNoteApiUtils";
import {SectionPicker, SectionPickerClass, SectionPickerState} from "../../../scripts/clipperUI/components/sectionPicker";
import {ClipperStorageKeys} from "../../../scripts/storage/clipperStorageKeys";
import {MithrilUtils} from "../../mithrilUtils";
import {MockProps} from "../../mockProps";
import {TestModule} from "../../testModule";
module TestConstants {
export module Ids {
export var sectionLocationContainer = "sectionLocationContainer";
export var sectionPickerContainer = "sectionPickerContainer";
}
export var defaultUserInfoAsJsonString = JSON.stringify({
emailAddress: "mockEmail@hotmail.com",
fullName: "Mock Johnson",
accessToken: "mockToken",
accessTokenExpiration: 3000
});
}
type StoredSection = {
section: OneNoteApi.Section,
path: string,
parentId: string
};
// Mock out the Clipper.Storage functionality
let mockStorage: { [key: string]: string } = {};
Clipper.getStoredValue = (key: string, callback: (value: string) => void) => {
callback(mockStorage[key]);
};
Clipper.storeValue = (key: string, value: string) => {
mockStorage[key] = value;
};
function initializeClipperStorage(notebooks: string, curSection: string, userInfo?: string) {
mockStorage = { };
Clipper.storeValue(ClipperStorageKeys.cachedNotebooks, notebooks);
Clipper.storeValue(ClipperStorageKeys.currentSelectedSection, curSection);
Clipper.storeValue(ClipperStorageKeys.userInformation, userInfo);
}
function createNotebook(id: string, isDefault?: boolean, sectionGroups?: OneNoteApi.SectionGroup[], sections?: OneNoteApi.Section[]): OneNoteApi.Notebook {
return {
name: id.toUpperCase(),
isDefault: isDefault,
userRole: undefined,
isShared: true,
links: undefined,
id: id.toLowerCase(),
self: undefined,
createdTime: undefined,
lastModifiedTime: undefined,
createdBy: undefined,
lastModifiedBy: undefined,
sectionsUrl: undefined,
sectionGroupsUrl: undefined,
sections: sections,
sectionGroups: sectionGroups
};
};
function createSectionGroup(id: string, sectionGroups?: OneNoteApi.SectionGroup[], sections?: OneNoteApi.Section[]): OneNoteApi.SectionGroup {
return {
name: id.toUpperCase(),
id: id.toLowerCase(),
self: undefined,
createdTime: undefined,
lastModifiedTime: undefined,
createdBy: undefined,
lastModifiedBy: undefined,
sectionsUrl: undefined,
sectionGroupsUrl: undefined,
sections: sections,
sectionGroups: sectionGroups
};
};
function createSection(id: string, isDefault?: boolean): OneNoteApi.Section {
return {
name: id.toUpperCase(),
isDefault: isDefault,
parentNotebook: undefined,
id: id.toLowerCase(),
self: undefined,
createdTime: undefined,
lastModifiedTime: undefined,
createdBy: undefined,
lastModifiedBy: undefined,
pagesUrl: undefined,
pages: undefined
};
};
export class SectionPickerTests extends TestModule {
private defaultComponent;
private mockClipperState = MockProps.getMockClipperState();
protected module() {
return "sectionPicker";
}
protected beforeEach() {
this.defaultComponent = <SectionPicker
onPopupToggle={() => {}}
clipperState={this.mockClipperState} />;
}
protected tests() {
test("fetchCachedNotebookAndSectionInfoAsState should return the cached notebooks, cached current section, and the succeed status if cached information is found", () => {
let clipperState = MockProps.getMockClipperState();
let mockNotebooks = MockProps.getMockNotebooks();
let mockSection = {
section: mockNotebooks[0].sections[0],
path: "A > B > C",
parentId: mockNotebooks[0].id
};
initializeClipperStorage(JSON.stringify(mockNotebooks), JSON.stringify(mockSection));
let component = <SectionPicker
onPopupToggle={() => {}}
clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(component);
controllerInstance.fetchCachedNotebookAndSectionInfoAsState((response: SectionPickerState) => {
strictEqual(JSON.stringify(response), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: mockSection }),
"The cached information should be returned as SectionPickerState");
});
});
test("fetchCachedNotebookAndSectionInfoAsState should return undefined if no cached information is found", () => {
let clipperState = MockProps.getMockClipperState();
initializeClipperStorage(undefined, undefined);
let component = <SectionPicker
onPopupToggle={() => {}}
clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(component);
controllerInstance.fetchCachedNotebookAndSectionInfoAsState((response: SectionPickerState) => {
strictEqual(response, undefined,
"The undefined notebooks and section information should be returned as SectionPickerState");
});
});
test("fetchCachedNotebookAndSectionInfoAsState should return the cached notebooks, undefined section, and the succeed status if no cached section is found", () => {
let clipperState = MockProps.getMockClipperState();
let mockNotebooks = MockProps.getMockNotebooks();
initializeClipperStorage(JSON.stringify(mockNotebooks), undefined);
let component = <SectionPicker
onPopupToggle={() => {}}
clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(component);
controllerInstance.fetchCachedNotebookAndSectionInfoAsState((response: SectionPickerState) => {
strictEqual(JSON.stringify(response), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: undefined }),
"The cached information should be returned as SectionPickerState");
});
});
test("fetchCachedNotebookAndSectionInfoAsState should return undefined when no notebooks are found, even if section information is found", () => {
let clipperState = MockProps.getMockClipperState();
let mockSection = {
section: MockProps.getMockNotebooks()[0].sections[0],
path: "A > B > C",
parentId: MockProps.getMockNotebooks()[0].id
};
initializeClipperStorage(undefined, JSON.stringify(mockSection));
let component = <SectionPicker
onPopupToggle={() => {}}
clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(component);
controllerInstance.fetchCachedNotebookAndSectionInfoAsState((response: SectionPickerState) => {
strictEqual(response, undefined,
"The cached information should be returned as SectionPickerState");
});
});
test("convertNotebookListToState should return the notebook list, success status, and default section in the general case", () => {
let section = createSection("S", true);
let sectionGroup2 = createSectionGroup("SG2", [], [section]);
let sectionGroup1 = createSectionGroup("SG1", [sectionGroup2], []);
let notebook = createNotebook("N", true, [sectionGroup1], []);
let notebooks = [notebook];
let actual = SectionPickerClass.convertNotebookListToState(notebooks);
strictEqual(actual.notebooks, notebooks, "The notebooks property is correct");
strictEqual(actual.status, Status.Succeeded, "The status property is correct");
deepEqual(actual.curSection, { path: "N > SG1 > SG2 > S", section: section },
"The curSection property is correct");
});
test("convertNotebookListToState should return the notebook list, success status, and undefined default section in case where there is no default section", () => {
let sectionGroup2 = createSectionGroup("SG2", [], []);
let sectionGroup1 = createSectionGroup("SG1", [sectionGroup2], []);
let notebook = createNotebook("N", true, [sectionGroup1], []);
let notebooks = [notebook];
let actual = SectionPickerClass.convertNotebookListToState(notebooks);
strictEqual(actual.notebooks, notebooks, "The notebooks property is correct");
strictEqual(actual.status, Status.Succeeded, "The status property is correct");
strictEqual(actual.curSection, undefined, "The curSection property is undefined");
});
test("convertNotebookListToState should return the notebook list, success status, and undefined default section in case where there is only one empty notebook", () => {
let notebook = createNotebook("N", true, [], []);
let notebooks = [notebook];
let actual = SectionPickerClass.convertNotebookListToState(notebooks);
strictEqual(actual.notebooks, notebooks, "The notebooks property is correct");
strictEqual(actual.status, Status.Succeeded, "The status property is correct");
strictEqual(actual.curSection, undefined, "The curSection property is undefined");
});
test("convertNotebookListToState should return the undefined notebook list, success status, and undefined default section if the input is undefined", () => {
let actual = SectionPickerClass.convertNotebookListToState(undefined);
strictEqual(actual.notebooks, undefined, "The notebooks property is undefined");
strictEqual(actual.status, Status.Succeeded, "The status property is correct");
strictEqual(actual.curSection, undefined, "The curSection property is undefined");
});
test("convertNotebookListToState should return the empty notebook list, success status, and undefined default section if the input is undefined", () => {
let actual = SectionPickerClass.convertNotebookListToState([]);
strictEqual(actual.notebooks.length, 0, "The notebooks property is the empty list");
strictEqual(actual.status, Status.Succeeded, "The status property is correct");
strictEqual(actual.curSection, undefined, "The curSection property is undefined");
});
test("formatSectionInfoForStorage should return a ' > ' delimited name path and the last element in the general case", () => {
let section = createSection("4");
let actual = SectionPickerClass.formatSectionInfoForStorage([
createNotebook("1"),
createSectionGroup("2"),
createSectionGroup("3"),
section
]);
deepEqual(actual, { path: "1 > 2 > 3 > 4", section: section },
"The section info should be formatted correctly");
});
test("formatSectionInfoForStorage should return a ' > ' delimited name path and the last element if there are no section groups", () => {
let section = createSection("2");
let actual = SectionPickerClass.formatSectionInfoForStorage([
createNotebook("1"),
section
]);
deepEqual(actual, { path: "1 > 2", section: section },
"The section info should be formatted correctly");
});
test("formatSectionInfoForStorage should return undefined if the list that is passed in is undefined", () => {
let actual = SectionPickerClass.formatSectionInfoForStorage(undefined);
strictEqual(actual, undefined, "The section info should be formatted correctly");
});
test("formatSectionInfoForStorage should return undefined if the list that is passed in is empty", () => {
let actual = SectionPickerClass.formatSectionInfoForStorage([]);
strictEqual(actual, undefined, "The section info should be formatted correctly");
});
}
}
export class SectionPickerSinonTests extends TestModule {
private defaultComponent;
private mockClipperState = MockProps.getMockClipperState();
private server: sinon.SinonFakeServer;
protected module() {
return "sectionPicker-sinon";
}
protected beforeEach() {
this.defaultComponent = <SectionPicker
onPopupToggle={() => {}}
clipperState={this.mockClipperState} />;
this.server = sinon.fakeServer.create();
this.server.respondImmediately = true;
}
protected afterEach() {
this.server.restore();
}
protected tests() {
test("retrieveAndUpdateNotebookAndSectionSelection should update states correctly when there's notebook and curSection information found in storage," +
"the user does not make a new selection, and then information is found on the server. Also the notebooks are the same in storage and on the server, " +
"and the current section in storage is the same as the default section in the server's notebook list", (assert: QUnitAssert) => {
let done = assert.async();
let clipperState = MockProps.getMockClipperState();
// Set up the storage mock
let mockNotebooks = MockProps.getMockNotebooks();
let mockSection = {
section: mockNotebooks[0].sections[0],
path: "Clipper Test > Full Page",
parentId: mockNotebooks[0].id
};
initializeClipperStorage(JSON.stringify(mockNotebooks), JSON.stringify(mockSection), TestConstants.defaultUserInfoAsJsonString);
// After retrieving fresh notebooks, the storage should be updated with the fresh notebooks (although it's the same in this case)
let freshNotebooks = MockProps.getMockNotebooks();
let responseJson = {
"@odata.context": "https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks",
value: freshNotebooks
};
this.server.respondWith([200, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]);
let component = <SectionPicker onPopupToggle={() => {}} clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(component);
strictEqual(JSON.stringify(controllerInstance.state), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: mockSection }),
"After the component is mounted, the state should be updated to reflect the notebooks and section found in storage");
controllerInstance.retrieveAndUpdateNotebookAndSectionSelection().then((response) => {
Clipper.getStoredValue(ClipperStorageKeys.cachedNotebooks, (notebooks) => {
Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection) => {
strictEqual(notebooks, JSON.stringify(freshNotebooks),
"After fresh notebooks have been retrieved, the storage should be updated with them. In this case, nothing should have changed.");
strictEqual(curSection, JSON.stringify(mockSection),
"The current selected section in storage should not have changed");
strictEqual(JSON.stringify(controllerInstance.state.notebooks), JSON.stringify(freshNotebooks),
"The state should always be updated with the fresh notebooks once it has been retrieved");
strictEqual(JSON.stringify(controllerInstance.state.curSection), JSON.stringify(mockSection),
"Since curSection was found in storage, and the user did not make an action to select another section, it should remain the same in state");
strictEqual(controllerInstance.state.status, Status.Succeeded, "The status should be Succeeded");
done();
});
});
}, (error) => {
ok(false, "reject should not be called");
});
});
test("retrieveAndUpdateNotebookAndSectionSelection should update states correctly when there's notebook and curSection information found in storage," +
"the user does not make a new selection, and then information is found on the server. The notebooks on the server is not the same as the ones in storage, " +
"and the current section in storage is the same as the default section in the server's notebook list", (assert: QUnitAssert) => {
let done = assert.async();
let clipperState = MockProps.getMockClipperState();
// Set up the storage mock
let mockNotebooks = MockProps.getMockNotebooks();
let mockSection = {
section: mockNotebooks[0].sections[0],
path: "Clipper Test > Full Page",
parentId: mockNotebooks[0].id
};
initializeClipperStorage(JSON.stringify(mockNotebooks), JSON.stringify(mockSection), TestConstants.defaultUserInfoAsJsonString);
let component = <SectionPicker
onPopupToggle={() => {}}
clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(component);
strictEqual(JSON.stringify(controllerInstance.state), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: mockSection }),
"After the component is mounted, the state should be updated to reflect the notebooks and section found in storage");
// After retrieving fresh notebooks, the storage should be updated with the fresh notebooks
let freshNotebooks = MockProps.getMockNotebooks();
freshNotebooks.push(createNotebook("id", false, [], []));
let responseJson = {
"@odata.context": "https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks",
value: freshNotebooks
};
this.server.respondWith([200, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]);
controllerInstance.retrieveAndUpdateNotebookAndSectionSelection().then((response: SectionPickerState) => {
Clipper.getStoredValue(ClipperStorageKeys.cachedNotebooks, (notebooks) => {
Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection) => {
strictEqual(notebooks, JSON.stringify(freshNotebooks),
"After fresh notebooks have been retrieved, the storage should be updated with them. In this case, nothing should have changed.");
strictEqual(curSection, JSON.stringify(mockSection),
"The current selected section in storage should not have changed");
strictEqual(JSON.stringify(controllerInstance.state.notebooks), JSON.stringify(freshNotebooks),
"The state should always be updated with the fresh notebooks once it has been retrieved");
strictEqual(JSON.stringify(controllerInstance.state.curSection), JSON.stringify(mockSection),
"Since curSection was found in storage, and the user did not make an action to select another section, it should remain the same in state");
strictEqual(controllerInstance.state.status, Status.Succeeded,
"The status should be Succeeded");
done();
});
});
}, (error) => {
ok(false, "reject should not be called");
});
});
test("retrieveAndUpdateNotebookAndSectionSelection should update states correctly when there's notebook, but no curSection information found in storage," +
"the user does not make a selection, and then information is found on the server. The notebooks on the server is the same as the ones in storage, " +
"and the current section in storage is still undefined by the time the fresh notebooks have been retrieved", (assert: QUnitAssert) => {
let done = assert.async();
let clipperState = MockProps.getMockClipperState();
// Set up the storage mock
let mockNotebooks = MockProps.getMockNotebooks();
initializeClipperStorage(JSON.stringify(mockNotebooks), undefined, TestConstants.defaultUserInfoAsJsonString);
let component = <SectionPicker
onPopupToggle={() => {}}
clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(component);
strictEqual(JSON.stringify(controllerInstance.state), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: undefined }),
"After the component is mounted, the state should be updated to reflect the notebooks and section found in storage");
// After retrieving fresh notebooks, the storage should be updated with the fresh notebooks (although it's the same in this case)
let freshNotebooks = MockProps.getMockNotebooks();
freshNotebooks.push(createNotebook("id", false, [], []));
let responseJson = {
"@odata.context": "https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks",
value: freshNotebooks
};
this.server.respondWith([200, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]);
// This is the default section in the mock notebooks, and this should be found in storage and state after fresh notebooks are retrieved
let defaultSection = {
path: "Clipper Test > Full Page",
section: mockNotebooks[0].sections[0]
};
controllerInstance.retrieveAndUpdateNotebookAndSectionSelection().then((response: SectionPickerState) => {
Clipper.getStoredValue(ClipperStorageKeys.cachedNotebooks, (notebooks) => {
Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection) => {
strictEqual(notebooks, JSON.stringify(freshNotebooks),
"After fresh notebooks have been retrieved, the storage should be updated with them. In this case, nothing should have changed.");
strictEqual(curSection, JSON.stringify(defaultSection),
"The current selected section in storage should have been updated with the default section since it was undefined before");
strictEqual(JSON.stringify(controllerInstance.state.notebooks), JSON.stringify(freshNotebooks),
"The state should always be updated with the fresh notebooks once it has been retrieved");
strictEqual(JSON.stringify(controllerInstance.state.curSection), JSON.stringify(defaultSection),
"Since curSection was not found in storage, and the user did not make an action to select another section, it should be updated in state");
strictEqual(controllerInstance.state.status, Status.Succeeded,
"The status should be Succeeded");
done();
});
});
}, (error) => {
ok(false, "reject should not be called");
});
});
test("retrieveAndUpdateNotebookAndSectionSelection should update states correctly when there's notebook, but no curSection information found in storage," +
"the user makes a new section selection, and then information is found on the server. The notebooks on the server is the same as the ones in storage, " +
"and the current section in storage is still undefined by the time the fresh notebooks have been retrieved", (assert: QUnitAssert) => {
let done = assert.async();
let clipperState = MockProps.getMockClipperState();
// Set up the storage mock
let mockNotebooks = MockProps.getMockNotebooks();
initializeClipperStorage(JSON.stringify(mockNotebooks), undefined, TestConstants.defaultUserInfoAsJsonString);
let component = <SectionPicker
onPopupToggle={() => {}}
clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(component);
strictEqual(JSON.stringify(controllerInstance.state), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: undefined }),
"After the component is mounted, the state should be updated to reflect the notebooks and section found in storage");
// The user now clicks on a section (second section of second notebook)
MithrilUtils.simulateAction(() => {
document.getElementById(TestConstants.Ids.sectionLocationContainer).click();
});
let sectionPicker = document.getElementById(TestConstants.Ids.sectionPickerContainer).firstElementChild;
let second = sectionPicker.childNodes[1];
let secondNotebook = second.childNodes[0] as HTMLElement;
let secondSections = second.childNodes[1] as HTMLElement;
MithrilUtils.simulateAction(() => {
secondNotebook.click();
});
let newSelectedSection = secondSections.childNodes[1] as HTMLElement;
MithrilUtils.simulateAction(() => {
// The clickable element is actually the first childNode
(newSelectedSection.childNodes[0] as HTMLElement).click();
});
// This corresponds to the second section of the second notebook in the mock notebooks
let selectedSection = {
section: mockNotebooks[1].sections[1],
path: "Clipper Test 2 > Section Y",
parentId: "a-bc!d"
};
Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection1) => {
strictEqual(curSection1, JSON.stringify(selectedSection),
"The current selected section in storage should have been updated with the selected section");
strictEqual(JSON.stringify(controllerInstance.state.curSection), JSON.stringify(selectedSection),
"The current selected section in state should have been updated with the selected section");
// After retrieving fresh notebooks, the storage should be updated with the fresh notebooks (although it's the same in this case)
let freshNotebooks = MockProps.getMockNotebooks();
freshNotebooks.push(createNotebook("id", false, [], []));
let responseJson = {
"@odata.context": "https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks",
value: freshNotebooks
};
this.server.respondWith([200, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]);
controllerInstance.retrieveAndUpdateNotebookAndSectionSelection().then((response: SectionPickerState) => {
Clipper.getStoredValue(ClipperStorageKeys.cachedNotebooks, (notebooks) => {
Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection2) => {
strictEqual(notebooks, JSON.stringify(freshNotebooks),
"After fresh notebooks have been retrieved, the storage should be updated with them. In this case, nothing should have changed.");
strictEqual(curSection2, JSON.stringify(selectedSection),
"The current selected section in storage should still be the selected section");
strictEqual(JSON.stringify(controllerInstance.state.notebooks), JSON.stringify(freshNotebooks),
"The state should always be updated with the fresh notebooks once it has been retrieved");
strictEqual(JSON.stringify(controllerInstance.state.curSection), JSON.stringify(selectedSection),
"The current selected section in state should still be the selected section");
strictEqual(controllerInstance.state.status, Status.Succeeded,
"The status should be Succeeded");
done();
});
});
}, (error) => {
ok(false, "reject should not be called");
});
});
});
test("retrieveAndUpdateNotebookAndSectionSelection should update states correctly when there's notebook and curSection information found in storage," +
" and then information is found on the server, but that selected section no longer exists.", (assert: QUnitAssert) => {
let done = assert.async();
let clipperState = MockProps.getMockClipperState();
// Set up the storage mock
let mockNotebooks = MockProps.getMockNotebooks();
let mockSection = {
section: mockNotebooks[0].sections[0],
path: "Clipper Test > Full Page",
parentId: mockNotebooks[0].id
};
initializeClipperStorage(JSON.stringify(mockNotebooks), JSON.stringify(mockSection), TestConstants.defaultUserInfoAsJsonString);
let component = <SectionPicker
onPopupToggle={() => {}}
clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(component);
strictEqual(JSON.stringify(controllerInstance.state), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: mockSection }),
"After the component is mounted, the state should be updated to reflect the notebooks and section found in storage");
// After retrieving fresh notebooks, the storage should be updated with the fresh notebooks (we deleted the cached currently selected section)
let freshNotebooks = MockProps.getMockNotebooks();
freshNotebooks[0].sections = [];
let responseJson = {
"@odata.context": "https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks",
value: freshNotebooks
};
this.server.respondWith([200, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]);
controllerInstance.retrieveAndUpdateNotebookAndSectionSelection().then((response: SectionPickerState) => {
Clipper.getStoredValue(ClipperStorageKeys.cachedNotebooks, (notebooks) => {
Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection2) => {
strictEqual(notebooks, JSON.stringify(freshNotebooks),
"After fresh notebooks have been retrieved, the storage should be updated with them.");
strictEqual(curSection2, undefined,
"The current selected section in storage should now be undefined as it no longer exists in the fresh notebooks");
strictEqual(JSON.stringify(controllerInstance.state.notebooks), JSON.stringify(freshNotebooks),
"The state should always be updated with the fresh notebooks once it has been retrieved");
strictEqual(controllerInstance.state.curSection, undefined,
"The current selected section in state should be undefined");
strictEqual(controllerInstance.state.status, Status.Succeeded,
"The status should be Succeeded");
done();
});
});
}, (error) => {
ok(false, "reject should not be called");
});
});
test("retrieveAndUpdateNotebookAndSectionSelection should update states correctly when there's notebook and curSection information found in storage," +
"the user does not make a new selection, and then notebooks is incorrectly returned as undefined or null from the server", (assert: QUnitAssert) => {
let done = assert.async();
let clipperState = MockProps.getMockClipperState();
// Set up the storage mock
let mockNotebooks = MockProps.getMockNotebooks();
let mockSection = {
section: mockNotebooks[0].sections[0],
path: "Clipper Test > Full Page",
parentId: mockNotebooks[0].id
};
initializeClipperStorage(JSON.stringify(mockNotebooks), JSON.stringify(mockSection), TestConstants.defaultUserInfoAsJsonString);
let component = <SectionPicker
onPopupToggle={() => {}}
clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(component);
strictEqual(JSON.stringify(controllerInstance.state), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: mockSection }),
"After the component is mounted, the state should be updated to reflect the notebooks and section found in storage");
// After retrieving fresh undefined notebooks, the storage should not be updated with the undefined value, but should still keep the old cached information
let responseJson = {
"@odata.context": "https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks",
value: undefined
};
this.server.respondWith([200, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]);
controllerInstance.retrieveAndUpdateNotebookAndSectionSelection().then((response: SectionPickerState) => {
ok(false, "resolve should not be called");
}, (error) => {
Clipper.getStoredValue(ClipperStorageKeys.cachedNotebooks,
(notebooks) => {
Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection,
(curSection) => {
strictEqual(notebooks,
JSON.stringify(mockNotebooks),
"After undefined notebooks have been retrieved, the storage should not be updated with them.");
strictEqual(curSection,
JSON.stringify(mockSection),
"The current selected section in storage should not have changed");
strictEqual(JSON.stringify(controllerInstance.state.notebooks),
JSON.stringify(mockNotebooks),
"The state should not be updated as retrieving fresh notebooks returned undefined");
strictEqual(JSON.stringify(controllerInstance.state.curSection),
JSON.stringify(mockSection),
"Since curSection was found in storage, and the user did not make an action to select another section, it should remain the same in state");
strictEqual(controllerInstance.state.status, Status.Failed, "The status should be Failed");
done();
});
});
});
});
test("retrieveAndUpdateNotebookAndSectionSelection should update states correctly when there's notebook and curSection information found in storage," +
"the user does not make a new selection, and the server returns an error status code", (assert: QUnitAssert) => {
let done = assert.async();
let clipperState = MockProps.getMockClipperState();
// Set up the storage mock
let mockNotebooks = MockProps.getMockNotebooks();
let mockSection = {
section: mockNotebooks[0].sections[0],
path: "Clipper Test > Full Page",
parentId: mockNotebooks[0].id
};
initializeClipperStorage(JSON.stringify(mockNotebooks), JSON.stringify(mockSection), TestConstants.defaultUserInfoAsJsonString);
let component = <SectionPicker
onPopupToggle={() => {}}
clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(component);
strictEqual(JSON.stringify(controllerInstance.state), JSON.stringify({ notebooks: mockNotebooks, status: Status.Succeeded, curSection: mockSection }),
"After the component is mounted, the state should be updated to reflect the notebooks and section found in storage");
// After retrieving fresh undefined notebooks, the storage should not be updated with the undefined value, but should still keep the old cached information
let responseJson = {};
this.server.respondWith([404, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]);
controllerInstance.retrieveAndUpdateNotebookAndSectionSelection().then((response: SectionPickerState) => {
ok(false, "resolve should not be called");
}, (error) => {
Clipper.getStoredValue(ClipperStorageKeys.cachedNotebooks, (notebooks) => {
Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection) => {
strictEqual(notebooks, JSON.stringify(mockNotebooks),
"After undefined notebooks have been retrieved, the storage should not be updated with them.");
strictEqual(curSection, JSON.stringify(mockSection),
"The current selected section in storage should not have changed");
strictEqual(JSON.stringify(controllerInstance.state.notebooks), JSON.stringify(mockNotebooks),
"The state should not be updated as retrieving fresh notebooks returned undefined");
strictEqual(JSON.stringify(controllerInstance.state.curSection), JSON.stringify(mockSection),
"Since curSection was found in storage, and the user did not make an action to select another section, it should remain the same in state");
strictEqual(controllerInstance.state.status, Status.Succeeded, "The status should be Succeeded since we have a fallback in storage");
done();
});
});
});
});
test("retrieveAndUpdateNotebookAndSectionSelection should update states correctly when there's no notebook and curSection information found in storage," +
"the user does not make a new selection, and the server returns an error status code, therefore there's no fallback notebooks", (assert: QUnitAssert) => {
let done = assert.async();
let clipperState = MockProps.getMockClipperState();
// Set up the storage mock
initializeClipperStorage(undefined, undefined, TestConstants.defaultUserInfoAsJsonString);
let component = <SectionPicker
onPopupToggle={() => {}}
clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(component);
strictEqual(JSON.stringify(controllerInstance.state), JSON.stringify({ notebooks: undefined, status: Status.NotStarted, curSection: undefined }),
"After the component is mounted, the state should be updated to reflect that notebooks and current section are not found in storage");
// After retrieving fresh undefined notebooks, the storage should not be updated with the undefined value, but should still keep the old cached information
let responseJson = {};
this.server.respondWith([404, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]);
controllerInstance.retrieveAndUpdateNotebookAndSectionSelection().then((response: SectionPickerState) => {
ok(false, "resolve should not be called");
}, (error) => {
Clipper.getStoredValue(ClipperStorageKeys.cachedNotebooks, (notebooks) => {
Clipper.getStoredValue(ClipperStorageKeys.currentSelectedSection, (curSection) => {
strictEqual(notebooks, undefined,
"After undefined notebooks have been retrieved, the storage notebook value should still be undefined");
strictEqual(curSection, undefined,
"After undefined notebooks have been retrieved, the storage section value should still be undefined as there was no default section present");
strictEqual(controllerInstance.state.notebooks, undefined,
"After undefined notebooks have been retrieved, the state notebook value should still be undefined");
strictEqual(controllerInstance.state.curSection, undefined,
"After undefined notebooks have been retrieved, the state section value should still be undefined as there was no default section present");
strictEqual(controllerInstance.state.status, Status.Failed, "The status should be Failed since getting fresh notebooks has failed and we don't have a fallback");
done();
});
});
});
});
test("fetchFreshNotebooks should parse out @odata.context from the raw 200 response and return the notebook object list and XHR in the resolve", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let notebooks = MockProps.getMockNotebooks();
let responseJson = {
"@odata.context": "https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks",
value: notebooks
};
this.server.respondWith([200, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]);
controllerInstance.fetchFreshNotebooks("sessionId").then((responsePackage: OneNoteApi.ResponsePackage<OneNoteApi.Notebook[]>) => {
strictEqual(JSON.stringify(responsePackage.parsedResponse), JSON.stringify(notebooks),
"The notebook list should be present in the response");
ok(!!responsePackage.request,
"The XHR must be present in the response");
}, (error) => {
ok(false, "reject should not be called");
}).then(() => {
done();
});
});
test("fetchFreshNotebooks should parse out @odata.context from the raw 201 response and return the notebook object list and XHR in the resolve", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let notebooks = MockProps.getMockNotebooks();
let responseJson = {
"@odata.context": "https://www.onenote.com/api/v1.0/$metadata#me/notes/notebooks",
value: notebooks
};
this.server.respondWith([201, { "Content-Type": "application/json" }, JSON.stringify(responseJson)]);
controllerInstance.fetchFreshNotebooks("sessionId").then((responsePackage: OneNoteApi.ResponsePackage<OneNoteApi.Notebook[]>) => {
strictEqual(JSON.stringify(responsePackage.parsedResponse), JSON.stringify(notebooks),
"The notebook list should be present in the response");
ok(!!responsePackage.request,
"The XHR must be present in the response");
}, (error) => {
ok(false, "reject should not be called");
}).then(() => {
done();
});
});
test("fetchFreshNotebooks should reject with the error object and a copy of the response if the status code is 4XX", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let responseJson = {
error: "Unexpected response status",
statusCode: 401,
responseHeaders: { "Content-Type": "application/json" }
};
let expected = {
error: responseJson.error,
statusCode: responseJson.statusCode,
responseHeaders: responseJson.responseHeaders,
response: JSON.stringify(responseJson),
timeout: 30000
};
this.server.respondWith([expected.statusCode, expected.responseHeaders, expected.response]);
controllerInstance.fetchFreshNotebooks("sessionId").then((responsePackage: OneNoteApi.ResponsePackage<OneNoteApi.Notebook[]>) => {
ok(false, "resolve should not be called");
}, (error) => {
deepEqual(error, expected, "The error object should be rejected");
strictEqual(controllerInstance.state.apiResponseCode, undefined);
}).then(() => {
done();
});
});
test("fetchFreshNotebooks should reject with the error object and an API response code if one is returned by the API", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let responseJson = {
error: {
code: "10008",
message: "The user's OneDrive, Group or Document Library contains more than 5000 items and cannot be queried using the API.",
"@api.url": "http://aka.ms/onenote-errors#C10008"
}
};
let expected = {
error: "Unexpected response status",
statusCode: 403,
responseHeaders: { "Content-Type": "application/json" },
response: JSON.stringify(responseJson),
timeout: 30000
};
this.server.respondWith([expected.statusCode, expected.responseHeaders, expected.response]);
controllerInstance.fetchFreshNotebooks("sessionId").then((responsePackage: OneNoteApi.ResponsePackage<OneNoteApi.Notebook[]>) => {
ok(false, "resolve should not be called");
}, (error: OneNoteApi.RequestError) => {
deepEqual(error, expected, "The error object should be rejected");
ok(!OneNoteApiUtils.isRetryable(controllerInstance.state.apiResponseCode));
}).then(() => {
done();
});
});
test("fetchFreshNotebooks should reject with the error object and a copy of the response if the status code is 5XX", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let responseJson = {
error: "Unexpected response status",
statusCode: 501,
responseHeaders: { "Content-Type": "application/json" }
};
this.server.respondWith([501, responseJson.responseHeaders, JSON.stringify(responseJson)]);
let expected = {
error: responseJson.error,
statusCode: responseJson.statusCode,
responseHeaders: responseJson.responseHeaders,
response: JSON.stringify(responseJson),
timeout: 30000
};
controllerInstance.fetchFreshNotebooks("sessionId").then((responsePackage: OneNoteApi.ResponsePackage<OneNoteApi.Notebook[]>) => {
ok(false, "resolve should not be called");
}, (error) => {
deepEqual(error, expected, "The error object should be rejected");
}).then(() => {
done();
});
});
test("onPopupToggle should restore focus to the section location container when the popup closes via ESC key", (assert: QUnitAssert) => {
let done = assert.async();
let clipperState = MockProps.getMockClipperState();
let mockNotebooks = MockProps.getMockNotebooks();
initializeClipperStorage(JSON.stringify(mockNotebooks), undefined, TestConstants.defaultUserInfoAsJsonString);
let component = <SectionPicker
onPopupToggle={() => {}}
clipperState={clipperState} />;
let controllerInstance = MithrilUtils.mountToFixture(component);
// Simulate opening the popup
controllerInstance.onPopupToggle(true);
strictEqual(controllerInstance.popupIsOpen, true, "The popupIsOpen flag should be true when popup opens");
// Create and dispatch an ESC key event
let escEvent: KeyboardEvent;
try {
// Try modern KeyboardEvent constructor first
escEvent = new KeyboardEvent("keydown", {
keyCode: 27,
bubbles: true,
cancelable: true
} as any);
} catch (e) {
// Fallback to deprecated initKeyboardEvent for older test environments
if (document.createEvent) {
escEvent = document.createEvent("KeyboardEvent") as KeyboardEvent;
escEvent.initKeyboardEvent(
"keydown",
true,
true,
/* tslint:disable:no-null-keyword */
null,
/* tslint:enable:no-null-keyword */
false,
false,
false,
false,
27, // ESC key code
0);
}
}
document.dispatchEvent(escEvent);
// The escWasPressed flag should be set
strictEqual(controllerInstance.escWasPressed, true, "The escWasPressed flag should be true after ESC is pressed");
// Simulate the popup closing
controllerInstance.onPopupToggle(false);
// Use a short delay to allow focus restoration to complete
setTimeout(() => {
strictEqual(controllerInstance.popupIsOpen, false, "The popupIsOpen flag should be false when popup closes");
strictEqual(controllerInstance.escWasPressed, false, "The escWasPressed flag should be reset after focus restoration");
// Verify focus was set (in a real browser, document.activeElement would be the section container)
let sectionContainer = document.getElementById(TestConstants.Ids.sectionLocationContainer);
if (sectionContainer) {
// In test environment, just verify the element exists and is accessible
ok(sectionContainer, "The section location container should exist and be accessible for focus");
}
done();
}, 10);
});
}
}
(new SectionPickerTests()).runTests();
(new SectionPickerSinonTests()).runTests();