forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.component.spec.ts
1361 lines (1092 loc) · 49.6 KB
/
app.component.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { APP_BASE_HREF } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, fakeAsync, flushMicrotasks, inject, TestBed, tick } from '@angular/core/testing';
import { MatProgressBar } from '@angular/material/progress-bar';
import { MatSidenav } from '@angular/material/sidenav';
import { By, Title } from '@angular/platform-browser';
import { ElementsLoader } from 'app/custom-elements/elements-loader';
import { DocumentService } from 'app/documents/document.service';
import { DocViewerComponent } from 'app/layout/doc-viewer/doc-viewer.component';
import { CurrentNodes } from 'app/navigation/navigation.model';
import { NavigationNode, NavigationService } from 'app/navigation/navigation.service';
import { SearchBoxComponent } from 'app/search/search-box/search-box.component';
import { SearchService } from 'app/search/search.service';
import { Deployment } from 'app/shared/deployment.service';
import { GaService } from 'app/shared/ga.service';
import { LocationService } from 'app/shared/location.service';
import { Logger } from 'app/shared/logger.service';
import { ScrollService } from 'app/shared/scroll.service';
import { SearchResultsComponent } from 'app/shared/search-results/search-results.component';
import { SelectComponent } from 'app/shared/select/select.component';
import { TocItem, TocService } from 'app/shared/toc.service';
import { of, Subject, timer } from 'rxjs';
import { first, mapTo } from 'rxjs/operators';
import { MockLocationService } from 'testing/location.service';
import { MockLogger } from 'testing/logger.service';
import { MockSearchService } from 'testing/search.service';
import { AppComponent } from './app.component';
import { AppModule } from './app.module';
const sideBySideBreakPoint = 992;
const hideToCBreakPoint = 800;
const startedDelay = 100;
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let documentService: DocumentService;
let docViewer: HTMLElement;
let docViewerComponent: DocViewerComponent;
let hamburger: HTMLButtonElement;
let locationService: MockLocationService;
let sidenav: MatSidenav;
let tocService: TocService;
async function awaitDocRendered() {
const newDocPromise = new Promise(resolve => documentService.currentDocument.subscribe(resolve));
const docRenderedPromise = new Promise(resolve => docViewerComponent.docRendered.subscribe(resolve));
await newDocPromise; // Wait for the new document to be fetched.
fixture.detectChanges(); // Propagate document change to the view (i.e to `DocViewer`).
await docRenderedPromise; // Wait for the `docRendered` event.
}
function initializeTest(waitForDoc = true) {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.onResize(sideBySideBreakPoint + 1); // wide by default
const de = fixture.debugElement;
const docViewerDe = de.query(By.css('aio-doc-viewer'));
documentService = de.injector.get<DocumentService>(DocumentService);
docViewer = docViewerDe.nativeElement;
docViewerComponent = docViewerDe.componentInstance;
hamburger = de.query(By.css('.hamburger')).nativeElement;
locationService = de.injector.get<any>(LocationService);
sidenav = de.query(By.directive(MatSidenav)).componentInstance;
tocService = de.injector.get<TocService>(TocService);
return waitForDoc && awaitDocRendered();
}
describe('with proper DocViewer', () => {
beforeEach(async () => {
DocViewerComponent.animationsEnabled = false;
createTestingModule('a/b');
await initializeTest();
});
afterEach(() => DocViewerComponent.animationsEnabled = true);
it('should create', () => {
expect(component).toBeDefined();
});
describe('hasFloatingToc', () => {
it('should initially be false', () => {
const fixture2 = TestBed.createComponent(AppComponent);
const component2 = fixture2.componentInstance;
expect(component2.hasFloatingToc).toBe(false);
});
it('should be false on narrow screens', () => {
component.onResize(hideToCBreakPoint - 1);
tocService.tocList.next([{}, {}, {}] as TocItem[]);
expect(component.hasFloatingToc).toBe(false);
tocService.tocList.next([]);
expect(component.hasFloatingToc).toBe(false);
tocService.tocList.next([{}, {}, {}] as TocItem[]);
expect(component.hasFloatingToc).toBe(false);
});
it('should be true on wide screens unless the toc is empty', () => {
component.onResize(hideToCBreakPoint + 1);
tocService.tocList.next([{}, {}, {}] as TocItem[]);
expect(component.hasFloatingToc).toBe(true);
tocService.tocList.next([]);
expect(component.hasFloatingToc).toBe(false);
tocService.tocList.next([{}, {}, {}] as TocItem[]);
expect(component.hasFloatingToc).toBe(true);
});
it('should be false when toc is empty', () => {
tocService.tocList.next([]);
component.onResize(hideToCBreakPoint + 1);
expect(component.hasFloatingToc).toBe(false);
component.onResize(hideToCBreakPoint - 1);
expect(component.hasFloatingToc).toBe(false);
component.onResize(hideToCBreakPoint + 1);
expect(component.hasFloatingToc).toBe(false);
});
it('should be true when toc is not empty unless the screen is narrow', () => {
tocService.tocList.next([{}, {}, {}] as TocItem[]);
component.onResize(hideToCBreakPoint + 1);
expect(component.hasFloatingToc).toBe(true);
component.onResize(hideToCBreakPoint - 1);
expect(component.hasFloatingToc).toBe(false);
component.onResize(hideToCBreakPoint + 1);
expect(component.hasFloatingToc).toBe(true);
});
});
describe('isSideBySide', () => {
it('should be updated on resize', () => {
component.onResize(sideBySideBreakPoint - 1);
expect(component.isSideBySide).toBe(false);
component.onResize(sideBySideBreakPoint + 1);
expect(component.isSideBySide).toBe(true);
});
});
describe('onScroll', () => {
it('should update `tocMaxHeight` accordingly', () => {
component.tocMaxHeight = '';
component.onScroll();
expect(component.tocMaxHeight).toMatch(/^\d+\.\d{2}$/);
});
});
describe('SideNav', () => {
const navigateTo = (path: string) => {
locationService.go(path);
component.updateSideNav();
fixture.detectChanges();
};
const resizeTo = (width: number) => {
component.onResize(width);
fixture.detectChanges();
};
const toggleSidenav = () => {
hamburger.click();
fixture.detectChanges();
};
describe('when side-by-side (wide)', () => {
beforeEach(() => resizeTo(sideBySideBreakPoint + 1)); // side-by-side
it('should open when navigating to a guide page (guide/pipes)', () => {
navigateTo('guide/pipes');
expect(sidenav.opened).toBe(true);
});
it('should open when navigating to an api page', () => {
navigateTo('api/a/b/c/d');
expect(sidenav.opened).toBe(true);
});
it('should be closed when navigating to a marketing page (features)', () => {
navigateTo('features');
expect(sidenav.opened).toBe(false);
});
describe('when manually closed', () => {
beforeEach(() => {
navigateTo('guide/pipes');
toggleSidenav();
});
it('should be closed', () => {
expect(sidenav.opened).toBe(false);
});
it('should stay closed when navigating from one guide page to another', () => {
navigateTo('guide/bags');
expect(sidenav.opened).toBe(false);
});
it('should stay closed when navigating from a guide page to api page', () => {
navigateTo('api');
expect(sidenav.opened).toBe(false);
});
it('should reopen when navigating to market page and back to guide page', () => {
navigateTo('features');
navigateTo('guide/bags');
expect(sidenav.opened).toBe(true);
});
});
});
describe('when NOT side-by-side (narrow)', () => {
beforeEach(() => resizeTo(sideBySideBreakPoint - 1)); // NOT side-by-side
it('should be closed when navigating to a guide page (guide/pipes)', () => {
navigateTo('guide/pipes');
expect(sidenav.opened).toBe(false);
});
it('should be closed when navigating to an api page', () => {
navigateTo('api/a/b/c/d');
expect(sidenav.opened).toBe(false);
});
it('should be closed when navigating to a marketing page (features)', () => {
navigateTo('features');
expect(sidenav.opened).toBe(false);
});
describe('when manually opened', () => {
beforeEach(() => {
navigateTo('guide/pipes');
toggleSidenav();
});
it('should be open', () => {
expect(sidenav.opened).toBe(true);
});
it('should close when clicking in gray content area overlay', () => {
const sidenavBackdrop = fixture.debugElement.query(By.css('.mat-drawer-backdrop')).nativeElement;
sidenavBackdrop.click();
fixture.detectChanges();
expect(sidenav.opened).toBe(false);
});
it('should close when navigating to another guide page', () => {
navigateTo('guide/bags');
expect(sidenav.opened).toBe(false);
});
it('should close when navigating to api page', () => {
navigateTo('api');
expect(sidenav.opened).toBe(false);
});
it('should close again when navigating to market page', () => {
navigateTo('features');
expect(sidenav.opened).toBe(false);
});
});
});
describe('when changing side-by-side (narrow --> wide)', () => {
const sidenavDocs = ['api/a/b/c/d', 'guide/pipes'];
const nonSidenavDocs = ['features', 'about'];
sidenavDocs.forEach(doc => {
it(`should open when on a sidenav doc (${doc})`, () => {
resizeTo(sideBySideBreakPoint - 1);
navigateTo(doc);
expect(sidenav.opened).toBe(false);
resizeTo(sideBySideBreakPoint + 1);
expect(sidenav.opened).toBe(true);
});
});
nonSidenavDocs.forEach(doc => {
it(`should remain closed when on a non-sidenav doc (${doc})`, () => {
resizeTo(sideBySideBreakPoint - 1);
navigateTo(doc);
expect(sidenav.opened).toBe(false);
resizeTo(sideBySideBreakPoint + 1);
expect(sidenav.opened).toBe(false);
});
});
describe('when manually opened', () => {
sidenavDocs.forEach(doc => {
it(`should remain opened when on a sidenav doc (${doc})`, () => {
resizeTo(sideBySideBreakPoint - 1);
navigateTo(doc);
toggleSidenav();
expect(sidenav.opened).toBe(true);
resizeTo(sideBySideBreakPoint + 1);
expect(sidenav.opened).toBe(true);
});
});
nonSidenavDocs.forEach(doc => {
it(`should close when on a non-sidenav doc (${doc})`, () => {
resizeTo(sideBySideBreakPoint - 1);
navigateTo(doc);
toggleSidenav();
expect(sidenav.opened).toBe(true);
resizeTo(sideBySideBreakPoint + 1);
expect(sidenav.opened).toBe(false);
});
});
});
});
describe('when changing side-by-side (wide --> narrow)', () => {
const sidenavDocs = ['api/a/b/c/d', 'guide/pipes'];
const nonSidenavDocs = ['features', 'about'];
sidenavDocs.forEach(doc => {
it(`should close when on a sidenav doc (${doc})`, () => {
navigateTo(doc);
expect(sidenav.opened).toBe(true);
resizeTo(sideBySideBreakPoint - 1);
expect(sidenav.opened).toBe(false);
});
});
nonSidenavDocs.forEach(doc => {
it(`should remain closed when on a non-sidenav doc (${doc})`, () => {
navigateTo(doc);
expect(sidenav.opened).toBe(false);
resizeTo(sideBySideBreakPoint - 1);
expect(sidenav.opened).toBe(false);
});
});
});
});
describe('SideNav version selector', () => {
let selectElement: DebugElement;
let selectComponent: SelectComponent;
async function setupSelectorForTesting(mode?: string) {
createTestingModule('a/b', mode);
await initializeTest();
component.onResize(sideBySideBreakPoint + 1); // side-by-side
selectElement = fixture.debugElement.query(By.directive(SelectComponent));
selectComponent = selectElement.componentInstance;
}
it('should select the version that matches the deploy mode', async () => {
await setupSelectorForTesting();
expect(selectComponent.selected.title).toContain('stable');
await setupSelectorForTesting('next');
expect(selectComponent.selected.title).toContain('next');
await setupSelectorForTesting('archive');
expect(selectComponent.selected.title).toContain('v4');
});
it('should add the current raw version string to the selected version', async () => {
await setupSelectorForTesting();
expect(selectComponent.selected.title).toContain(`(v${component.versionInfo.raw})`);
await setupSelectorForTesting('next');
expect(selectComponent.selected.title).toContain(`(v${component.versionInfo.raw})`);
await setupSelectorForTesting('archive');
expect(selectComponent.selected.title).toContain(`(v${component.versionInfo.raw})`);
});
// Older docs versions have an href
it('should navigate when change to a version with a url', async () => {
await setupSelectorForTesting();
locationService.urlSubject.next('new-page?id=1#section-1');
const versionWithUrlIndex = component.docVersions.findIndex(v => !!v.url);
const versionWithUrl = component.docVersions[versionWithUrlIndex];
const versionWithUrlAndPage = `${versionWithUrl.url}new-page?id=1#section-1`;
selectElement.triggerEventHandler('change', { option: versionWithUrl, index: versionWithUrlIndex});
expect(locationService.go).toHaveBeenCalledWith(versionWithUrlAndPage);
});
it('should not navigate when change to a version without a url', async () => {
await setupSelectorForTesting();
const versionWithoutUrlIndex = component.docVersions.length;
const versionWithoutUrl = component.docVersions[versionWithoutUrlIndex] = { title: 'foo' };
selectElement.triggerEventHandler('change', { option: versionWithoutUrl, index: versionWithoutUrlIndex });
expect(locationService.go).not.toHaveBeenCalled();
});
it('should navigate when change to a version with a url that does not end with `/`', async () => {
await setupSelectorForTesting();
locationService.urlSubject.next('docs#section-1');
const versionWithoutSlashIndex = component.docVersions.length;
const versionWithoutSlashUrl = component.docVersions[versionWithoutSlashIndex] = { url: 'https://next.angular.io', title: 'foo' };
selectElement.triggerEventHandler('change', { option: versionWithoutSlashUrl, index: versionWithoutSlashIndex });
expect(locationService.go).toHaveBeenCalledWith('https://next.angular.io/docs#section-1');
});
});
describe('currentDocument', () => {
const navigateTo = async (path: string) => {
locationService.go(path);
await awaitDocRendered();
};
it('should display a guide page (guide/pipes)', async () => {
await navigateTo('guide/pipes');
expect(docViewer.textContent).toMatch(/Pipes/i);
});
it('should display the api page', async () => {
await navigateTo('api');
expect(docViewer.textContent).toMatch(/API/i);
});
it('should display a marketing page', async () => {
await navigateTo('features');
expect(docViewer.textContent).toMatch(/Features/i);
});
it('should update the document title', async () => {
const titleService = TestBed.inject(Title);
spyOn(titleService, 'setTitle');
await navigateTo('guide/pipes');
expect(titleService.setTitle).toHaveBeenCalledWith('Angular - Pipes');
});
it('should update the document title, with a default value if the document has no title', async () => {
const titleService = TestBed.inject(Title);
spyOn(titleService, 'setTitle');
await navigateTo('no-title');
expect(titleService.setTitle).toHaveBeenCalledWith('Angular');
});
});
describe('auto-scrolling', () => {
const scrollDelay = 500;
let scrollService: ScrollService;
let scrollSpy: jasmine.Spy;
let scrollToTopSpy: jasmine.Spy;
let scrollAfterRenderSpy: jasmine.Spy;
let removeStoredScrollInfoSpy: jasmine.Spy;
beforeEach(() => {
scrollService = fixture.debugElement.injector.get<ScrollService>(ScrollService);
scrollSpy = spyOn(scrollService, 'scroll');
scrollToTopSpy = spyOn(scrollService, 'scrollToTop');
scrollAfterRenderSpy = spyOn(scrollService, 'scrollAfterRender');
removeStoredScrollInfoSpy = spyOn(scrollService, 'removeStoredScrollInfo');
});
it('should not scroll immediately when the docId (path) changes', () => {
locationService.go('guide/pipes');
// deliberately not calling `fixture.detectChanges` because don't want `onDocInserted`
expect(scrollSpy).not.toHaveBeenCalled();
expect(scrollToTopSpy).not.toHaveBeenCalled();
});
it('should scroll when just the hash changes (# alone)', () => {
locationService.go('guide/pipes');
locationService.go('guide/pipes#somewhere');
expect(scrollSpy).toHaveBeenCalled();
});
it('should scroll when just the hash changes (/#)', () => {
locationService.go('guide/pipes');
locationService.go('guide/pipes/#somewhere');
expect(scrollSpy).toHaveBeenCalled();
});
it('should scroll again when navigating to the same hash twice in succession', () => {
locationService.go('guide/pipes');
locationService.go('guide/pipes#somewhere');
locationService.go('guide/pipes#somewhere');
expect(scrollSpy.calls.count()).toBe(2);
});
it('should scroll when navigating to the same path', () => {
locationService.go('guide/pipes');
scrollSpy.calls.reset();
locationService.go('guide/pipes');
expect(scrollSpy).toHaveBeenCalledTimes(1);
});
it('should scroll when re-nav to the empty path', () => {
locationService.go('');
scrollSpy.calls.reset();
locationService.go('');
expect(scrollSpy).toHaveBeenCalledTimes(1);
});
it('should call `removeStoredScrollInfo` when call `onDocRemoved` directly', () => {
component.onDocRemoved();
expect(removeStoredScrollInfoSpy).toHaveBeenCalled();
});
it('should call `scrollAfterRender` when call `onDocInserted` directly', (() => {
component.onDocInserted();
expect(scrollAfterRenderSpy).toHaveBeenCalledWith(scrollDelay);
}));
it('should call `scrollAfterRender` (via `onDocInserted`) when navigate to a new Doc', fakeAsync(() => {
locationService.go('guide/pipes');
tick(1); // triggers the HTTP response for the document
fixture.detectChanges(); // passes the new doc to the `DocViewer`
flushMicrotasks(); // triggers the `DocViewer` event that calls `onDocInserted`
expect(scrollAfterRenderSpy).toHaveBeenCalledWith(scrollDelay);
tick(500); // there are other outstanding timers in the AppComponent that are not relevant
}));
});
describe('click intercepting', () => {
it('should intercept clicks on anchors and call `location.handleAnchorClick()`',
inject([LocationService], (location: LocationService) => {
const el = fixture.nativeElement as Element;
el.innerHTML = '<a href="some/local/url">click me</a>';
const anchorElement = el.getElementsByTagName('a')[0];
anchorElement.click();
expect(location.handleAnchorClick).toHaveBeenCalledWith(anchorElement, 0, false, false);
}));
it('should intercept clicks on elements deep within an anchor tag',
inject([LocationService], (location: LocationService) => {
const el = fixture.nativeElement as Element;
el.innerHTML = '<a href="some/local/url"><div><img></div></a>';
const imageElement = el.getElementsByTagName('img')[0];
const anchorElement = el.getElementsByTagName('a')[0];
imageElement.click();
expect(location.handleAnchorClick).toHaveBeenCalledWith(anchorElement, 0, false, false);
}));
it('should ignore clicks on elements without an anchor ancestor',
inject([LocationService], (location: LocationService) => {
const el = fixture.nativeElement as Element;
el.innerHTML = '<div><p><div><img></div></p></div>';
const imageElement = el.getElementsByTagName('img')[0];
imageElement.click();
expect(location.handleAnchorClick).not.toHaveBeenCalled();
}));
});
describe('restrainScrolling()', () => {
const preventedScrolling = (currentTarget: object, deltaY: number) => {
const evt = {
deltaY,
currentTarget,
defaultPrevented: false,
preventDefault() { this.defaultPrevented = true; }
} as any as WheelEvent;
component.restrainScrolling(evt);
return evt.defaultPrevented;
};
it('should prevent scrolling up if already at the top', () => {
const elem = {scrollTop: 0};
expect(preventedScrolling(elem, -100)).toBe(true);
expect(preventedScrolling(elem, +100)).toBe(false);
expect(preventedScrolling(elem, -10)).toBe(true);
});
it('should prevent scrolling down if already at the bottom', () => {
const elem = {scrollTop: 100, scrollHeight: 150, clientHeight: 50};
expect(preventedScrolling(elem, +10)).toBe(true);
expect(preventedScrolling(elem, -10)).toBe(false);
expect(preventedScrolling(elem, +5)).toBe(true);
elem.clientHeight -= 10;
expect(preventedScrolling(elem, +5)).toBe(false);
elem.scrollHeight -= 20;
expect(preventedScrolling(elem, +5)).toBe(true);
elem.scrollTop -= 30;
expect(preventedScrolling(elem, +5)).toBe(false);
});
it('should not prevent scrolling if neither at the top nor at the bottom', () => {
const elem = {scrollTop: 50, scrollHeight: 150, clientHeight: 50};
expect(preventedScrolling(elem, +100)).toBe(false);
expect(preventedScrolling(elem, -100)).toBe(false);
});
});
describe('aio-toc', () => {
let tocContainer: HTMLElement|null;
let toc: HTMLElement|null;
const setHasFloatingToc = (hasFloatingToc: boolean) => {
component.hasFloatingToc = hasFloatingToc;
fixture.detectChanges();
tocContainer = fixture.debugElement.nativeElement.querySelector('.toc-container');
toc = tocContainer && tocContainer.querySelector('aio-toc');
};
beforeEach(() => {
tocContainer = null;
toc = null;
});
it('should show/hide `<aio-toc>` based on `hasFloatingToc`', () => {
expect(tocContainer).toBeFalsy();
expect(toc).toBeFalsy();
setHasFloatingToc(true);
expect(tocContainer).toBeTruthy();
expect(toc).toBeTruthy();
setHasFloatingToc(false);
expect(tocContainer).toBeFalsy();
expect(toc).toBeFalsy();
});
it('should have a non-embedded `<aio-toc>` element', () => {
setHasFloatingToc(true);
expect(toc!.classList.contains('embedded')).toBe(false);
});
it('should update the TOC container\'s `maxHeight` based on `tocMaxHeight`', () => {
setHasFloatingToc(true);
component.tocMaxHeight = '100';
fixture.detectChanges();
expect(tocContainer!.style.maxHeight).toBe('100px');
component.tocMaxHeight = '200';
fixture.detectChanges();
expect(tocContainer!.style.maxHeight).toBe('200px');
});
it('should restrain scrolling inside the ToC container', () => {
const restrainScrolling = spyOn(component, 'restrainScrolling');
const evt = new WheelEvent('wheel');
setHasFloatingToc(true);
expect(restrainScrolling).not.toHaveBeenCalled();
tocContainer!.dispatchEvent(evt);
expect(restrainScrolling).toHaveBeenCalledWith(evt);
});
it('should not be loaded/registered until necessary', () => {
const loader = fixture.debugElement.injector.get(ElementsLoader) as unknown as TestElementsLoader;
expect(loader.loadCustomElement).not.toHaveBeenCalled();
setHasFloatingToc(true);
expect(loader.loadCustomElement).toHaveBeenCalledWith('aio-toc');
});
});
describe('footer', () => {
it('should have version number', () => {
const versionEl: HTMLElement = fixture.debugElement.query(By.css('aio-footer')).nativeElement;
expect(versionEl.textContent).toContain(TestHttpClient.versionInfo.full);
});
});
describe('deployment banner', () => {
it('should show a message if the deployment mode is "archive"', async () => {
createTestingModule('a/b', 'archive');
await initializeTest();
const banner: HTMLElement = fixture.debugElement.query(By.css('aio-mode-banner')).nativeElement;
expect(banner.textContent).toContain('archived documentation for Angular v4');
});
it('should show no message if the deployment mode is not "archive"', async () => {
createTestingModule('a/b', 'stable');
await initializeTest();
const banner: HTMLElement = fixture.debugElement.query(By.css('aio-mode-banner')).nativeElement;
expect(banner.textContent!.trim()).toEqual('');
});
});
describe('search', () => {
describe('initialization', () => {
it('should initialize the search worker', inject([SearchService], (searchService: SearchService) => {
expect(searchService.initWorker).toHaveBeenCalled();
}));
});
describe('click handling', () => {
it('should intercept clicks not on the search elements and hide the search results', () => {
component.showSearchResults = true;
fixture.detectChanges();
// docViewer is a commonly-clicked, non-search element
docViewer.click();
expect(component.showSearchResults).toBe(false);
});
it('should clear "only" the search query param from the URL', () => {
// Mock out the current state of the URL query params
locationService.search.and.returnValue({ a: 'some-A', b: 'some-B', search: 'some-C'});
// docViewer is a commonly-clicked, non-search element
docViewer.click();
// Check that the query params were updated correctly
expect(locationService.setSearch).toHaveBeenCalledWith('', { a: 'some-A', b: 'some-B', search: undefined });
});
it('should not intercept clicks on the searchResults', () => {
component.showSearchResults = true;
fixture.detectChanges();
const searchResults = fixture.debugElement.query(By.directive(SearchResultsComponent));
searchResults.nativeElement.click();
fixture.detectChanges();
expect(component.showSearchResults).toBe(true);
});
it('should not intercept clicks on the searchBox', () => {
component.showSearchResults = true;
fixture.detectChanges();
const searchBox = fixture.debugElement.query(By.directive(SearchBoxComponent));
searchBox.nativeElement.click();
fixture.detectChanges();
expect(component.showSearchResults).toBe(true);
});
it('should not call `locationService.setSearch` when searchResults are not shown', () => {
docViewer.click();
expect(locationService.setSearch).not.toHaveBeenCalled();
});
});
describe('keyup handling', () => {
it('should grab focus when the / key is pressed', () => {
const searchBox: SearchBoxComponent = fixture.debugElement.query(By.directive(SearchBoxComponent)).componentInstance;
spyOn(searchBox, 'focus');
window.document.dispatchEvent(new KeyboardEvent('keyup', { 'key': '/' }));
fixture.detectChanges();
expect(searchBox.focus).toHaveBeenCalled();
});
it('should set focus back to the search box when the search results are displayed and the escape key is pressed', () => {
const searchBox: SearchBoxComponent = fixture.debugElement.query(By.directive(SearchBoxComponent)).componentInstance;
spyOn(searchBox, 'focus');
component.showSearchResults = true;
window.document.dispatchEvent(new KeyboardEvent('keyup', { 'key': 'Escape' }));
fixture.detectChanges();
expect(searchBox.focus).toHaveBeenCalled();
});
});
describe('showing search results', () => {
it('should not display search results when query is empty', () => {
const searchService = TestBed.inject(SearchService) as Partial<SearchService> as MockSearchService;
searchService.searchResults.next({ query: '', results: [] });
fixture.detectChanges();
expect(component.showSearchResults).toBe(false);
});
it('should hide the results when a search result is selected', () => {
const searchService = TestBed.inject(SearchService) as Partial<SearchService> as MockSearchService;
const results = [
{ path: 'news', title: 'News', type: 'marketing', keywords: '', titleWords: '', deprecated: false, topics: '' }
];
searchService.searchResults.next({ query: 'something', results });
component.showSearchResults = true;
fixture.detectChanges();
const searchResultsComponent = fixture.debugElement.query(By.directive(SearchResultsComponent));
searchResultsComponent.triggerEventHandler('resultSelected', {});
fixture.detectChanges();
expect(component.showSearchResults).toBe(false);
});
it('should re-run the search when the search box regains focus', () => {
const doSearchSpy = spyOn(component, 'doSearch');
const searchBox = fixture.debugElement.query(By.directive(SearchBoxComponent));
searchBox.triggerEventHandler('onFocus', 'some query');
expect(doSearchSpy).toHaveBeenCalledWith('some query');
});
});
});
describe('archive redirection', () => {
const redirectionPerMode: {[mode: string]: boolean} = {
archive: true,
next: false,
stable: false,
};
Object.keys(redirectionPerMode).forEach(mode => {
const doRedirect = redirectionPerMode[mode];
const description =
`should ${doRedirect ? '' : 'not '}redirect to 'docs' if deployment mode is '${mode}' ` +
'and at a marketing page';
const verifyNoRedirection = () => expect(TestBed.inject(LocationService).replace).not.toHaveBeenCalled();
const verifyRedirection = () => expect(TestBed.inject(LocationService).replace).toHaveBeenCalledWith('docs');
const verifyPossibleRedirection = doRedirect ? verifyRedirection : verifyNoRedirection;
it(description, () => {
createTestingModule('', mode);
const navService = TestBed.inject(NavigationService);
const testCurrentNodes = navService.currentNodes = new Subject<CurrentNodes>();
initializeTest(false);
testCurrentNodes.next({SideNav: {url: 'foo', view: 'SideNav', nodes: []}});
verifyNoRedirection();
testCurrentNodes.next({NoSideNav: {url: 'bar', view: 'SideNav', nodes: []}});
verifyPossibleRedirection();
locationService.replace.calls.reset();
testCurrentNodes.next({});
verifyPossibleRedirection();
locationService.replace.calls.reset();
testCurrentNodes.next({SideNav: {url: 'baz', view: 'SideNav', nodes: []}});
verifyNoRedirection();
});
});
});
});
describe('with mocked DocViewer', () => {
const getDocViewer = () => fixture.debugElement.query(By.css('aio-doc-viewer'));
const triggerDocViewerEvent =
(evt: 'docReady' | 'docRemoved' | 'docInserted' | 'docRendered') =>
getDocViewer().triggerEventHandler(evt, undefined);
beforeEach(() => {
createTestingModule('a/b');
// Remove the DocViewer for this test and hide the missing component message
TestBed.overrideModule(AppModule, {
remove: { declarations: [DocViewerComponent] },
add: { schemas: [NO_ERRORS_SCHEMA] }
});
});
describe('initial rendering', () => {
beforeEach(jasmine.clock().install);
afterEach(jasmine.clock().uninstall);
it('should initially disable Angular animations until a document is rendered', () => {
initializeTest(false);
jasmine.clock().tick(1); // triggers the HTTP response for the document
expect(component.isStarting).toBe(true);
expect(fixture.debugElement.properties['@.disabled']).toBe(true);
triggerDocViewerEvent('docInserted');
jasmine.clock().tick(startedDelay);
fixture.detectChanges();
expect(component.isStarting).toBe(true);
expect(fixture.debugElement.properties['@.disabled']).toBe(true);
triggerDocViewerEvent('docRendered');
jasmine.clock().tick(startedDelay);
fixture.detectChanges();
expect(component.isStarting).toBe(false);
expect(fixture.debugElement.properties['@.disabled']).toBe(false);
});
it('should initially add the starting class until a document is rendered', () => {
initializeTest(false);
jasmine.clock().tick(1); // triggers the HTTP response for the document
const sidenavContainer = fixture.debugElement.query(By.css('mat-sidenav-container')).nativeElement;
expect(component.isStarting).toBe(true);
expect(hamburger.classList.contains('starting')).toBe(true);
expect(sidenavContainer.classList.contains('starting')).toBe(true);
triggerDocViewerEvent('docInserted');
jasmine.clock().tick(startedDelay);
fixture.detectChanges();
expect(component.isStarting).toBe(true);
expect(hamburger.classList.contains('starting')).toBe(true);
expect(sidenavContainer.classList.contains('starting')).toBe(true);
triggerDocViewerEvent('docRendered');
jasmine.clock().tick(startedDelay);
fixture.detectChanges();
expect(component.isStarting).toBe(false);
expect(hamburger.classList.contains('starting')).toBe(false);
expect(sidenavContainer.classList.contains('starting')).toBe(false);
});
it('should initially disable animations on the DocViewer for the first rendering', () => {
initializeTest(false);
jasmine.clock().tick(1); // triggers the HTTP response for the document
expect(component.isStarting).toBe(true);
expect(docViewer.classList.contains('no-animations')).toBe(true);
triggerDocViewerEvent('docInserted');
jasmine.clock().tick(startedDelay);
fixture.detectChanges();
expect(component.isStarting).toBe(true);
expect(docViewer.classList.contains('no-animations')).toBe(true);
triggerDocViewerEvent('docRendered');
jasmine.clock().tick(startedDelay);
fixture.detectChanges();
expect(component.isStarting).toBe(false);
expect(docViewer.classList.contains('no-animations')).toBe(false);
});
});
describe('subsequent rendering', () => {
beforeEach(jasmine.clock().install);
afterEach(jasmine.clock().uninstall);
it('should set the transitioning class on `.app-toolbar` while a document is being rendered', () => {
initializeTest(false);
jasmine.clock().tick(1); // triggers the HTTP response for the document
const toolbar = fixture.debugElement.query(By.css('.app-toolbar'));
// Initially, `isTransitoning` is true.
expect(component.isTransitioning).toBe(true);
expect(toolbar.classes['transitioning']).toBe(true);
triggerDocViewerEvent('docRendered');
fixture.detectChanges();
expect(component.isTransitioning).toBe(false);
expect(toolbar.classes['transitioning']).toBeFalsy();
// While a document is being rendered, `isTransitoning` is set to true.
triggerDocViewerEvent('docReady');
fixture.detectChanges();
expect(component.isTransitioning).toBe(true);
expect(toolbar.classes['transitioning']).toBe(true);
triggerDocViewerEvent('docRendered');
fixture.detectChanges();
expect(component.isTransitioning).toBe(false);
expect(toolbar.classes['transitioning']).toBeFalsy();
});
it('should update the sidenav state as soon as a new document is inserted (but not before)', () => {
initializeTest(false);
jasmine.clock().tick(1); // triggers the HTTP response for the document
jasmine.clock().tick(0); // calls `updateSideNav()` for initial rendering
const updateSideNavSpy = spyOn(component, 'updateSideNav');
triggerDocViewerEvent('docReady');
jasmine.clock().tick(0);
expect(updateSideNavSpy).not.toHaveBeenCalled();
triggerDocViewerEvent('docInserted');
jasmine.clock().tick(0);
expect(updateSideNavSpy).toHaveBeenCalledTimes(1);
updateSideNavSpy.calls.reset();
triggerDocViewerEvent('docReady');
jasmine.clock().tick(0);
expect(updateSideNavSpy).not.toHaveBeenCalled();