-
Notifications
You must be signed in to change notification settings - Fork 24.7k
/
bootstrap.spec.ts
570 lines (507 loc) Β· 18.4 KB
/
bootstrap.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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {APP_BASE_HREF, DOCUMENT, HashLocationStrategy, LocationStrategy, Ι΅getDOM as getDOM} from '@angular/common';
import {ApplicationRef, Component, CUSTOM_ELEMENTS_SCHEMA, destroyPlatform, Injectable, NgModule} from '@angular/core';
import {inject} from '@angular/core/testing';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {NavigationEnd, provideRouter, Resolve, Router, RouterModule, RouterOutlet, withEnabledBlockingInitialNavigation} from '@angular/router';
// This is needed, because all files under `packages/` are compiled together as part of the
// [legacy-unit-tests-saucelabs][1] CI job, including the `lib.webworker.d.ts` typings brought in by
// [service-worker/worker/src/service-worker.d.ts][2].
//
// [1]:
// https://github.com/angular/angular/blob/ffeea63f43e6a7fd46be4a8cd5a5d254c98dea08/.circleci/config.yml#L681
// [2]:
// https://github.com/angular/angular/blob/316dc2f12ce8931f5ff66fa5f8da21c0d251a337/packages/service-worker/worker/src/service-worker.d.ts#L9
declare var window: Window;
describe('bootstrap', () => {
if (isNode) {
// Jasmine will throw if there are no tests.
it('should pass', () => {});
return;
}
let log: any[] = [];
let testProviders: any[] = null!;
@Component({template: 'simple'})
class SimpleCmp {
}
@Component({selector: 'test-app', template: 'root <router-outlet></router-outlet>'})
class RootCmp {
constructor() {
log.push('RootCmp');
}
}
@Component({selector: 'test-app2', template: 'root <router-outlet></router-outlet>'})
class SecondRootCmp {
}
@Injectable({providedIn: 'root'})
class TestResolver implements Resolve<any> {
resolve() {
let resolve: any = null;
const res = new Promise(r => resolve = r);
setTimeout(() => resolve('test-data'), 0);
return res;
}
}
beforeEach(inject([DOCUMENT], (doc: any) => {
destroyPlatform();
const el1 = getDOM().createElement('test-app', doc);
const el2 = getDOM().createElement('test-app2', doc);
doc.body.appendChild(el1);
doc.body.appendChild(el2);
log = [];
testProviders = [{provide: APP_BASE_HREF, useValue: ''}];
}));
afterEach(inject([DOCUMENT], (doc: any) => {
const oldRoots = doc.querySelectorAll('test-app,test-app2');
for (let i = 0; i < oldRoots.length; i++) {
getDOM().remove(oldRoots[i]);
}
}));
it('should complete resolvers when initial navigation fails and initialNavigation = enabledBlocking',
async () => {
@NgModule({
imports: [BrowserModule],
declarations: [RootCmp],
bootstrap: [RootCmp],
providers: [
...testProviders, {provide: LocationStrategy, useClass: HashLocationStrategy},
provideRouter(
[{
matcher: () => {
throw new Error('error in matcher');
},
children: []
}],
withEnabledBlockingInitialNavigation())
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
class TestModule {
constructor(router: Router) {
log.push('TestModule');
router.events.subscribe(e => log.push(e.constructor.name));
}
}
await platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
const router = res.injector.get(Router);
expect(router.navigated).toEqual(false);
expect(router.getCurrentNavigation()).toBeNull();
expect(log).toContain('TestModule');
expect(log).toContain('NavigationError');
});
});
it('should finish navigation when initial navigation is enabledBlocking and component renavigates on render',
async () => {
@Component({
template: '',
standalone: true,
})
class Renavigate {
constructor(router: Router) {
router.navigateByUrl('/other');
}
}
@Component({
template: '',
standalone: true,
})
class BlankCmp {
}
let resolveFn: () => void;
const navigationEndPromise = new Promise<void>(r => {
resolveFn = r;
});
@NgModule({
imports: [BrowserModule, RouterOutlet],
declarations: [RootCmp],
bootstrap: [RootCmp],
providers: [
{provide: LocationStrategy, useClass: HashLocationStrategy},
provideRouter(
[{path: '', component: Renavigate}, {path: 'other', component: BlankCmp}],
withEnabledBlockingInitialNavigation())
],
})
class TestModule {
constructor(router: Router) {
router.events.subscribe(e => {
if (e instanceof NavigationEnd) {
resolveFn();
expect(router.url).toEqual('/other');
}
});
}
}
await Promise.all(
[platformBrowserDynamic([]).bootstrapModule(TestModule), navigationEndPromise]);
});
it('should wait for redirect when initialNavigation = enabledBlocking', async () => {
@Injectable({providedIn: 'root'})
class Redirect {
constructor(private router: Router) {}
canActivate() {
this.router.navigateByUrl('redirectToMe');
return false;
}
}
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(
[
{path: 'redirectToMe', children: [], resolve: {test: TestResolver}},
{path: '**', canActivate: [Redirect], children: []}
],
{useHash: true, initialNavigation: 'enabledBlocking'})
],
declarations: [RootCmp],
bootstrap: [RootCmp],
providers: [...testProviders],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
class TestModule {
constructor(router: Router) {
log.push('TestModule');
}
}
await platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
const router = res.injector.get(Router);
expect(router.navigated).toEqual(true);
expect(router.url).toContain('redirectToMe');
expect(log).toContain('TestModule');
});
});
it('should wait for redirect with UrlTree when initialNavigation = enabledBlocking', async () => {
@Injectable({providedIn: 'root'})
class Redirect {
constructor(private router: Router) {}
canActivate() {
return this.router.createUrlTree(['/redirectToMe']);
}
}
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(
[
{path: 'redirectToMe', children: [], resolve: {test: TestResolver}},
{path: '**', canActivate: [Redirect], children: []}
],
{useHash: true, initialNavigation: 'enabledBlocking'})
],
declarations: [RootCmp],
bootstrap: [RootCmp],
providers: [...testProviders],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
class TestModule {
constructor(router: Router) {
log.push('TestModule');
}
}
await platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
const router = res.injector.get(Router);
expect(router.navigated).toEqual(true);
expect(router.url).toContain('redirectToMe');
expect(log).toContain('TestModule');
});
});
it('should wait for resolvers to complete when initialNavigation = enabledBlocking', (done) => {
@Component({selector: 'test', template: 'test'})
class TestCmpEnabled {
}
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(
[{path: '**', component: TestCmpEnabled, resolve: {test: TestResolver}}],
{useHash: true, initialNavigation: 'enabledBlocking'})
],
declarations: [RootCmp, TestCmpEnabled],
bootstrap: [RootCmp],
providers: [...testProviders, TestResolver],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
class TestModule {
constructor(router: Router) {
log.push('TestModule');
router.events.subscribe(e => log.push(e.constructor.name));
}
}
platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
const router = res.injector.get(Router);
const data = router.routerState.snapshot.root.firstChild!.data;
expect(data['test']).toEqual('test-data');
expect(log).toEqual([
'TestModule', 'NavigationStart', 'RoutesRecognized', 'GuardsCheckStart',
'ChildActivationStart', 'ActivationStart', 'GuardsCheckEnd', 'ResolveStart', 'ResolveEnd',
'RootCmp', 'ActivationEnd', 'ChildActivationEnd', 'NavigationEnd', 'Scroll'
]);
done();
});
});
it('should NOT wait for resolvers to complete when initialNavigation = enabledNonBlocking',
(done) => {
@Component({selector: 'test', template: 'test'})
class TestCmpLegacyEnabled {
}
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(
[{path: '**', component: TestCmpLegacyEnabled, resolve: {test: TestResolver}}],
{useHash: true, initialNavigation: 'enabledNonBlocking'})
],
declarations: [RootCmp, TestCmpLegacyEnabled],
bootstrap: [RootCmp],
providers: [...testProviders, TestResolver],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
class TestModule {
constructor(router: Router) {
log.push('TestModule');
router.events.subscribe(e => log.push(e.constructor.name));
}
}
platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
const router: Router = res.injector.get(Router);
expect(router.routerState.snapshot.root.firstChild).toBeNull();
// ResolveEnd has not been emitted yet because bootstrap returned too early
expect(log).toEqual([
'TestModule', 'RootCmp', 'NavigationStart', 'RoutesRecognized', 'GuardsCheckStart',
'ChildActivationStart', 'ActivationStart', 'GuardsCheckEnd', 'ResolveStart'
]);
router.events.subscribe((e) => {
if (e instanceof NavigationEnd) {
done();
}
});
});
});
it('should NOT wait for resolvers to complete when initialNavigation is not set', (done) => {
@Component({selector: 'test', template: 'test'})
class TestCmpLegacyEnabled {
}
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(
[{path: '**', component: TestCmpLegacyEnabled, resolve: {test: TestResolver}}],
{useHash: true})
],
declarations: [RootCmp, TestCmpLegacyEnabled],
bootstrap: [RootCmp],
providers: [...testProviders, TestResolver],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
class TestModule {
constructor(router: Router) {
log.push('TestModule');
router.events.subscribe(e => log.push(e.constructor.name));
}
}
platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
const router: Router = res.injector.get(Router);
expect(router.routerState.snapshot.root.firstChild).toBeNull();
// ResolveEnd has not been emitted yet because bootstrap returned too early
expect(log).toEqual([
'TestModule', 'RootCmp', 'NavigationStart', 'RoutesRecognized', 'GuardsCheckStart',
'ChildActivationStart', 'ActivationStart', 'GuardsCheckEnd', 'ResolveStart'
]);
router.events.subscribe((e) => {
if (e instanceof NavigationEnd) {
done();
}
});
});
});
it('should not run navigation when initialNavigation = disabled', (done) => {
@Component({selector: 'test', template: 'test'})
class TestCmpDiabled {
}
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(
[{path: '**', component: TestCmpDiabled, resolve: {test: TestResolver}}],
{useHash: true, initialNavigation: 'disabled'})
],
declarations: [RootCmp, TestCmpDiabled],
bootstrap: [RootCmp],
providers: [...testProviders, TestResolver],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
class TestModule {
constructor(router: Router) {
log.push('TestModule');
router.events.subscribe(e => log.push(e.constructor.name));
}
}
platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
const router = res.injector.get(Router);
expect(log).toEqual(['TestModule', 'RootCmp']);
done();
});
});
it('should not init router navigation listeners if a non root component is bootstrapped',
(done) => {
@NgModule({
imports: [BrowserModule, RouterModule.forRoot([], {useHash: true})],
declarations: [SecondRootCmp, RootCmp],
bootstrap: [RootCmp],
providers: testProviders,
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
class TestModule {
}
platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
const router = res.injector.get(Router);
spyOn(router as any, 'resetRootComponentType').and.callThrough();
const appRef: ApplicationRef = res.injector.get(ApplicationRef);
appRef.bootstrap(SecondRootCmp);
expect((router as any).resetRootComponentType).not.toHaveBeenCalled();
done();
});
});
it('should reinit router navigation listeners if a previously bootstrapped root component is destroyed',
(done) => {
@NgModule({
imports: [BrowserModule, RouterModule.forRoot([], {useHash: true})],
declarations: [SecondRootCmp, RootCmp],
bootstrap: [RootCmp],
providers: testProviders,
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
class TestModule {
}
platformBrowserDynamic([]).bootstrapModule(TestModule).then(res => {
const router = res.injector.get(Router);
spyOn(router as any, 'resetRootComponentType').and.callThrough();
const appRef: ApplicationRef = res.injector.get(ApplicationRef);
appRef.components[0].onDestroy(() => {
appRef.bootstrap(SecondRootCmp);
expect((router as any).resetRootComponentType).toHaveBeenCalled();
done();
});
appRef.components[0].destroy();
});
});
it('should restore the scrolling position', async () => {
@Component({
selector: 'component-a',
template: `
<div style="height: 3000px;"></div>
<div id="marker1"></div>
<div style="height: 3000px;"></div>
<div id="marker2"></div>
<div style="height: 3000px;"></div>
<a name="marker3"></a>
<div style="height: 3000px;"></div>
`
})
class TallComponent {
}
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(
[
{path: '', pathMatch: 'full', redirectTo: '/aa'},
{path: 'aa', component: TallComponent}, {path: 'bb', component: TallComponent},
{path: 'cc', component: TallComponent},
{path: 'fail', component: TallComponent, canActivate: ['returnFalse']}
],
{
useHash: true,
scrollPositionRestoration: 'enabled',
anchorScrolling: 'enabled',
scrollOffset: [0, 100],
onSameUrlNavigation: 'reload'
})
],
declarations: [TallComponent, RootCmp],
bootstrap: [RootCmp],
providers: [...testProviders, {provide: 'returnFalse', useValue: () => false}],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
class TestModule {
}
const res = await platformBrowserDynamic([]).bootstrapModule(TestModule);
const router = res.injector.get(Router);
await router.navigateByUrl('/aa');
window.scrollTo(0, 5000);
await router.navigateByUrl('/fail');
expect(window.pageYOffset).toEqual(5000);
await router.navigateByUrl('/bb');
window.scrollTo(0, 3000);
expect(window.pageYOffset).toEqual(3000);
await router.navigateByUrl('/cc');
expect(window.pageYOffset).toEqual(0);
await router.navigateByUrl('/aa#marker2');
expect(window.pageYOffset).toBeGreaterThanOrEqual(5900);
expect(window.pageYOffset).toBeLessThan(6000); // offset
await router.navigateByUrl('/aa#marker3');
expect(window.pageYOffset).toBeGreaterThanOrEqual(8900);
expect(window.pageYOffset).toBeLessThan(9000);
});
it('should cleanup "popstate" and "hashchange" listeners', async () => {
@NgModule({
imports: [BrowserModule, RouterModule.forRoot([])],
declarations: [RootCmp],
bootstrap: [RootCmp],
providers: testProviders,
})
class TestModule {
}
spyOn(window, 'addEventListener').and.callThrough();
spyOn(window, 'removeEventListener').and.callThrough();
const ngModuleRef = await platformBrowserDynamic().bootstrapModule(TestModule);
ngModuleRef.destroy();
expect(window.addEventListener).toHaveBeenCalledTimes(2);
expect(window.addEventListener)
.toHaveBeenCalledWith('popstate', jasmine.any(Function), jasmine.any(Boolean));
expect(window.addEventListener)
.toHaveBeenCalledWith('hashchange', jasmine.any(Function), jasmine.any(Boolean));
expect(window.removeEventListener).toHaveBeenCalledWith('popstate', jasmine.any(Function));
expect(window.removeEventListener).toHaveBeenCalledWith('hashchange', jasmine.any(Function));
});
it('can schedule a navigation from the NavigationEnd event #37460', (done) => {
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(
[
{path: 'a', component: SimpleCmp},
{path: 'b', component: SimpleCmp},
],
)
],
declarations: [RootCmp, SimpleCmp],
bootstrap: [RootCmp],
providers: [...testProviders],
})
class TestModule {
}
(async () => {
const res = await platformBrowserDynamic([]).bootstrapModule(TestModule);
const router = res.injector.get(Router);
router.events.subscribe(() => {
expect(router.getCurrentNavigation()?.id).toBeDefined();
});
router.events.subscribe(async (e) => {
if (e instanceof NavigationEnd && e.url === '/b') {
await router.navigate(['a']);
done();
}
});
await router.navigateByUrl('/b');
})();
});
});