From 0142ae1c8e3d8f0ec256db0055fa2cf5050c1a19 Mon Sep 17 00:00:00 2001 From: Andrew Scott Date: Thu, 13 Mar 2025 15:18:15 -0700 Subject: [PATCH] refactor(router): Update tests to not use deprecated string tokens (#60378) This replaces string tokens in the router tests with functional guads. PR Close #60378 --- packages/router/test/apply_redirects.spec.ts | 64 +- .../test/computed_state_restoration.spec.ts | 3 +- packages/router/test/helpers.ts | 8 - .../duplicate_in_flight_navigations.spec.ts | 33 +- .../eager_url_update_strategy.spec.ts | 19 +- .../router/test/integration/guards.spec.ts | 615 +++++++----------- .../test/integration/lazy_loading.spec.ts | 22 +- .../test/integration/navigation.spec.ts | 43 +- .../integration/navigation_errors.spec.ts | 6 +- .../test/integration/route_data.spec.ts | 14 +- .../test/regression_integration.spec.ts | 14 +- packages/router/test/router.spec.ts | 134 ++-- packages/router/test/router_preloader.spec.ts | 4 +- 13 files changed, 418 insertions(+), 561 deletions(-) diff --git a/packages/router/test/apply_redirects.spec.ts b/packages/router/test/apply_redirects.spec.ts index cd591a4d83e..ae1e16ac50f 100644 --- a/packages/router/test/apply_redirects.spec.ts +++ b/packages/router/test/apply_redirects.spec.ts @@ -6,11 +6,10 @@ * found in the LICENSE file at https://angular.dev/license */ -import {EnvironmentInjector, inject, Injectable, NgModuleRef} from '@angular/core'; +import {EnvironmentInjector, inject, Injectable} from '@angular/core'; import {fakeAsync, TestBed, tick} from '@angular/core/testing'; -import {provideRouter, withRouterConfig} from '@angular/router'; -import {firstValueFrom, Observable, of} from 'rxjs'; -import {delay, map, tap} from 'rxjs/operators'; +import {Observable, of} from 'rxjs'; +import {delay, tap} from 'rxjs/operators'; import {Route, Routes} from '../src/models'; import {recognize} from '../src/recognize'; @@ -584,24 +583,28 @@ describe('redirects', () => { let passedUrlSegments: UrlSegment[]; - const guard = { - canLoad: (route: Route, urlSegments: UrlSegment[]) => { - passedUrlSegments = urlSegments; - return true; - }, - }; - const injector = {get: (token: any) => (token === 'guard' ? guard : {injector})}; - const config = [ { path: 'a', component: ComponentA, - canLoad: ['guard'], + canLoad: [ + (route: Route, urlSegments: UrlSegment[]) => { + passedUrlSegments = urlSegments; + return true; + }, + ], loadChildren: jasmine.createSpy('children'), }, ]; - recognize(injector, loader, null, config, tree('a/b'), serializer).subscribe( + recognize( + TestBed.inject(EnvironmentInjector), + loader, + null, + config, + tree('a/b'), + serializer, + ).subscribe( ({tree: r}) => { expectTreeToBe(r, '/a/b'); expect(passedUrlSegments.length).toBe(2); @@ -710,7 +713,7 @@ describe('redirects', () => { }); }); - it('should not load the configuration of a wildcard route if there is a match', () => { + it('should not load the configuration of a wildcard route if there is a match', async () => { const loadedConfig = { routes: [{path: '', component: ComponentB}], injector: TestBed.inject(EnvironmentInjector), @@ -727,20 +730,23 @@ describe('redirects', () => { {path: '**', loadChildren: jasmine.createSpy('children')}, ]; - recognize( - TestBed.inject(EnvironmentInjector), - loader, - null, - config, - tree(''), - serializer, - ).forEach(({tree: r}) => { - expect(loader.loadChildren.calls.count()).toEqual(1); - expect(loader.loadChildren.calls.first().args).not.toContain( - jasmine.objectContaining({ - loadChildren: jasmine.createSpy('children'), - }), - ); + await new Promise((resolve) => { + recognize( + TestBed.inject(EnvironmentInjector), + loader, + null, + config, + tree(''), + serializer, + ).forEach(({tree: r}) => { + expect(loader.loadChildren.calls.count()).toEqual(1); + expect(loader.loadChildren.calls.first().args).not.toContain( + jasmine.objectContaining({ + loadChildren: jasmine.createSpy('children'), + }), + ); + resolve(); + }); }); }); diff --git a/packages/router/test/computed_state_restoration.spec.ts b/packages/router/test/computed_state_restoration.spec.ts index 726625fc173..8317052680f 100644 --- a/packages/router/test/computed_state_restoration.spec.ts +++ b/packages/router/test/computed_state_restoration.spec.ts @@ -70,7 +70,6 @@ describe('`restoredState#ɵrouterPageId`', () => { TestBed.configureTestingModule({ imports: [TestModule], providers: [ - {provide: 'alwaysFalse', useValue: (a: any) => false}, {provide: Location, useClass: SpyLocation}, provideRouter( [ @@ -106,7 +105,7 @@ describe('`restoredState#ɵrouterPageId`', () => { { path: 'loaded', loadChildren: () => of(ModuleWithSimpleCmpAsRoute), - canLoad: ['alwaysFalse'], + canLoad: [() => false], }, ], withRouterConfig({ diff --git a/packages/router/test/helpers.ts b/packages/router/test/helpers.ts index e15638b305a..bd64fd5e58e 100644 --- a/packages/router/test/helpers.ts +++ b/packages/router/test/helpers.ts @@ -23,14 +23,6 @@ export class Logger { } } -export function provideTokenLogger(token: string, returnValue = true as boolean | UrlTree) { - return { - provide: token, - useFactory: (logger: Logger) => () => (logger.add(token), returnValue), - deps: [Logger], - }; -} - export declare type ARSArgs = { url?: UrlSegment[]; params?: Params; diff --git a/packages/router/test/integration/duplicate_in_flight_navigations.spec.ts b/packages/router/test/integration/duplicate_in_flight_navigations.spec.ts index 068b442d3b3..c1d2b6ec073 100644 --- a/packages/router/test/integration/duplicate_in_flight_navigations.spec.ts +++ b/packages/router/test/integration/duplicate_in_flight_navigations.spec.ts @@ -34,18 +34,7 @@ export function duplicateInFlightNavigationsIntegrationSuite() { beforeEach(() => { TestBed.configureTestingModule({ - providers: [ - { - provide: 'in1Second', - useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { - let res: any = null; - const p = new Promise((_) => (res = _)); - setTimeout(() => res(true), 1000); - return p; - }, - }, - RedirectingGuard, - ], + providers: [RedirectingGuard], }); }); @@ -54,7 +43,13 @@ export function duplicateInFlightNavigationsIntegrationSuite() { const location = TestBed.inject(Location); const fixture = createRoot(router, RootCmp); - router.resetConfig([{path: 'simple', component: SimpleCmp, canActivate: ['in1Second']}]); + router.resetConfig([ + { + path: 'simple', + component: SimpleCmp, + canActivate: [() => new Promise((resolve) => setTimeout(resolve, 1000))], + }, + ]); // Trigger two location changes to the same URL. // Because of the guard the order will look as follows: @@ -162,8 +157,16 @@ export function duplicateInFlightNavigationsIntegrationSuite() { it('should accurately track currentNavigation', fakeAsync(() => { const router = TestBed.inject(Router); router.resetConfig([ - {path: 'one', component: SimpleCmp, canActivate: ['in1Second']}, - {path: 'two', component: BlankCmp, canActivate: ['in1Second']}, + { + path: 'one', + component: SimpleCmp, + canActivate: [() => new Promise((resolve) => setTimeout(resolve, 1000))], + }, + { + path: 'two', + component: BlankCmp, + canActivate: [() => new Promise((resolve) => setTimeout(resolve, 1000))], + }, ]); router.events.subscribe((e) => { diff --git a/packages/router/test/integration/eager_url_update_strategy.spec.ts b/packages/router/test/integration/eager_url_update_strategy.spec.ts index 78642629c5b..79f8eb2cb8b 100644 --- a/packages/router/test/integration/eager_url_update_strategy.spec.ts +++ b/packages/router/test/integration/eager_url_update_strategy.spec.ts @@ -53,14 +53,6 @@ export function eagerUrlUpdateStrategyIntegrationSuite() { const serializer = new DefaultUrlSerializer(); TestBed.configureTestingModule({ providers: [ - { - provide: 'authGuardFail', - useValue: (a: any, b: any) => { - return new Promise((res) => { - setTimeout(() => res(serializer.parse('/login')), 1); - }); - }, - }, AuthGuard, DelayedGuard, provideRouter([], withRouterConfig({urlUpdateStrategy: 'eager'})), @@ -102,7 +94,16 @@ export function eagerUrlUpdateStrategyIntegrationSuite() { advance(fixture); router.resetConfig([ - {path: 'team/:id', component: SimpleCmp, canActivate: ['authGuardFail']}, + { + path: 'team/:id', + component: SimpleCmp, + canActivate: [ + () => + new Promise((res) => { + setTimeout(() => res(new DefaultUrlSerializer().parse('/login')), 1); + }), + ], + }, {path: 'login', component: AbsoluteSimpleLinkCmp}, ]); diff --git a/packages/router/test/integration/guards.spec.ts b/packages/router/test/integration/guards.spec.ts index 0c16c51ea7c..6ab34838f3c 100644 --- a/packages/router/test/integration/guards.spec.ts +++ b/packages/router/test/integration/guards.spec.ts @@ -49,6 +49,7 @@ import { CanMatchFn, CanActivateFn, CanActivateChildFn, + CanDeactivateFn, } from '../../src'; import {wrapIntoObservable} from '../../src/utils/collection'; import {RouterTestingHarness} from '../../testing'; @@ -117,12 +118,6 @@ export function guardsIntegrationSuite() { }); describe('should not activate a route when CanActivate returns false', () => { - beforeEach(() => { - TestBed.configureTestingModule({ - providers: [{provide: 'alwaysFalse', useValue: (a: any, b: any) => false}], - }); - }); - it('works', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); @@ -131,7 +126,7 @@ export function guardsIntegrationSuite() { router.events.forEach((e) => recordedEvents.push(e)); router.resetConfig([ - {path: 'team/:id', component: TeamCmp, canActivate: ['alwaysFalse']}, + {path: 'team/:id', component: TeamCmp, canActivate: [() => false]}, ]); router.navigateByUrl('/team/22'); @@ -153,12 +148,6 @@ export function guardsIntegrationSuite() { }); describe('should not activate a route when CanActivate returns false (componentless route)', () => { - beforeEach(() => { - TestBed.configureTestingModule({ - providers: [{provide: 'alwaysFalse', useValue: (a: any, b: any) => false}], - }); - }); - it('works', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); @@ -166,7 +155,7 @@ export function guardsIntegrationSuite() { router.resetConfig([ { path: 'parent', - canActivate: ['alwaysFalse'], + canActivate: [() => false], children: [{path: 'team/:id', component: TeamCmp}], }, ]); @@ -180,24 +169,11 @@ export function guardsIntegrationSuite() { }); describe('should activate a route when CanActivate returns true', () => { - beforeEach(() => { - TestBed.configureTestingModule({ - providers: [ - { - provide: 'alwaysTrue', - useValue: (a: ActivatedRouteSnapshot, s: RouterStateSnapshot) => true, - }, - ], - }); - }); - it('works', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); - router.resetConfig([ - {path: 'team/:id', component: TeamCmp, canActivate: ['alwaysTrue']}, - ]); + router.resetConfig([{path: 'team/:id', component: TeamCmp, canActivate: [() => true]}]); router.navigateByUrl('/team/22'); advance(fixture); @@ -232,27 +208,21 @@ export function guardsIntegrationSuite() { }); describe('should work when returns an observable', () => { - beforeEach(() => { - TestBed.configureTestingModule({ - providers: [ - { - provide: 'CanActivate', - useValue: (a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { - return new Observable((observer) => { - observer.next(false); - }); - }, - }, - ], - }); - }); - it('works', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ - {path: 'team/:id', component: TeamCmp, canActivate: ['CanActivate']}, + { + path: 'team/:id', + component: TeamCmp, + canActivate: [ + () => + new Observable((observer) => { + observer.next(false); + }), + ], + }, ]); router.navigateByUrl('/team/22'); @@ -263,29 +233,24 @@ export function guardsIntegrationSuite() { }); describe('should work when returns a promise', () => { - beforeEach(() => { - TestBed.configureTestingModule({ - providers: [ - { - provide: 'CanActivate', - useValue: (a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { - if (a.params['id'] === '22') { - return Promise.resolve(true); - } else { - return Promise.resolve(false); - } - }, - }, - ], - }); - }); - it('works', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ - {path: 'team/:id', component: TeamCmp, canActivate: ['CanActivate']}, + { + path: 'team/:id', + component: TeamCmp, + canActivate: [ + (a) => { + if (a.params['id'] === '22') { + return Promise.resolve(true); + } else { + return Promise.resolve(false); + } + }, + ], + }, ]); router.navigateByUrl('/team/22'); @@ -302,15 +267,7 @@ export function guardsIntegrationSuite() { describe('should reset the location when cancelling a navigation', () => { beforeEach(() => { TestBed.configureTestingModule({ - providers: [ - { - provide: 'alwaysFalse', - useValue: (a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { - return false; - }, - }, - {provide: LocationStrategy, useClass: HashLocationStrategy}, - ], + providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}], }); }); @@ -320,7 +277,7 @@ export function guardsIntegrationSuite() { router.resetConfig([ {path: 'one', component: SimpleCmp}, - {path: 'two', component: SimpleCmp, canActivate: ['alwaysFalse']}, + {path: 'two', component: SimpleCmp, canActivate: [() => false]}, ]); router.navigateByUrl('/one'); @@ -336,21 +293,6 @@ export function guardsIntegrationSuite() { }); describe('should redirect to / when guard returns false', () => { - beforeEach(() => - TestBed.configureTestingModule({ - providers: [ - { - provide: 'returnFalseAndNavigate', - useFactory: (router: Router) => () => { - router.navigate(['/']); - return false; - }, - deps: [Router], - }, - ], - }), - ); - it('works', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { router.resetConfig([ @@ -358,7 +300,16 @@ export function guardsIntegrationSuite() { path: '', component: SimpleCmp, }, - {path: 'one', component: RouteCmp, canActivate: ['returnFalseAndNavigate']}, + { + path: 'one', + component: RouteCmp, + canActivate: [ + () => { + coreInject(Router).navigate(['/']); + return false; + }, + ], + }, ]); const fixture = TestBed.createComponent(RootCmp); @@ -371,27 +322,6 @@ export function guardsIntegrationSuite() { }); describe('should redirect when guard returns UrlTree', () => { - beforeEach(() => - TestBed.configureTestingModule({ - providers: [ - { - provide: 'returnUrlTree', - useFactory: (router: Router) => () => { - return router.parseUrl('/redirected'); - }, - deps: [Router], - }, - { - provide: 'returnRootUrlTree', - useFactory: (router: Router) => () => { - return router.parseUrl('/'); - }, - deps: [Router], - }, - ], - }), - ); - it('works', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const recordedEvents: Event[] = []; @@ -402,7 +332,11 @@ export function guardsIntegrationSuite() { }); router.resetConfig([ {path: '', component: SimpleCmp}, - {path: 'one', component: RouteCmp, canActivate: ['returnUrlTree']}, + { + path: 'one', + component: RouteCmp, + canActivate: [() => coreInject(Router).parseUrl('/redirected')], + }, {path: 'redirected', component: SimpleCmp}, ]); @@ -448,7 +382,11 @@ export function guardsIntegrationSuite() { }); router.resetConfig([ {path: '', component: SimpleCmp}, - {path: 'one', component: RouteCmp, canActivate: ['returnRootUrlTree']}, + { + path: 'one', + component: RouteCmp, + canActivate: [() => coreInject(Router).parseUrl('/')], + }, ]); const fixture = TestBed.createComponent(RootCmp); @@ -491,7 +429,11 @@ export function guardsIntegrationSuite() { const location = TestBed.inject(Location); router.resetConfig([ {path: '', component: SimpleCmp}, - {path: 'one', component: RouteCmp, canActivate: ['returnUrlTree']}, + { + path: 'one', + component: RouteCmp, + canActivate: [() => coreInject(Router).parseUrl('/redirected')], + }, {path: 'redirected', component: SimpleCmp}, ]); createRoot(router, RootCmp); @@ -519,7 +461,11 @@ export function guardsIntegrationSuite() { let resolvedPath = ''; router.resetConfig([ {path: '', component: SimpleCmp}, - {path: 'one', component: RouteCmp, canActivate: ['returnUrlTree']}, + { + path: 'one', + component: RouteCmp, + canActivate: [() => coreInject(Router).parseUrl('/redirected')], + }, {path: 'redirected', component: SimpleCmp}, ]); const fixture = createRoot(router, RootCmp); @@ -655,16 +601,7 @@ export function guardsIntegrationSuite() { guardRunCount = 0; resolverRunCount = 0; TestBed.configureTestingModule({ - providers: [ - { - provide: 'guard', - useValue: () => { - guardRunCount++; - return true; - }, - }, - {provide: 'resolver', useValue: () => resolverRunCount++}, - ], + providers: [{provide: 'resolver', useValue: () => resolverRunCount++}], }); }); @@ -679,7 +616,12 @@ export function guardsIntegrationSuite() { path: 'a', runGuardsAndResolvers, component: RouteCmp, - canActivate: ['guard'], + canActivate: [ + () => { + guardRunCount++; + return true; + }, + ], resolve: {data: 'resolver'}, }, {path: 'b', component: SimpleCmp, outlet: 'right'}, @@ -687,7 +629,12 @@ export function guardsIntegrationSuite() { path: 'c/:param', runGuardsAndResolvers, component: RouteCmp, - canActivate: ['guard'], + canActivate: [ + () => { + guardRunCount++; + return true; + }, + ], resolve: {data: 'resolver'}, }, { @@ -698,7 +645,12 @@ export function guardsIntegrationSuite() { { path: 'e/:param', component: SimpleCmp, - canActivate: ['guard'], + canActivate: [ + () => { + guardRunCount++; + return true; + }, + ], resolve: {data: 'resolver'}, }, ], @@ -707,7 +659,12 @@ export function guardsIntegrationSuite() { path: 'throwing', runGuardsAndResolvers, component: ThrowingCmp, - canActivate: ['guard'], + canActivate: [ + () => { + guardRunCount++; + return true; + }, + ], resolve: {data: 'resolver'}, }, ]); @@ -978,28 +935,6 @@ export function guardsIntegrationSuite() { beforeEach(() => { log = []; - TestBed.configureTestingModule({ - providers: [ - { - provide: 'parentGuard', - useValue: () => { - return delayPromise(10).then(() => { - log.push('parent'); - return true; - }); - }, - }, - { - provide: 'childGuard', - useValue: () => { - return delayPromise(5).then(() => { - log.push('child'); - return true; - }); - }, - }, - ], - }); }); function delayPromise(delay: number): Promise { @@ -1016,8 +951,27 @@ export function guardsIntegrationSuite() { router.resetConfig([ { path: 'parent', - canActivate: ['parentGuard'], - children: [{path: 'child', component: SimpleCmp, canActivate: ['childGuard']}], + canActivate: [ + () => + delayPromise(10).then(() => { + log.push('parent'); + return true; + }), + ], + children: [ + { + path: 'child', + component: SimpleCmp, + canActivate: [ + () => { + return delayPromise(5).then(() => { + log.push('child'); + return true; + }); + }, + ], + }, + ], }, ]); @@ -1032,69 +986,13 @@ export function guardsIntegrationSuite() { describe('CanDeactivate', () => { let log: any; + const recordingDeactivate: CanDeactivateFn = (c, a) => { + log.push({path: a.routeConfig!.path, component: c}); + return true; + }; beforeEach(() => { log = []; - - TestBed.configureTestingModule({ - providers: [ - { - provide: 'CanDeactivateParent', - useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { - return a.params['id'] === '22'; - }, - }, - { - provide: 'CanDeactivateTeam', - useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { - return c.route.snapshot.params['id'] === '22'; - }, - }, - { - provide: 'CanDeactivateUser', - useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { - return a.params['name'] === 'victor'; - }, - }, - { - provide: 'RecordingDeactivate', - useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { - log.push({path: a.routeConfig!.path, component: c}); - return true; - }, - }, - { - provide: 'alwaysFalse', - useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { - return false; - }, - }, - { - provide: 'alwaysFalseAndLogging', - useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { - log.push('called'); - return false; - }, - }, - { - provide: 'alwaysFalseWithDelayAndLogging', - useValue: () => { - log.push('called'); - let resolve: (result: boolean) => void; - const promise = new Promise((res) => (resolve = res)); - setTimeout(() => resolve(false), 0); - return promise; - }, - }, - { - provide: 'canActivate_alwaysTrueAndLogging', - useValue: () => { - log.push('canActivate called'); - return true; - }, - }, - ], - }); }); describe('should not deactivate a route when CanDeactivate returns false', () => { @@ -1103,7 +1001,15 @@ export function guardsIntegrationSuite() { const fixture = createRoot(router, RootCmp); router.resetConfig([ - {path: 'team/:id', component: TeamCmp, canDeactivate: ['CanDeactivateTeam']}, + { + path: 'team/:id', + component: TeamCmp, + canDeactivate: [ + (c, a) => { + return a.params['id'] === '22'; + }, + ], + }, ]); router.navigateByUrl('/team/22'); @@ -1131,20 +1037,20 @@ export function guardsIntegrationSuite() { router.resetConfig([ { path: 'grandparent', - canDeactivate: ['RecordingDeactivate'], + canDeactivate: [recordingDeactivate], children: [ { path: 'parent', - canDeactivate: ['RecordingDeactivate'], + canDeactivate: [recordingDeactivate], children: [ { path: 'child', - canDeactivate: ['RecordingDeactivate'], + canDeactivate: [recordingDeactivate], children: [ { path: 'simple', component: SimpleCmp, - canDeactivate: ['RecordingDeactivate'], + canDeactivate: [recordingDeactivate], }, ], }, @@ -1189,7 +1095,7 @@ export function guardsIntegrationSuite() { {path: 'a', component: BlankCmp}, { path: 'b', - canDeactivate: ['RecordingDeactivate'], + canDeactivate: [recordingDeactivate], component: SimpleCmp, outlet: 'aux', }, @@ -1219,7 +1125,15 @@ export function guardsIntegrationSuite() { component: TeamCmp, children: [ {path: '', pathMatch: 'full', component: SimpleCmp}, - {path: 'user/:name', component: UserCmp, canDeactivate: ['CanDeactivateUser']}, + { + path: 'user/:name', + component: UserCmp, + canDeactivate: [ + (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { + return a.params['name'] === 'victor'; + }, + ], + }, ], }, ]); @@ -1259,7 +1173,7 @@ export function guardsIntegrationSuite() { { path: '', component: AdminComponent, - canDeactivate: ['RecordingDeactivate'], + canDeactivate: [recordingDeactivate], }, ]), ], @@ -1295,7 +1209,7 @@ export function guardsIntegrationSuite() { path: 'main', component: TeamCmp, children: [ - {path: 'component1', component: SimpleCmp, canDeactivate: ['alwaysFalse']}, + {path: 'component1', component: SimpleCmp, canDeactivate: [() => false]}, {path: 'component2', component: SimpleCmp}, ], }, @@ -1325,12 +1239,25 @@ export function guardsIntegrationSuite() { { path: 'component1', component: SimpleCmp, - canDeactivate: ['alwaysFalseWithDelayAndLogging'], + canDeactivate: [ + () => { + log.push('called'); + let resolve: (result: boolean) => void; + const promise = new Promise((res) => (resolve = res)); + setTimeout(() => resolve(false), 0); + return promise; + }, + ], }, { path: 'component2', component: SimpleCmp, - canActivate: ['canActivate_alwaysTrueAndLogging'], + canActivate: [ + () => { + log.push('canActivate called'); + return true; + }, + ], }, ], }, @@ -1352,7 +1279,16 @@ export function guardsIntegrationSuite() { const fixture = createRoot(router, RootCmp); router.resetConfig([ - {path: 'simple', component: SimpleCmp, canDeactivate: ['alwaysFalseAndLogging']}, + { + path: 'simple', + component: SimpleCmp, + canDeactivate: [ + () => { + log.push('called'); + return false; + }, + ], + }, {path: 'blank', component: BlankCmp}, ]); @@ -1389,21 +1325,7 @@ export function guardsIntegrationSuite() { beforeEach(() => { log = []; TestBed.configureTestingModule({ - providers: [ - ClassWithNextState, - { - provide: 'FunctionWithNextState', - useValue: ( - cmp: any, - currentRoute: ActivatedRouteSnapshot, - currentState: RouterStateSnapshot, - nextState: RouterStateSnapshot, - ) => { - log.push(currentState.url, nextState.url); - return true; - }, - }, - ], + providers: [ClassWithNextState], }); }); @@ -1448,7 +1370,16 @@ export function guardsIntegrationSuite() { const fixture = createRoot(router, RootCmp); router.resetConfig([ - {path: 'team/:id', component: TeamCmp, canDeactivate: ['FunctionWithNextState']}, + { + path: 'team/:id', + component: TeamCmp, + canDeactivate: [ + (cmp, currentRoute, currentState, nextState) => { + log.push(currentState.url, nextState.url); + return true; + }, + ], + }, ]); router.navigateByUrl('/team/22'); @@ -1498,27 +1429,22 @@ export function guardsIntegrationSuite() { }); describe('should work when returns an observable', () => { - beforeEach(() => { - TestBed.configureTestingModule({ - providers: [ - { - provide: 'CanDeactivate', - useValue: (c: TeamCmp, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { - return new Observable((observer) => { - observer.next(false); - }); - }, - }, - ], - }); - }); - it('works', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ - {path: 'team/:id', component: TeamCmp, canDeactivate: ['CanDeactivate']}, + { + path: 'team/:id', + component: TeamCmp, + canDeactivate: [ + () => { + return new Observable((observer) => { + observer.next(false); + }); + }, + ], + }, ]); router.navigateByUrl('/team/22'); @@ -1535,17 +1461,6 @@ export function guardsIntegrationSuite() { describe('CanActivateChild', () => { describe('should be invoked when activating a child', () => { - beforeEach(() => { - TestBed.configureTestingModule({ - providers: [ - { - provide: 'alwaysFalse', - useValue: (a: any, b: any) => a.paramMap.get('id') === '22', - }, - ], - }); - }); - it('works', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); @@ -1553,7 +1468,7 @@ export function guardsIntegrationSuite() { router.resetConfig([ { path: '', - canActivateChild: ['alwaysFalse'], + canActivateChild: [(a: any) => a.paramMap.get('id') === '22'], children: [{path: 'team/:id', component: TeamCmp}], }, ]); @@ -1597,14 +1512,13 @@ export function guardsIntegrationSuite() { children: [ { path: '', - canActivateChild: ['alwaysTrue'], + canActivateChild: [() => true], children: [{path: '', component: LazyLoadedComponent}], }, ], }, ]), ], - providers: [{provide: 'alwaysTrue', useValue: () => true}], }) class LazyLoadedModule {} @@ -1627,24 +1541,8 @@ export function guardsIntegrationSuite() { canLoadRunCount = 0; TestBed.configureTestingModule({ providers: [ - {provide: 'alwaysFalse', useValue: (a: any) => false}, { - provide: 'returnUrlTree', - useFactory: (router: Router) => () => { - return router.createUrlTree(['blank']); - }, - deps: [Router], - }, - { - provide: 'returnFalseAndNavigate', - useFactory: (router: Router) => (a: any) => { - router.navigate(['blank']); - return false; - }, - deps: [Router], - }, - { - provide: 'alwaysTrue', + provide: () => true, useValue: () => { canLoadRunCount++; return true; @@ -1672,8 +1570,8 @@ export function guardsIntegrationSuite() { const fixture = createRoot(router, RootCmp); router.resetConfig([ - {path: 'lazyFalse', canLoad: ['alwaysFalse'], loadChildren: () => LoadedModule}, - {path: 'lazyTrue', canLoad: ['alwaysTrue'], loadChildren: () => LoadedModule}, + {path: 'lazyFalse', canLoad: [() => false], loadChildren: () => LoadedModule}, + {path: 'lazyTrue', canLoad: [() => true], loadChildren: () => LoadedModule}, ]); const recordedEvents: Event[] = []; @@ -1732,7 +1630,12 @@ export function guardsIntegrationSuite() { router.resetConfig([ { path: 'lazyFalse', - canLoad: ['returnFalseAndNavigate'], + canLoad: [ + () => { + router.navigate(['blank']); + return false; + }, + ], loadChildren: jasmine.createSpy('lazyFalse'), }, {path: 'blank', component: BlankCmp}, @@ -1778,7 +1681,7 @@ export function guardsIntegrationSuite() { router.resetConfig([ { path: 'lazyFalse', - canLoad: ['returnUrlTree'], + canLoad: [() => coreInject(Router).createUrlTree(['blank'])], loadChildren: jasmine.createSpy('lazyFalse'), }, {path: 'blank', component: BlankCmp}, @@ -1837,8 +1740,8 @@ export function guardsIntegrationSuite() { const fixture = createRoot(router, RootCmp); router.resetConfig([ - {path: 'lazy-false', canLoad: ['alwaysFalse'], loadChildren: () => LazyLoadedModule}, - {path: 'lazy-true', canLoad: ['alwaysTrue'], loadChildren: () => LazyLoadedModule}, + {path: 'lazy-false', canLoad: [() => false], loadChildren: () => LazyLoadedModule}, + {path: 'lazy-true', canLoad: [() => true], loadChildren: () => LazyLoadedModule}, ]); let navFalseResult = true; @@ -1875,7 +1778,16 @@ export function guardsIntegrationSuite() { const fixture = createRoot(router, RootCmp); router.resetConfig([ - {path: 'lazy', canLoad: ['alwaysTrue'], loadChildren: () => LazyLoadedModule}, + { + path: 'lazy', + canLoad: [ + () => { + canLoadRunCount++; + return true; + }, + ], + loadChildren: () => LazyLoadedModule, + }, ]); router.navigateByUrl('/lazy/loaded'); @@ -1935,51 +1847,31 @@ export function guardsIntegrationSuite() { } let log: string[]; + const guard1 = () => { + return delayObservable(5).pipe(tap({next: () => log.push('guard1')})); + }; + const guard2 = () => { + return delayObservable(0).pipe(tap({next: () => log.push('guard2')})); + }; + const returnFalse = () => { + log.push('returnFalse'); + return false; + }; + const returnFalseAndNavigate = () => { + log.push('returnFalseAndNavigate'); + coreInject(Router).navigateByUrl('/redirected'); + return false; + }; + const returnUrlTree = () => { + const router = coreInject(Router); + return delayObservable(15).pipe( + mapTo(router.parseUrl('/redirected')), + tap({next: () => log.push('returnUrlTree')}), + ); + }; beforeEach(() => { log = []; - TestBed.configureTestingModule({ - providers: [ - { - provide: 'guard1', - useValue: () => { - return delayObservable(5).pipe(tap({next: () => log.push('guard1')})); - }, - }, - { - provide: 'guard2', - useValue: () => { - return delayObservable(0).pipe(tap({next: () => log.push('guard2')})); - }, - }, - { - provide: 'returnFalse', - useValue: () => { - log.push('returnFalse'); - return false; - }, - }, - { - provide: 'returnFalseAndNavigate', - useFactory: (router: Router) => () => { - log.push('returnFalseAndNavigate'); - router.navigateByUrl('/redirected'); - return false; - }, - deps: [Router], - }, - { - provide: 'returnUrlTree', - useFactory: (router: Router) => () => { - return delayObservable(15).pipe( - mapTo(router.parseUrl('/redirected')), - tap({next: () => log.push('returnUrlTree')}), - ); - }, - deps: [Router], - }, - ], - }); }); it('should only execute canLoad guards of routes being activated', fakeAsync(() => { @@ -1988,14 +1880,14 @@ export function guardsIntegrationSuite() { router.resetConfig([ { path: 'lazy', - canLoad: ['guard1'], + canLoad: [guard1], loadChildren: () => of(ModuleWithBlankCmpAsRoute), }, {path: 'redirected', component: SimpleCmp}, // canLoad should not run for this route because 'lazy' activates first { path: '', - canLoad: ['returnFalseAndNavigate'], + canLoad: [returnFalseAndNavigate], loadChildren: () => of(ModuleWithBlankCmpAsRoute), }, ]); @@ -2011,7 +1903,7 @@ export function guardsIntegrationSuite() { router.resetConfig([ { path: 'lazy', - canLoad: ['guard1', 'guard2'], + canLoad: [guard1, guard2], loadChildren: () => ModuleWithBlankCmpAsRoute, }, ]); @@ -2029,7 +1921,7 @@ export function guardsIntegrationSuite() { router.resetConfig([ { path: 'lazy', - canLoad: ['returnUrlTree', 'guard1', 'guard2'], + canLoad: [returnUrlTree, guard1, guard2], loadChildren: () => ModuleWithBlankCmpAsRoute, }, {path: 'redirected', component: SimpleCmp}, @@ -2049,7 +1941,7 @@ export function guardsIntegrationSuite() { router.resetConfig([ { path: 'lazy', - canLoad: ['guard1', 'returnUrlTree'], + canLoad: [guard1, returnUrlTree], loadChildren: () => ModuleWithBlankCmpAsRoute, }, {path: 'redirected', component: SimpleCmp}, @@ -2072,48 +1964,25 @@ export function guardsIntegrationSuite() { this.logs.push(thing); } } - beforeEach(() => { TestBed.configureTestingModule({ - providers: [ - Logger, - { - provide: 'canActivateChild_parent', - useFactory: (logger: Logger) => () => (logger.add('canActivateChild_parent'), true), - deps: [Logger], - }, - { - provide: 'canActivate_team', - useFactory: (logger: Logger) => () => (logger.add('canActivate_team'), true), - deps: [Logger], - }, - { - provide: 'canDeactivate_team', - useFactory: (logger: Logger) => () => (logger.add('canDeactivate_team'), true), - deps: [Logger], - }, - { - provide: 'canDeactivate_simple', - useFactory: (logger: Logger) => () => (logger.add('canDeactivate_simple'), true), - deps: [Logger], - }, - ], + providers: [Logger], }); }); it('should call guards in the right order', fakeAsync( - inject([Router, Location, Logger], (router: Router, location: Location, logger: Logger) => { + inject([Router, Logger], (router: Router, logger: Logger) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: '', - canActivateChild: ['canActivateChild_parent'], + canActivateChild: [() => (logger.add('canActivateChild_parent'), true)], children: [ { path: 'team/:id', - canActivate: ['canActivate_team'], - canDeactivate: ['canDeactivate_team'], + canActivate: [() => (logger.add('canActivate_team'), true)], + canDeactivate: [() => (logger.add('canDeactivate_team'), true)], component: TeamCmp, }, ], @@ -2138,7 +2007,7 @@ export function guardsIntegrationSuite() { )); it('should call deactivate guards from bottom to top', fakeAsync( - inject([Router, Location, Logger], (router: Router, location: Location, logger: Logger) => { + inject([Router, Logger], (router: Router, logger: Logger) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ @@ -2147,9 +2016,13 @@ export function guardsIntegrationSuite() { children: [ { path: 'team/:id', - canDeactivate: ['canDeactivate_team'], + canDeactivate: [() => (logger.add('canDeactivate_team'), true)], children: [ - {path: '', component: SimpleCmp, canDeactivate: ['canDeactivate_simple']}, + { + path: '', + component: SimpleCmp, + canDeactivate: [() => (logger.add('canDeactivate_simple'), true)], + }, ], component: TeamCmp, }, diff --git a/packages/router/test/integration/lazy_loading.spec.ts b/packages/router/test/integration/lazy_loading.spec.ts index 0f1a733edd1..6df83186267 100644 --- a/packages/router/test/integration/lazy_loading.spec.ts +++ b/packages/router/test/integration/lazy_loading.spec.ts @@ -769,16 +769,7 @@ export function lazyLoadingIntegrationSuite() { beforeEach(() => { log.length = 0; TestBed.configureTestingModule({ - providers: [ - {provide: PreloadingStrategy, useExisting: PreloadAllModules}, - { - provide: 'loggingReturnsTrue', - useValue: () => { - log.push('loggingReturnsTrue'); - return true; - }, - }, - ], + providers: [{provide: PreloadingStrategy, useExisting: PreloadAllModules}], }); const preloader = TestBed.inject(RouterPreloader); preloader.setUpPreloading(); @@ -813,7 +804,16 @@ export function lazyLoadingIntegrationSuite() { router.resetConfig([ {path: 'blank', component: BlankCmp}, - {path: 'lazy', loadChildren: () => LoadedModule1, canLoad: ['loggingReturnsTrue']}, + { + path: 'lazy', + loadChildren: () => LoadedModule1, + canLoad: [ + () => { + log.push('loggingReturnsTrue'); + return true; + }, + ], + }, ]); router.navigateByUrl('/blank'); diff --git a/packages/router/test/integration/navigation.spec.ts b/packages/router/test/integration/navigation.spec.ts index 3d09ac64f54..70f7eb4fb55 100644 --- a/packages/router/test/integration/navigation.spec.ts +++ b/packages/router/test/integration/navigation.spec.ts @@ -445,31 +445,6 @@ export function navigationIntegrationTestSuite() { beforeEach(() => { log = []; - - TestBed.configureTestingModule({ - providers: [ - { - provide: 'trueRightAway', - useValue: () => { - log.push('trueRightAway'); - return true; - }, - }, - { - provide: 'trueIn2Seconds', - useValue: () => { - log.push('trueIn2Seconds-start'); - let res: (value: boolean) => void; - const p = new Promise((r) => (res = r)); - setTimeout(() => { - log.push('trueIn2Seconds-end'); - res(true); - }, 2000); - return p; - }, - }, - ], - }); }); describe('route activation', () => { @@ -680,10 +655,22 @@ export function navigationIntegrationTestSuite() { it('should not wait for prior navigations to start a new navigation', fakeAsync( inject([Router, Location], (router: Router) => { const fixture = createRoot(router, RootCmp); - + const trueRightAway = () => { + log.push('trueRightAway'); + return true; + }; + const trueIn2Seconds = () => { + log.push('trueIn2Seconds-start'); + return new Promise((res) => { + setTimeout(() => { + log.push('trueIn2Seconds-end'); + res(true); + }, 2000); + }); + }; router.resetConfig([ - {path: 'a', component: SimpleCmp, canActivate: ['trueRightAway', 'trueIn2Seconds']}, - {path: 'b', component: SimpleCmp, canActivate: ['trueRightAway', 'trueIn2Seconds']}, + {path: 'a', component: SimpleCmp, canActivate: [trueRightAway, trueIn2Seconds]}, + {path: 'b', component: SimpleCmp, canActivate: [trueRightAway, trueIn2Seconds]}, ]); router.navigateByUrl('/a'); diff --git a/packages/router/test/integration/navigation_errors.spec.ts b/packages/router/test/integration/navigation_errors.spec.ts index 5abc4917668..29876dd5ff7 100644 --- a/packages/router/test/integration/navigation_errors.spec.ts +++ b/packages/router/test/integration/navigation_errors.spec.ts @@ -352,10 +352,6 @@ export function navigationErrorsIntegrationSuite() { }); it('should dispatch NavigationCancel after the url has been reset back', fakeAsync(() => { - TestBed.configureTestingModule({ - providers: [{provide: 'returnsFalse', useValue: () => false}], - }); - const router: Router = TestBed.inject(Router); const location = TestBed.inject(Location); @@ -366,7 +362,7 @@ export function navigationErrorsIntegrationSuite() { { path: 'throwing', loadChildren: jasmine.createSpy('doesnotmatter'), - canLoad: ['returnsFalse'], + canLoad: [() => false], }, ]); diff --git a/packages/router/test/integration/route_data.spec.ts b/packages/router/test/integration/route_data.spec.ts index 15c3d3c4d41..b4705663b49 100644 --- a/packages/router/test/integration/route_data.spec.ts +++ b/packages/router/test/integration/route_data.spec.ts @@ -71,13 +71,6 @@ export function routeDataIntegrationSuite() { {provide: 'resolveNullError', useValue: (a: any, b: any) => Promise.reject(null)}, {provide: 'resolveEmpty', useValue: (a: any, b: any) => EMPTY}, {provide: 'numberOfUrlSegments', useValue: (a: any, b: any) => a.url.length}, - { - provide: 'overridingGuard', - useValue: (route: ActivatedRouteSnapshot) => { - route.data = {prop: 10}; - return true; - }, - }, ], }); }); @@ -596,7 +589,12 @@ export function routeDataIntegrationSuite() { { path: 'route', component: NestedComponentWithData, - canActivate: ['overridingGuard'], + canActivate: [ + (route: ActivatedRouteSnapshot) => { + route.data = {prop: 10}; + return true; + }, + ], }, ]); diff --git a/packages/router/test/regression_integration.spec.ts b/packages/router/test/regression_integration.spec.ts index 0845ca04dd4..d80a3e019fd 100644 --- a/packages/router/test/regression_integration.spec.ts +++ b/packages/router/test/regression_integration.spec.ts @@ -18,6 +18,7 @@ import { Type, ViewChild, ViewContainerRef, + inject, } from '@angular/core'; import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'; import { @@ -294,20 +295,11 @@ describe('Integration', () => { imports: [ RouterModule.forRoot([ {path: '', component: SimpleCmp}, - {path: 'one', component: OneCmp, canActivate: ['returnRootUrlTree']}, + {path: 'one', component: OneCmp, canActivate: [() => inject(Router).parseUrl('/')]}, ]), ], declarations: [SimpleCmp, RootCmp, OneCmp], - providers: [ - provideLocationMocks(), - { - provide: 'returnRootUrlTree', - useFactory: (router: Router) => () => { - return router.parseUrl('/'); - }, - deps: [Router], - }, - ], + providers: [provideLocationMocks()], }); const router = TestBed.inject(Router); diff --git a/packages/router/test/router.spec.ts b/packages/router/test/router.spec.ts index 5685ba1a76c..d39e9c0e852 100644 --- a/packages/router/test/router.spec.ts +++ b/packages/router/test/router.spec.ts @@ -7,7 +7,7 @@ */ import {Location} from '@angular/common'; -import {EnvironmentInjector} from '@angular/core'; +import {EnvironmentInjector, inject as coreInject} from '@angular/core'; import {inject, TestBed} from '@angular/core/testing'; import {RouterModule} from '@angular/router'; import {of} from 'rxjs'; @@ -24,7 +24,7 @@ import {DefaultUrlSerializer, UrlTree} from '../src/url_tree'; import {getAllRouteGuards} from '../src/utils/preactivation'; import {TreeNode} from '../src/utils/tree'; -import {createActivatedRouteSnapshot, Logger, provideTokenLogger} from './helpers'; +import {createActivatedRouteSnapshot, Logger} from './helpers'; describe('Router', () => { describe('resetConfig', () => { @@ -110,54 +110,44 @@ describe('Router', () => { const serializer = new DefaultUrlSerializer(); let empty: RouterStateSnapshot; let logger: Logger; + + function createLoggerGuard(token: string, returnValue = true as boolean | UrlTree) { + return () => { + coreInject(Logger).add(token); + return returnValue; + }; + } let events: any[]; - const CA_CHILD = 'canActivate_child'; - const CA_CHILD_FALSE = 'canActivate_child_false'; - const CA_CHILD_REDIRECT = 'canActivate_child_redirect'; - const CAC_CHILD = 'canActivateChild_child'; - const CAC_CHILD_FALSE = 'canActivateChild_child_false'; - const CAC_CHILD_REDIRECT = 'canActivateChild_child_redirect'; - const CA_GRANDCHILD = 'canActivate_grandchild'; - const CA_GRANDCHILD_FALSE = 'canActivate_grandchild_false'; - const CA_GRANDCHILD_REDIRECT = 'canActivate_grandchild_redirect'; - const CDA_CHILD = 'canDeactivate_child'; - const CDA_CHILD_FALSE = 'canDeactivate_child_false'; - const CDA_CHILD_REDIRECT = 'canDeactivate_child_redirect'; - const CDA_GRANDCHILD = 'canDeactivate_grandchild'; - const CDA_GRANDCHILD_FALSE = 'canDeactivate_grandchild_false'; - const CDA_GRANDCHILD_REDIRECT = 'canDeactivate_grandchild_redirect'; + const CA_CHILD = createLoggerGuard('canActivate_child'); + const CA_CHILD_FALSE = createLoggerGuard('canActivate_child_false', false); + const CA_CHILD_REDIRECT = createLoggerGuard( + 'canActivate_child_redirect', + serializer.parse('/canActivate_child_redirect'), + ); + const CAC_CHILD = createLoggerGuard('canActivateChild_child'); + const CAC_CHILD_FALSE = createLoggerGuard('canActivateChild_child_false', false); + const CAC_CHILD_REDIRECT = createLoggerGuard( + 'canActivateChild_child_redirect', + serializer.parse('/canActivateChild_child_redirect'), + ); + const CA_GRANDCHILD = createLoggerGuard('canActivate_grandchild'); + const CA_GRANDCHILD_REDIRECT = createLoggerGuard( + 'canActivate_grandchild_redirect', + serializer.parse('/canActivate_grandchild_redirect'), + ); + const CDA_CHILD = createLoggerGuard('canDeactivate_child'); + const CDA_CHILD_FALSE = createLoggerGuard('canDeactivate_child_false', false); + const CDA_CHILD_REDIRECT = createLoggerGuard( + 'canDeactivate_child_redirect', + serializer.parse('/canDeactivate_child_redirect'), + ); + const CDA_GRANDCHILD = createLoggerGuard('canDeactivate_grandchild'); beforeEach(() => { TestBed.configureTestingModule({ imports: [RouterModule], - providers: [ - Logger, - provideTokenLogger(CA_CHILD), - provideTokenLogger(CA_CHILD_FALSE, false), - provideTokenLogger(CA_CHILD_REDIRECT, serializer.parse('/canActivate_child_redirect')), - provideTokenLogger(CAC_CHILD), - provideTokenLogger(CAC_CHILD_FALSE, false), - provideTokenLogger( - CAC_CHILD_REDIRECT, - serializer.parse('/canActivateChild_child_redirect'), - ), - provideTokenLogger(CA_GRANDCHILD), - provideTokenLogger(CA_GRANDCHILD_FALSE, false), - provideTokenLogger( - CA_GRANDCHILD_REDIRECT, - serializer.parse('/canActivate_grandchild_redirect'), - ), - provideTokenLogger(CDA_CHILD), - provideTokenLogger(CDA_CHILD_FALSE, false), - provideTokenLogger(CDA_CHILD_REDIRECT, serializer.parse('/canDeactivate_child_redirect')), - provideTokenLogger(CDA_GRANDCHILD), - provideTokenLogger(CDA_GRANDCHILD_FALSE, false), - provideTokenLogger( - CDA_GRANDCHILD_REDIRECT, - serializer.parse('/canDeactivate_grandchild_redirect'), - ), - ], + providers: [Logger], }); }); @@ -440,7 +430,11 @@ describe('Router', () => { checkGuards(futureState, empty, TestBed.inject(EnvironmentInjector), (result) => { expect(result).toBe(true); - expect(logger.logs).toEqual([CA_CHILD, CAC_CHILD, CA_GRANDCHILD]); + expect(logger.logs).toEqual([ + 'canActivate_child', + 'canActivateChild_child', + 'canActivate_grandchild', + ]); }); }); @@ -471,7 +465,7 @@ describe('Router', () => { checkGuards(futureState, empty, TestBed.inject(EnvironmentInjector), (result) => { expect(result).toBe(false); - expect(logger.logs).toEqual([CA_CHILD_FALSE]); + expect(logger.logs).toEqual(['canActivate_child_false']); }); }); @@ -502,7 +496,7 @@ describe('Router', () => { checkGuards(futureState, empty, TestBed.inject(EnvironmentInjector), (result) => { expect(result).toBe(false); - expect(logger.logs).toEqual([CA_CHILD, CAC_CHILD_FALSE]); + expect(logger.logs).toEqual(['canActivate_child', 'canActivateChild_child_false']); }); }); @@ -543,7 +537,12 @@ describe('Router', () => { ); checkGuards(futureState, currentState, TestBed.inject(EnvironmentInjector), (result) => { - expect(logger.logs).toEqual([CDA_CHILD, CA_CHILD, CAC_CHILD, CA_GRANDCHILD]); + expect(logger.logs).toEqual([ + 'canDeactivate_child', + 'canActivate_child', + 'canActivateChild_child', + 'canActivate_grandchild', + ]); }); }); @@ -582,7 +581,7 @@ describe('Router', () => { checkGuards(futureState, currentState, TestBed.inject(EnvironmentInjector), (result) => { expect(result).toBe(false); - expect(logger.logs).toEqual([CDA_CHILD_FALSE]); + expect(logger.logs).toEqual(['canDeactivate_child_false']); }); }); it('should deactivate from bottom up, then activate top down', () => { @@ -628,11 +627,11 @@ describe('Router', () => { checkGuards(futureState, currentState, TestBed.inject(EnvironmentInjector), (result) => { expect(result).toBe(true); expect(logger.logs).toEqual([ - CDA_GRANDCHILD, - CDA_CHILD, - CA_CHILD, - CAC_CHILD, - CA_GRANDCHILD, + 'canDeactivate_grandchild', + 'canDeactivate_child', + 'canActivate_child', + 'canActivateChild_child', + 'canActivate_grandchild', ]); }); @@ -664,8 +663,10 @@ describe('Router', () => { ); checkGuards(futureState, empty, TestBed.inject(EnvironmentInjector), (result) => { - expect(serializer.serialize(result as UrlTree)).toBe('/' + CA_CHILD_REDIRECT); - expect(logger.logs).toEqual([CA_CHILD_REDIRECT]); + expect(serializer.serialize(result as UrlTree)).toBe( + '/' + 'canActivate_child_redirect', + ); + expect(logger.logs).toEqual(['canActivate_child_redirect']); }); }); @@ -695,8 +696,10 @@ describe('Router', () => { ); checkGuards(futureState, empty, TestBed.inject(EnvironmentInjector), (result) => { - expect(serializer.serialize(result as UrlTree)).toBe('/' + CAC_CHILD_REDIRECT); - expect(logger.logs).toEqual([CAC_CHILD_REDIRECT]); + expect(serializer.serialize(result as UrlTree)).toBe( + '/' + 'canActivateChild_child_redirect', + ); + expect(logger.logs).toEqual(['canActivateChild_child_redirect']); }); }); @@ -726,8 +729,13 @@ describe('Router', () => { ); checkGuards(futureState, empty, TestBed.inject(EnvironmentInjector), (result) => { - expect(serializer.serialize(result as UrlTree)).toBe('/' + CA_GRANDCHILD_REDIRECT); - expect(logger.logs).toEqual([CAC_CHILD, CA_GRANDCHILD_REDIRECT]); + expect(serializer.serialize(result as UrlTree)).toBe( + '/' + 'canActivate_grandchild_redirect', + ); + expect(logger.logs).toEqual([ + 'canActivateChild_child', + 'canActivate_grandchild_redirect', + ]); }); }); @@ -765,8 +773,10 @@ describe('Router', () => { ); checkGuards(futureState, currentState, TestBed.inject(EnvironmentInjector), (result) => { - expect(serializer.serialize(result as UrlTree)).toBe('/' + CDA_CHILD_REDIRECT); - expect(logger.logs).toEqual([CDA_CHILD_REDIRECT]); + expect(serializer.serialize(result as UrlTree)).toBe( + '/' + 'canDeactivate_child_redirect', + ); + expect(logger.logs).toEqual(['canDeactivate_child_redirect']); }); }); }); diff --git a/packages/router/test/router_preloader.spec.ts b/packages/router/test/router_preloader.spec.ts index 85f9ea27dd8..ed04536b7ff 100644 --- a/packages/router/test/router_preloader.spec.ts +++ b/packages/router/test/router_preloader.spec.ts @@ -52,7 +52,7 @@ describe('RouterPreloader', () => { providers: [ provideLocationMocks(), provideRouter( - [{path: 'lazy', loadChildren: jasmine.createSpy('expected'), canLoad: ['someGuard']}], + [{path: 'lazy', loadChildren: jasmine.createSpy('expected'), canLoad: [() => true]}], withPreloading(PreloadAllModules), ), ], @@ -85,7 +85,7 @@ describe('RouterPreloader', () => { providers: [ provideLocationMocks(), provideRouter( - [{path: 'lazy', loadChildren: () => LoadedModule, canLoad: ['someGuard']}], + [{path: 'lazy', loadChildren: () => LoadedModule, canLoad: [() => true]}], withPreloading(PreloadAllModules), ), ],