_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/platform-browser/src/dom/events/hammer_gestures.ts_8290_8988
** * Adds support for HammerJS. * * Import this module at the root of your application so that Angular can work with * HammerJS to detect gesture events. * * Note that applications still need to include the HammerJS script itself. This module * simply sets up the coordination layer between HammerJS and Angular's `EventManager`. * * @publicApi */ @NgModule({ providers: [ { provide: EVENT_MANAGER_PLUGINS, useClass: HammerGesturesPlugin, multi: true, deps: [DOCUMENT, HAMMER_GESTURE_CONFIG, Console, [new Optional(), HAMMER_LOADER]], }, {provide: HAMMER_GESTURE_CONFIG, useClass: HammerGestureConfig, deps: []}, ], }) export class HammerModule {}
{ "end_byte": 8988, "start_byte": 8290, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/dom/events/hammer_gestures.ts" }
angular/packages/platform-browser/src/dom/debug/by.ts_0_1704
/** * @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.dev/license */ import {ɵgetDOM as getDOM} from '@angular/common'; import {DebugElement, DebugNode, Predicate, Type} from '@angular/core'; /** * Predicates for use with {@link DebugElement}'s query functions. * * @publicApi */ export class By { /** * Match all nodes. * * @usageNotes * ### Example * * {@example platform-browser/dom/debug/ts/by/by.ts region='by_all'} */ static all(): Predicate<DebugNode> { return () => true; } /** * Match elements by the given CSS selector. * * @usageNotes * ### Example * * {@example platform-browser/dom/debug/ts/by/by.ts region='by_css'} */ static css(selector: string): Predicate<DebugElement> { return (debugElement) => { return debugElement.nativeElement != null ? elementMatches(debugElement.nativeElement, selector) : false; }; } /** * Match nodes that have the given directive present. * * @usageNotes * ### Example * * {@example platform-browser/dom/debug/ts/by/by.ts region='by_directive'} */ static directive(type: Type<any>): Predicate<DebugNode> { return (debugNode) => debugNode.providerTokens!.indexOf(type) !== -1; } } function elementMatches(n: any, selector: string): boolean { if (getDOM().isElementNode(n)) { return ( (n.matches && n.matches(selector)) || (n.msMatchesSelector && n.msMatchesSelector(selector)) || (n.webkitMatchesSelector && n.webkitMatchesSelector(selector)) ); } return false; }
{ "end_byte": 1704, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/dom/debug/by.ts" }
angular/packages/router/README.md_0_652
Angular Router ========= Managing state transitions is one of the hardest parts of building applications. This is especially true on the web, where you also need to ensure that the state is reflected in the URL. In addition, we often want to split applications into multiple bundles and load them on demand. Doing this transparently isn’t trivial. The Angular router is designed to solve these problems. Using the router, you can declaratively specify application state, manage state transitions while taking care of the URL, and load components on demand. ## Guide Read the dev guide [here](https://angular.io/guide/routing/common-router-tasks).
{ "end_byte": 652, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/README.md" }
angular/packages/router/PACKAGE.md_0_528
Implements the Angular Router service , which enables navigation from one view to the next as users perform application tasks. Defines the `Route` object that maps a URL path to a component, and the `RouterOutlet` directive that you use to place a routed view in a template, as well as a complete API for configuring, querying, and controlling the router state. Import `RouterModule` to use the Router service in your app. For more usage information, see the [Routing and Navigation](guide/routing/common-router-tasks) guide.
{ "end_byte": 528, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/PACKAGE.md" }
angular/packages/router/BUILD.bazel_0_2218
load("//tools:defaults.bzl", "api_golden_test", "api_golden_test_npm_package", "generate_api_docs", "ng_module", "ng_package") package(default_visibility = ["//visibility:public"]) ng_module( name = "router", srcs = glob( [ "*.ts", "src/**/*.ts", ], ), deps = [ "//packages/common", "//packages/core", "//packages/platform-browser", "@npm//@types/dom-view-transitions", "@npm//rxjs", ], ) ng_package( name = "npm_package", package_name = "@angular/router", srcs = [ "package.json", ], tags = [ "release-with-framework", ], # Do not add more to this list. # Dependencies on the full npm_package cause long re-builds. visibility = [ "//adev:__pkg__", "//adev/shared-docs:__subpackages__", "//integration:__subpackages__", "//modules/ssr-benchmarks:__pkg__", "//packages/compiler-cli/integrationtest:__pkg__", "//packages/compiler-cli/test:__pkg__", "//packages/compiler-cli/test/transformers:__pkg__", ], deps = [ ":router", "//packages/router/testing", "//packages/router/upgrade", ], ) api_golden_test_npm_package( name = "router_api", data = [ ":npm_package", "//goldens:public-api", ], golden_dir = "angular/goldens/public-api/router", npm_package = "angular/packages/router/npm_package", ) api_golden_test( name = "router_errors", data = [ "//goldens:public-api", "//packages/router", ], entry_point = "angular/packages/router/src/errors.d.ts", golden = "angular/goldens/public-api/router/errors.api.md", ) filegroup( name = "files_for_docgen", srcs = glob([ "*.ts", "src/**/*.ts", ]) + ["PACKAGE.md"], ) generate_api_docs( name = "router_docs", srcs = [ ":files_for_docgen", "//packages:common_files_and_deps_for_docs", "//packages/common:files_for_docgen", "//packages/common/http:files_for_docgen", "@npm//@types/dom-view-transitions", ], entry_point = ":index.ts", module_name = "@angular/router", )
{ "end_byte": 2218, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/BUILD.bazel" }
angular/packages/router/index.ts_0_481
/** * @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.dev/license */ // This file is not used to build this module. It is only used during editing // by the TypeScript language service and during build for verification. `ngc` // replaces this file with production index.ts when it rewrites private symbol // names. export * from './public_api';
{ "end_byte": 481, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/index.ts" }
angular/packages/router/public_api.ts_0_396
/** * @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.dev/license */ /** * @module * @description * Entry point for all public APIs of this package. */ export * from './src/index'; // This file only reexports content of the `src` folder. Keep it that way.
{ "end_byte": 396, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/public_api.ts" }
angular/packages/router/upgrade/PACKAGE.md_0_79
Provides support for upgrading routing applications from Angular JS to Angular.
{ "end_byte": 79, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/upgrade/PACKAGE.md" }
angular/packages/router/upgrade/BUILD.bazel_0_782
load("//tools:defaults.bzl", "generate_api_docs", "ng_module") package(default_visibility = ["//visibility:public"]) exports_files(["package.json"]) ng_module( name = "upgrade", srcs = glob( [ "*.ts", "src/**/*.ts", ], ), deps = [ "//packages/common", "//packages/core", "//packages/router", "//packages/upgrade/static", ], ) filegroup( name = "files_for_docgen", srcs = glob([ "*.ts", "src/**/*.ts", ]) + ["PACKAGE.md"], ) generate_api_docs( name = "router_upgrade_docs", srcs = [ ":files_for_docgen", "//packages:common_files_and_deps_for_docs", ], entry_point = ":index.ts", module_name = "@angular/router/upgrade", )
{ "end_byte": 782, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/upgrade/BUILD.bazel" }
angular/packages/router/upgrade/index.ts_0_481
/** * @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.dev/license */ // This file is not used to build this module. It is only used during editing // by the TypeScript language service and during build for verification. `ngc` // replaces this file with production index.ts when it rewrites private symbol // names. export * from './public_api';
{ "end_byte": 481, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/upgrade/index.ts" }
angular/packages/router/upgrade/public_api.ts_0_398
/** * @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.dev/license */ /** * @module * @description * Entry point for all public APIs of this package. */ export * from './src/upgrade'; // This file only reexports content of the `src` folder. Keep it that way.
{ "end_byte": 398, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/upgrade/public_api.ts" }
angular/packages/router/upgrade/test/upgrade.spec.ts_0_6720
/** * @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.dev/license */ import {Location} from '@angular/common'; import {$locationShim, UrlCodec} from '@angular/common/upgrade'; import {fakeAsync, flush, TestBed} from '@angular/core/testing'; import {Router, RouterModule} from '@angular/router'; import {setUpLocationSync} from '@angular/router/upgrade'; import {UpgradeModule} from '@angular/upgrade/static'; import {LocationUpgradeTestModule} from './upgrade_location_test_module'; export function injectorFactory() { const rootScopeMock = new $rootScopeMock(); const rootElementMock = {on: () => undefined}; return function $injectorGet(provider: string) { if (provider === '$rootScope') { return rootScopeMock; } else if (provider === '$rootElement') { return rootElementMock; } else { throw new Error(`Unsupported injectable mock: ${provider}`); } }; } export class $rootScopeMock { private watchers: any[] = []; private events: {[k: string]: any[]} = {}; $watch(fn: any) { this.watchers.push(fn); } $broadcast(evt: string, ...args: any[]) { if (this.events[evt]) { this.events[evt].forEach((fn) => { fn.apply(fn, [/** angular.IAngularEvent*/ {}, ...args]); }); } return { defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, }; } $on(evt: string, fn: any) { this.events[evt] ??= []; this.events[evt].push(fn); } $evalAsync(fn: any) { fn(); } $digest() { this.watchers.forEach((fn) => fn()); } } describe('setUpLocationSync', () => { let upgradeModule: UpgradeModule; let router: any; let location: any; beforeEach(() => { TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ {path: '1', children: []}, {path: '2', children: []}, ]), UpgradeModule, LocationUpgradeTestModule.config(), ], }); upgradeModule = TestBed.inject(UpgradeModule); router = TestBed.inject(Router); location = TestBed.inject(Location); spyOn(router, 'navigateByUrl').and.callThrough(); spyOn(location, 'normalize').and.callThrough(); upgradeModule.$injector = {get: injectorFactory()}; }); it('should throw an error if the UpgradeModule.bootstrap has not been called', () => { upgradeModule.$injector = null; expect(() => setUpLocationSync(upgradeModule)).toThrowError(` RouterUpgradeInitializer can be used only after UpgradeModule.bootstrap has been called. Remove RouterUpgradeInitializer and call setUpLocationSync after UpgradeModule.bootstrap. `); }); it('should get the $rootScope from AngularJS and set an $on watch on $locationChangeStart', () => { const $rootScope = upgradeModule.$injector.get('$rootScope'); spyOn($rootScope, '$on'); setUpLocationSync(upgradeModule); expect($rootScope.$on).toHaveBeenCalledTimes(1); expect($rootScope.$on).toHaveBeenCalledWith('$locationChangeStart', jasmine.any(Function)); }); it('should navigate by url every time $locationChangeStart is broadcasted', () => { const url = 'https://google.com'; const pathname = '/custom/route'; const normalizedPathname = 'foo'; const query = '?query=1&query2=3'; const hash = '#new/hash'; const $rootScope = upgradeModule.$injector.get('$rootScope'); spyOn($rootScope, '$on'); location.normalize.and.returnValue(normalizedPathname); setUpLocationSync(upgradeModule); const callback = $rootScope.$on.calls.argsFor(0)[1]; callback({}, url + pathname + query + hash, ''); expect(router.navigateByUrl).toHaveBeenCalledTimes(1); expect(router.navigateByUrl).toHaveBeenCalledWith(normalizedPathname + query + hash); }); it('should allow configuration to work with hash-based routing', () => { const url = 'https://google.com'; const pathname = '/custom/route'; const normalizedPathname = 'foo'; const query = '?query=1&query2=3'; const hash = '#new/hash'; const combinedUrl = url + '#' + pathname + query + hash; const $rootScope = upgradeModule.$injector.get('$rootScope'); spyOn($rootScope, '$on'); location.normalize.and.returnValue(normalizedPathname); setUpLocationSync(upgradeModule, 'hash'); const callback = $rootScope.$on.calls.argsFor(0)[1]; callback({}, combinedUrl, ''); expect(router.navigateByUrl).toHaveBeenCalledTimes(1); expect(router.navigateByUrl).toHaveBeenCalledWith(normalizedPathname + query + hash); }); it('should work correctly on browsers that do not start pathname with `/`', () => { const anchorProto = HTMLAnchorElement.prototype; const originalDescriptor = Object.getOwnPropertyDescriptor(anchorProto, 'pathname'); Object.defineProperty(anchorProto, 'pathname', {get: () => 'foo/bar'}); try { const $rootScope = upgradeModule.$injector.get('$rootScope'); spyOn($rootScope, '$on'); setUpLocationSync(upgradeModule); const callback = $rootScope.$on.calls.argsFor(0)[1]; callback({}, '', ''); expect(location.normalize).toHaveBeenCalledWith('/foo/bar'); } finally { Object.defineProperty(anchorProto, 'pathname', originalDescriptor!); } }); it('should not duplicate navigations triggered by Angular router', fakeAsync(() => { spyOn(TestBed.inject(UrlCodec), 'parse').and.returnValue({ pathname: '', href: '', protocol: '', host: '', search: '', hash: '', hostname: '', port: '', }); const $rootScope = upgradeModule.$injector.get('$rootScope'); spyOn($rootScope, '$broadcast').and.callThrough(); setUpLocationSync(upgradeModule); // Inject location shim so its urlChangeListener subscribes TestBed.inject($locationShim); router.navigateByUrl('/1'); location.normalize.and.returnValue('/1'); flush(); expect(router.navigateByUrl).toHaveBeenCalledTimes(1); expect($rootScope.$broadcast.calls.argsFor(0)[0]).toEqual('$locationChangeStart'); expect($rootScope.$broadcast.calls.argsFor(1)[0]).toEqual('$locationChangeSuccess'); $rootScope.$broadcast.calls.reset(); router.navigateByUrl.calls.reset(); location.go('/2'); location.normalize.and.returnValue('/2'); flush(); expect($rootScope.$broadcast.calls.argsFor(0)[0]).toEqual('$locationChangeStart'); expect($rootScope.$broadcast.calls.argsFor(1)[0]).toEqual('$locationChangeSuccess'); expect(router.navigateByUrl).toHaveBeenCalledTimes(1); })); });
{ "end_byte": 6720, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/upgrade/test/upgrade.spec.ts" }
angular/packages/router/upgrade/test/upgrade_location_test_module.ts_0_3074
/** * @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.dev/license */ import { APP_BASE_HREF, CommonModule, Location, LocationStrategy, PlatformLocation, } from '@angular/common'; import {MockPlatformLocation} from '@angular/common/testing'; import { $locationShim, $locationShimProvider, LocationUpgradeModule, UrlCodec, } from '@angular/common/upgrade'; import {Inject, InjectionToken, ModuleWithProviders, NgModule, Optional} from '@angular/core'; import {UpgradeModule} from '@angular/upgrade/static'; export interface LocationUpgradeTestingConfig { useHash?: boolean; hashPrefix?: string; urlCodec?: typeof UrlCodec; startUrl?: string; appBaseHref?: string; } /** * @description * * Is used in DI to configure the router. */ export const LOC_UPGRADE_TEST_CONFIG = new InjectionToken<LocationUpgradeTestingConfig>( 'LOC_UPGRADE_TEST_CONFIG', ); export const APP_BASE_HREF_RESOLVED = new InjectionToken<string>('APP_BASE_HREF_RESOLVED'); /** * Module used for configuring Angular's LocationUpgradeService. */ @NgModule({imports: [CommonModule]}) export class LocationUpgradeTestModule { static config( config?: LocationUpgradeTestingConfig, ): ModuleWithProviders<LocationUpgradeTestModule> { return { ngModule: LocationUpgradeTestModule, providers: [ {provide: LOC_UPGRADE_TEST_CONFIG, useValue: config || {}}, { provide: PlatformLocation, useFactory: (appBaseHref?: string) => { if (config && config.appBaseHref != null) { appBaseHref = config.appBaseHref; } else if (appBaseHref == null) { appBaseHref = ''; } return new MockPlatformLocation({ startUrl: config && config.startUrl, appBaseHref: appBaseHref, }); }, deps: [[new Inject(APP_BASE_HREF), new Optional()]], }, { provide: $locationShim, useFactory: provide$location, deps: [ UpgradeModule, Location, PlatformLocation, UrlCodec, LocationStrategy, LOC_UPGRADE_TEST_CONFIG, ], }, LocationUpgradeModule.config({ appBaseHref: config && config.appBaseHref, useHash: (config && config.useHash) || false, }).providers!, ], }; } } export function provide$location( ngUpgrade: UpgradeModule, location: Location, platformLocation: PlatformLocation, urlCodec: UrlCodec, locationStrategy: LocationStrategy, config?: LocationUpgradeTestingConfig, ) { const $locationProvider = new $locationShimProvider( ngUpgrade, location, platformLocation, urlCodec, locationStrategy, ); $locationProvider.hashPrefix(config && config.hashPrefix); $locationProvider.html5Mode(config && !config.useHash); return $locationProvider.$get(); }
{ "end_byte": 3074, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/upgrade/test/upgrade_location_test_module.ts" }
angular/packages/router/upgrade/test/BUILD.bazel_0_854
load("//tools:defaults.bzl", "karma_web_test_suite", "ts_library") load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test") circular_dependency_test( name = "circular_deps_test", entry_point = "angular/packages/router/upgrade/index.mjs", deps = ["//packages/router/upgrade"], ) ts_library( name = "test_lib", testonly = True, srcs = glob(["**/*.ts"]), deps = [ "//packages/common", "//packages/common/testing", "//packages/common/upgrade", "//packages/core", "//packages/core/testing", "//packages/private/testing", "//packages/router", "//packages/router/testing", "//packages/router/upgrade", "//packages/upgrade/static", ], ) karma_web_test_suite( name = "test_web", deps = [ ":test_lib", ], )
{ "end_byte": 854, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/upgrade/test/BUILD.bazel" }
angular/packages/router/upgrade/src/upgrade.ts_0_4840
/** * @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.dev/license */ import {Location} from '@angular/common'; import {APP_BOOTSTRAP_LISTENER, ComponentRef, InjectionToken} from '@angular/core'; import {Router, ɵRestoredState as RestoredState} from '@angular/router'; import {UpgradeModule} from '@angular/upgrade/static'; /** * Creates an initializer that sets up `ngRoute` integration * along with setting up the Angular router. * * @usageNotes * * <code-example language="typescript"> * @NgModule({ * imports: [ * RouterModule.forRoot(SOME_ROUTES), * UpgradeModule * ], * providers: [ * RouterUpgradeInitializer * ] * }) * export class AppModule { * ngDoBootstrap() {} * } * </code-example> * * @publicApi */ export const RouterUpgradeInitializer = { provide: APP_BOOTSTRAP_LISTENER, multi: true, useFactory: locationSyncBootstrapListener as (ngUpgrade: UpgradeModule) => () => void, deps: [UpgradeModule], }; /** * @internal */ export function locationSyncBootstrapListener(ngUpgrade: UpgradeModule) { return () => { setUpLocationSync(ngUpgrade); }; } /** * Sets up a location change listener to trigger `history.pushState`. * Works around the problem that `onPopState` does not trigger `history.pushState`. * Must be called *after* calling `UpgradeModule.bootstrap`. * * @param ngUpgrade The upgrade NgModule. * @param urlType The location strategy. * @see {@link HashLocationStrategy} * @see {@link PathLocationStrategy} * * @publicApi */ export function setUpLocationSync(ngUpgrade: UpgradeModule, urlType: 'path' | 'hash' = 'path') { if (!ngUpgrade.$injector) { throw new Error(` RouterUpgradeInitializer can be used only after UpgradeModule.bootstrap has been called. Remove RouterUpgradeInitializer and call setUpLocationSync after UpgradeModule.bootstrap. `); } const router: Router = ngUpgrade.injector.get(Router); const location: Location = ngUpgrade.injector.get(Location); ngUpgrade.$injector .get('$rootScope') .$on( '$locationChangeStart', ( event: any, newUrl: string, oldUrl: string, newState?: {[k: string]: unknown} | RestoredState, oldState?: {[k: string]: unknown} | RestoredState, ) => { // Navigations coming from Angular router have a navigationId state // property. Don't trigger Angular router navigation again if it is // caused by a URL change from the current Angular router // navigation. const currentNavigationId = router.getCurrentNavigation()?.id; const newStateNavigationId = newState?.navigationId; if (newStateNavigationId !== undefined && newStateNavigationId === currentNavigationId) { return; } let url; if (urlType === 'path') { url = resolveUrl(newUrl); } else if (urlType === 'hash') { // Remove the first hash from the URL const hashIdx = newUrl.indexOf('#'); url = resolveUrl(newUrl.substring(0, hashIdx) + newUrl.substring(hashIdx + 1)); } else { throw 'Invalid URLType passed to setUpLocationSync: ' + urlType; } const path = location.normalize(url.pathname); router.navigateByUrl(path + url.search + url.hash); }, ); } /** * Normalizes and parses a URL. * * - Normalizing means that a relative URL will be resolved into an absolute URL in the context of * the application document. * - Parsing means that the anchor's `protocol`, `hostname`, `port`, `pathname` and related * properties are all populated to reflect the normalized URL. * * While this approach has wide compatibility, it doesn't work as expected on IE. On IE, normalizing * happens similar to other browsers, but the parsed components will not be set. (E.g. if you assign * `a.href = 'foo'`, then `a.protocol`, `a.host`, etc. will not be correctly updated.) * We work around that by performing the parsing in a 2nd step by taking a previously normalized URL * and assigning it again. This correctly populates all properties. * * See * https://github.com/angular/angular.js/blob/2c7400e7d07b0f6cec1817dab40b9250ce8ebce6/src/ng/urlUtils.js#L26-L33 * for more info. */ let anchor: HTMLAnchorElement | undefined; function resolveUrl(url: string): {pathname: string; search: string; hash: string} { anchor ??= document.createElement('a'); anchor.setAttribute('href', url); anchor.setAttribute('href', anchor.href); return { // IE does not start `pathname` with `/` like other browsers. pathname: `/${anchor.pathname.replace(/^\//, '')}`, search: anchor.search, hash: anchor.hash, }; }
{ "end_byte": 4840, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/upgrade/src/upgrade.ts" }
angular/packages/router/test/router_devtools.spec.ts_0_2343
/** * @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.dev/license */ import {Component} from '@angular/core'; import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'; import {Router, RouterModule} from '@angular/router'; import {getLoadedRoutes} from '../src/router_devtools'; @Component({template: '<div>simple standalone</div>', standalone: true}) export class SimpleStandaloneComponent {} @Component({ template: '<router-outlet></router-outlet>', standalone: true, imports: [RouterModule], }) export class RootCmp {} describe('router_devtools', () => { describe('getLoadedRoutes', () => { it('should return loaded routes when called with load children', fakeAsync(() => { TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ { path: 'lazy', component: RootCmp, loadChildren: () => [{path: 'simple', component: SimpleStandaloneComponent}], }, ]), ], }); const root = TestBed.createComponent(RootCmp); const router = TestBed.inject(Router); router.navigateByUrl('/lazy/simple'); advance(root); expect(root.nativeElement.innerHTML).toContain('simple standalone'); const loadedRoutes = getLoadedRoutes(router.config[0]); const loadedPath = loadedRoutes && loadedRoutes[0].path; expect(loadedPath).toEqual('simple'); })); }); it('should return undefined when called without load children', fakeAsync(() => { TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ { path: 'lazy', component: RootCmp, }, ]), ], }); const root = TestBed.createComponent(RootCmp); const router = TestBed.inject(Router); router.navigateByUrl('/lazy'); advance(root); expect(root.nativeElement.innerHTML).toContain(''); const loadedRoutes = getLoadedRoutes(router.config[0]); const loadedPath = loadedRoutes && loadedRoutes[0].path; expect(loadedPath).toEqual(undefined); })); }); function advance(fixture: ComponentFixture<unknown>) { tick(); fixture.detectChanges(); }
{ "end_byte": 2343, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/router_devtools.spec.ts" }
angular/packages/router/test/helpers.ts_0_1435
/** * @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.dev/license */ import {Type} from '@angular/core'; import {Data, ResolveData, Route} from '../src/models'; import {ActivatedRouteSnapshot} from '../src/router_state'; import {Params} from '../src/shared'; import {UrlSegment, UrlTree} from '../src/url_tree'; export class Logger { logs: string[] = []; add(thing: string) { this.logs.push(thing); } empty() { this.logs.length = 0; } } 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; queryParams?: Params; fragment?: string; data?: Data; outlet?: string; component: Type<unknown> | string | null; routeConfig?: Route | null; resolve?: ResolveData; }; export function createActivatedRouteSnapshot(args: ARSArgs): ActivatedRouteSnapshot { return new (ActivatedRouteSnapshot as any)( args.url || [], args.params || {}, args.queryParams || null, args.fragment || null, args.data || null, args.outlet || null, args.component, args.routeConfig || {}, args.resolve || {}, ); }
{ "end_byte": 1435, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/helpers.ts" }
angular/packages/router/test/computed_state_restoration.spec.ts_0_4432
/** * @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.dev/license */ import {CommonModule, Location} from '@angular/common'; import {provideLocationMocks, SpyLocation} from '@angular/common/testing'; import {Component, Injectable, NgModule, Type} from '@angular/core'; import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/src/matchers'; import {Router, RouterModule, RouterOutlet, UrlTree, withRouterConfig} from '@angular/router'; import {EMPTY, of} from 'rxjs'; import {provideRouter} from '../src/provide_router'; import {isUrlTree} from '../src/url_tree'; describe('`restoredState#ɵrouterPageId`', () => { @Injectable({providedIn: 'root'}) class MyCanDeactivateGuard { allow: boolean = true; canDeactivate(): boolean { return this.allow; } } @Injectable({providedIn: 'root'}) class ThrowingCanActivateGuard { throw = false; constructor(private router: Router) {} canActivate(): boolean { if (this.throw) { throw new Error('error in guard'); } return true; } } @Injectable({providedIn: 'root'}) class MyCanActivateGuard { allow: boolean = true; redirectTo: string | null | UrlTree = null; constructor(private router: Router) {} canActivate(): boolean | UrlTree { if (typeof this.redirectTo === 'string') { this.router.navigateByUrl(this.redirectTo); } else if (isUrlTree(this.redirectTo)) { return this.redirectTo; } return this.allow; } } @Injectable({providedIn: 'root'}) class MyResolve { myresolve = of(2); resolve() { return this.myresolve; } } let fixture: ComponentFixture<unknown>; function createNavigationHistory(urlUpdateStrategy: 'eager' | 'deferred' = 'deferred') { TestBed.configureTestingModule({ imports: [TestModule], providers: [ {provide: 'alwaysFalse', useValue: (a: any) => false}, {provide: Location, useClass: SpyLocation}, provideRouter( [ { path: 'first', component: SimpleCmp, canDeactivate: [MyCanDeactivateGuard], canActivate: [MyCanActivateGuard, ThrowingCanActivateGuard], resolve: {x: MyResolve}, }, { path: 'second', component: SimpleCmp, canDeactivate: [MyCanDeactivateGuard], canActivate: [MyCanActivateGuard, ThrowingCanActivateGuard], resolve: {x: MyResolve}, }, { path: 'third', component: SimpleCmp, canDeactivate: [MyCanDeactivateGuard], canActivate: [MyCanActivateGuard, ThrowingCanActivateGuard], resolve: {x: MyResolve}, }, { path: 'unguarded', component: SimpleCmp, }, { path: 'throwing', component: ThrowingCmp, }, { path: 'loaded', loadChildren: () => of(ModuleWithSimpleCmpAsRoute), canLoad: ['alwaysFalse'], }, ], withRouterConfig({ urlUpdateStrategy, canceledNavigationResolution: 'computed', resolveNavigationPromiseOnError: true, }), ), ], }); const router = TestBed.inject(Router); const location = TestBed.inject(Location); fixture = createRoot(router, RootCmp); router.initialNavigation(); advance(fixture); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 0})); router.navigateByUrl('/first'); advance(fixture); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 1})); router.navigateByUrl('/second'); advance(fixture); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); router.navigateByUrl('/third'); advance(fixture); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 3})); location.back(); advance(fixture); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); } de
{ "end_byte": 4432, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/computed_state_restoration.spec.ts" }
angular/packages/router/test/computed_state_restoration.spec.ts_4436_13086
be('deferred url updates', () => { beforeEach(fakeAsync(() => { createNavigationHistory(); })); it('should work when CanActivate returns false', fakeAsync(() => { const location = TestBed.inject(Location); const router = TestBed.inject(Router); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); TestBed.inject(MyCanActivateGuard).allow = false; location.back(); advance(fixture); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); TestBed.inject(MyCanActivateGuard).allow = true; location.back(); advance(fixture); expect(location.path()).toEqual('/first'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 1})); TestBed.inject(MyCanActivateGuard).allow = false; location.forward(); advance(fixture); expect(location.path()).toEqual('/first'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 1})); router.navigateByUrl('/second'); advance(fixture); expect(location.path()).toEqual('/first'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 1})); })); it('should work when CanDeactivate returns false', fakeAsync(() => { const location = TestBed.inject(Location); const router = TestBed.inject(Router); TestBed.inject(MyCanDeactivateGuard).allow = false; location.back(); advance(fixture); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); location.forward(); advance(fixture); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); router.navigateByUrl('third'); advance(fixture); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); TestBed.inject(MyCanDeactivateGuard).allow = true; location.forward(); advance(fixture); expect(location.path()).toEqual('/third'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 3})); })); it('should work when using `NavigationExtras.skipLocationChange`', fakeAsync(() => { const location = TestBed.inject(Location); const router = TestBed.inject(Router); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); router.navigateByUrl('/first', {skipLocationChange: true}); advance(fixture); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); router.navigateByUrl('/third'); advance(fixture); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 3})); location.back(); advance(fixture); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); })); it('should work when using `NavigationExtras.replaceUrl`', fakeAsync(() => { const location = TestBed.inject(Location); const router = TestBed.inject(Router); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); router.navigateByUrl('/first', {replaceUrl: true}); advance(fixture); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); expect(location.path()).toEqual('/first'); })); it('should work when CanLoad returns false', fakeAsync(() => { const location = TestBed.inject(Location); const router = TestBed.inject(Router); router.navigateByUrl('/loaded'); advance(fixture); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); })); it('should work when resolve empty', fakeAsync(() => { const location = TestBed.inject(Location); const router = TestBed.inject(Router); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); TestBed.inject(MyResolve).myresolve = EMPTY; location.back(); advance(fixture); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); expect(location.path()).toEqual('/second'); TestBed.inject(MyResolve).myresolve = of(2); location.back(); advance(fixture); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 1})); expect(location.path()).toEqual('/first'); TestBed.inject(MyResolve).myresolve = EMPTY; // We should cancel the navigation to `/third` when myresolve is empty router.navigateByUrl('/third'); advance(fixture); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 1})); expect(location.path()).toEqual('/first'); location.historyGo(2); advance(fixture); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 1})); expect(location.path()).toEqual('/first'); TestBed.inject(MyResolve).myresolve = of(2); location.historyGo(2); advance(fixture); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 3})); expect(location.path()).toEqual('/third'); TestBed.inject(MyResolve).myresolve = EMPTY; location.historyGo(-2); advance(fixture); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 3})); expect(location.path()).toEqual('/third'); })); it('should work when an error occurred during navigation', fakeAsync(() => { const location = TestBed.inject(Location); const router = TestBed.inject(Router); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); router.navigateByUrl('/invalid').catch(() => null); advance(fixture); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); location.back(); advance(fixture); expect(location.path()).toEqual('/first'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 1})); })); it('should work when CanActivate redirects', fakeAsync(() => { const location = TestBed.inject(Location); TestBed.inject(MyCanActivateGuard).redirectTo = '/unguarded'; location.back(); advance(fixture); expect(location.path()).toEqual('/unguarded'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); TestBed.inject(MyCanActivateGuard).redirectTo = null; location.back(); advance(fixture); expect(location.path()).toEqual('/first'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 1})); })); it('restores history correctly when component throws error in constructor and replaceUrl=true', fakeAsync(() => { const location = TestBed.inject(Location); const router = TestBed.inject(Router); router.navigateByUrl('/throwing', {replaceUrl: true}).catch(() => null); advance(fixture); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); location.back(); advance(fixture); expect(location.path()).toEqual('/first'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 1})); })); it('restores history correctly when component throws error in constructor and skipLocationChange=true', fakeAsync(() => { const location = TestBed.inject(Location); const router = TestBed.inject(Router); router.navigateByUrl('/throwing', {skipLocationChange: true}).catch(() => null); advance(fixture); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); location.back(); advance(fixture); expect(location.path()).toEqual('/first'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 1})); })); }); describe('eager url updates', () =
{ "end_byte": 13086, "start_byte": 4436, "url": "https://github.com/angular/angular/blob/main/packages/router/test/computed_state_restoration.spec.ts" }
angular/packages/router/test/computed_state_restoration.spec.ts_13090_20294
beforeEach(fakeAsync(() => { createNavigationHistory('eager'); })); it('should work', fakeAsync(() => { const location = TestBed.inject(Location) as SpyLocation; const router = TestBed.inject(Router); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); TestBed.inject(MyCanActivateGuard).allow = false; router.navigateByUrl('/first'); advance(fixture); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); location.back(); advance(fixture); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); })); it('should work when CanActivate redirects', fakeAsync(() => { const location = TestBed.inject(Location); const router = TestBed.inject(Router); TestBed.inject(MyCanActivateGuard).redirectTo = '/unguarded'; router.navigateByUrl('/third'); advance(fixture); expect(location.path()).toEqual('/unguarded'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 4})); TestBed.inject(MyCanActivateGuard).redirectTo = null; location.back(); advance(fixture); expect(location.path()).toEqual('/third'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 3})); })); it('should work when CanActivate redirects with UrlTree', fakeAsync(() => { // Note that this test is different from the above case because we are able to specifically // handle the `UrlTree` case as a proper redirect and set `replaceUrl: true` on the // follow-up navigation. const location = TestBed.inject(Location); const router = TestBed.inject(Router); let allowNavigation = true; router.resetConfig([ {path: 'initial', children: []}, {path: 'redirectFrom', redirectTo: 'redirectTo'}, {path: 'redirectTo', children: [], canActivate: [() => allowNavigation]}, ]); // already at '2' from the `beforeEach` navigations expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); router.navigateByUrl('/initial'); advance(fixture); expect(location.path()).toEqual('/initial'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 3})); TestBed.inject(MyCanActivateGuard).redirectTo = null; router.navigateByUrl('redirectTo'); advance(fixture); expect(location.path()).toEqual('/redirectTo'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 4})); // Navigate to different URL but get redirected to same URL should result in same page id router.navigateByUrl('redirectFrom'); advance(fixture); expect(location.path()).toEqual('/redirectTo'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 4})); // Back and forward should have page IDs 1 apart location.back(); advance(fixture); expect(location.path()).toEqual('/initial'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 3})); location.forward(); advance(fixture); expect(location.path()).toEqual('/redirectTo'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 4})); // Rejected navigation after redirect to same URL should have the same page ID allowNavigation = false; router.navigateByUrl('redirectFrom'); advance(fixture); expect(location.path()).toEqual('/redirectTo'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 4})); })); it('redirectTo with same url, and guard reject', fakeAsync(() => { const location = TestBed.inject(Location); const router = TestBed.inject(Router); TestBed.inject(MyCanActivateGuard).redirectTo = router.createUrlTree(['unguarded']); router.navigateByUrl('/third'); advance(fixture); expect(location.path()).toEqual('/unguarded'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 3})); TestBed.inject(MyCanActivateGuard).redirectTo = null; location.back(); advance(fixture); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); })); }); for (const urlUpdateStrategy of ['deferred', 'eager'] as const) { it(`restores history correctly when an error is thrown in guard with urlUpdateStrategy ${urlUpdateStrategy}`, fakeAsync(() => { createNavigationHistory(urlUpdateStrategy); const location = TestBed.inject(Location); TestBed.inject(ThrowingCanActivateGuard).throw = true; location.back(); advance(fixture); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); TestBed.inject(ThrowingCanActivateGuard).throw = false; location.back(); advance(fixture); expect(location.path()).toEqual('/first'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 1})); })); it(`restores history correctly when component throws error in constructor with urlUpdateStrategy ${urlUpdateStrategy}`, fakeAsync(() => { createNavigationHistory(urlUpdateStrategy); const location = TestBed.inject(Location); const router = TestBed.inject(Router); router.navigateByUrl('/throwing').catch(() => null); advance(fixture); expect(location.path()).toEqual('/second'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); location.back(); advance(fixture); expect(location.path()).toEqual('/first'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 1})); })); } }); function createRoot<T>(router: Router, type: Type<T>): ComponentFixture<T> { const f = TestBed.createComponent(type); advance(f); router.initialNavigation(); advance(f); return f; } @Component({ selector: 'simple-cmp', template: `simple`, standalone: false, }) class SimpleCmp {} @NgModule({imports: [RouterModule.forChild([{path: '', component: SimpleCmp}])]}) class ModuleWithSimpleCmpAsRoute {} @Component({ selector: 'root-cmp', template: `<router-outlet></router-outlet>`, standalone: false, }) class RootCmp {} @Component({ selector: 'throwing-cmp', template: '', standalone: false, }) class ThrowingCmp { constructor() { throw new Error('Throwing Cmp'); } } function advance(fixture: ComponentFixture<unknown>, millis?: number): void { tick(millis); fixture.detectChanges(); } @NgModule({ imports: [RouterOutlet, CommonModule], providers: [provideLocationMocks()], exports: [SimpleCmp, RootCmp, ThrowingCmp], declarations: [SimpleCmp, RootCmp, ThrowingCmp], }) class TestModule {}
{ "end_byte": 20294, "start_byte": 13090, "url": "https://github.com/angular/angular/blob/main/packages/router/test/computed_state_restoration.spec.ts" }
angular/packages/router/test/default_export_component.ts_0_374
/** * @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.dev/license */ import {Component} from '@angular/core'; @Component({ standalone: true, template: 'default exported', selector: 'test-route', }) export default class TestRoute {}
{ "end_byte": 374, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/default_export_component.ts" }
angular/packages/router/test/standalone.spec.ts_0_9367
/** * @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.dev/license */ import {Component, Injectable, NgModule} from '@angular/core'; import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {provideRoutes, Router, RouterModule, ROUTES} from '@angular/router'; @Component({template: '<div>simple standalone</div>', standalone: true}) export class SimpleStandaloneComponent {} @Component({template: '<div>not standalone</div>', standalone: false}) export class NotStandaloneComponent {} @Component({ template: '<router-outlet></router-outlet>', standalone: true, imports: [RouterModule], }) export class RootCmp {} describe('standalone in Router API', () => { describe('loadChildren => routes', () => { it('can navigate to and render standalone component', fakeAsync(() => { TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ { path: 'lazy', component: RootCmp, loadChildren: () => [{path: '', component: SimpleStandaloneComponent}], }, ]), ], }); const root = TestBed.createComponent(RootCmp); const router = TestBed.inject(Router); router.navigateByUrl('/lazy'); advance(root); expect(root.nativeElement.innerHTML).toContain('simple standalone'); })); it('throws an error when loadChildren=>routes has a component that is not standalone', fakeAsync(() => { TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ { path: 'lazy', component: RootCmp, loadChildren: () => [{path: 'notstandalone', component: NotStandaloneComponent}], }, ]), ], }); const root = TestBed.createComponent(RootCmp); const router = TestBed.inject(Router); router.navigateByUrl('/lazy/notstandalone'); expect(() => advance(root)).toThrowError( /.*lazy\/notstandalone.*component must be standalone/, ); })); }); describe('route providers', () => { it('can provide a guard on a route', fakeAsync(() => { @Injectable() class ConfigurableGuard { static canActivateValue = false; canActivate() { return ConfigurableGuard.canActivateValue; } } TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ { path: 'simple', providers: [ConfigurableGuard], canActivate: [ConfigurableGuard], component: SimpleStandaloneComponent, }, ]), ], }); const root = TestBed.createComponent(RootCmp); ConfigurableGuard.canActivateValue = false; const router = TestBed.inject(Router); router.navigateByUrl('/simple'); advance(root); expect(root.nativeElement.innerHTML).not.toContain('simple standalone'); expect(router.url).not.toContain('simple'); ConfigurableGuard.canActivateValue = true; router.navigateByUrl('/simple'); advance(root); expect(root.nativeElement.innerHTML).toContain('simple standalone'); expect(router.url).toContain('simple'); })); it('can inject provider on a route into component', fakeAsync(() => { @Injectable() class Service { value = 'my service'; } @Component({ template: `{{service.value}}`, standalone: false, }) class MyComponent { constructor(readonly service: Service) {} } TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([{path: 'home', providers: [Service], component: MyComponent}]), ], declarations: [MyComponent], }); const root = TestBed.createComponent(RootCmp); const router = TestBed.inject(Router); router.navigateByUrl('/home'); advance(root); expect(root.nativeElement.innerHTML).toContain('my service'); expect(router.url).toContain('home'); })); it('can not inject provider in lazy loaded ngModule from component on same level', fakeAsync(() => { @Injectable() class Service { value = 'my service'; } @NgModule({providers: [Service]}) class LazyModule {} @Component({ template: `{{service.value}}`, standalone: false, }) class MyComponent { constructor(readonly service: Service) {} } TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ {path: 'home', loadChildren: () => LazyModule, component: MyComponent}, ]), ], declarations: [MyComponent], }); const root = TestBed.createComponent(RootCmp); const router = TestBed.inject(Router); router.navigateByUrl('/home'); expect(() => advance(root)).toThrowError(); })); it('component from lazy module can inject provider from parent route', fakeAsync(() => { @Injectable() class Service { value = 'my service'; } @Component({ template: `{{service.value}}`, standalone: false, }) class MyComponent { constructor(readonly service: Service) {} } @NgModule({ providers: [Service], declarations: [MyComponent], imports: [RouterModule.forChild([{path: '', component: MyComponent}])], }) class LazyModule {} TestBed.configureTestingModule({ imports: [RouterModule.forRoot([{path: 'home', loadChildren: () => LazyModule}])], }); const root = TestBed.createComponent(RootCmp); const router = TestBed.inject(Router); router.navigateByUrl('/home'); advance(root); expect(root.nativeElement.innerHTML).toContain('my service'); })); it('gets the correct injector for guards and components when combining lazy modules and route providers', fakeAsync(() => { const canActivateLog: string[] = []; abstract class ServiceBase { abstract name: string; canActivate() { canActivateLog.push(this.name); return true; } } @Injectable() class Service1 extends ServiceBase { override name = 'service1'; } @Injectable() class Service2 extends ServiceBase { override name = 'service2'; } @Injectable() class Service3 extends ServiceBase { override name = 'service3'; } @Component({ template: `parent<router-outlet></router-outlet>`, standalone: false, }) class ParentCmp { constructor(readonly service: ServiceBase) {} } @Component({ template: `child`, standalone: false, }) class ChildCmp { constructor(readonly service: ServiceBase) {} } @Component({ template: `child2`, standalone: false, }) class ChildCmp2 { constructor(readonly service: ServiceBase) {} } @NgModule({ providers: [{provide: ServiceBase, useClass: Service2}], declarations: [ChildCmp, ChildCmp2], imports: [ RouterModule.forChild([ { path: '', // This component and guard should get Service2 since it's provided in this module component: ChildCmp, canActivate: [ServiceBase], }, { path: 'child2', providers: [{provide: ServiceBase, useFactory: () => new Service3()}], // This component and guard should get Service3 since it's provided on this route component: ChildCmp2, canActivate: [ServiceBase], }, ]), ], }) class LazyModule {} TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ { path: 'home', // This component and guard should get Service1 since it's provided on this route component: ParentCmp, canActivate: [ServiceBase], providers: [{provide: ServiceBase, useFactory: () => new Service1()}], loadChildren: () => LazyModule, }, ]), ], declarations: [ParentCmp], }); const root = TestBed.createComponent(RootCmp); const router = TestBed.inject(Router); router.navigateByUrl('/home'); advance(root); expect(canActivateLog).toEqual(['service1', 'service2']); expect( root.debugElement.query(By.directive(ParentCmp)).componentInstance.service.name, ).toEqual('service1'); expect( root.debugElement.query(By.directive(ChildCmp)).componentInstance.service.name, ).toEqual('service2'); router.navigateByUrl('/home/child2'); advance(root); expect(canActivateLog).toEqual(['service1', 'service2', 'service3']); expect( root.debugElement.query(By.directive(ChildCmp2)).componentInstance.service.name, ).toEqual('service3'); })); });
{ "end_byte": 9367, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/standalone.spec.ts" }
angular/packages/router/test/standalone.spec.ts_9371_13215
describe('loadComponent', () => { it('does not load component when canActivate returns false', fakeAsync(() => { const loadComponentSpy = jasmine.createSpy(); @Injectable({providedIn: 'root'}) class Guard { canActivate() { return false; } } TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ { path: 'home', loadComponent: loadComponentSpy, canActivate: [Guard], }, ]), ], }); TestBed.inject(Router).navigateByUrl('/home'); tick(); expect(loadComponentSpy).not.toHaveBeenCalled(); })); it('loads and renders lazy component', fakeAsync(() => { TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ { path: 'home', loadComponent: () => SimpleStandaloneComponent, }, ]), ], }); const root = TestBed.createComponent(RootCmp); TestBed.inject(Router).navigateByUrl('/home'); advance(root); expect(root.nativeElement.innerHTML).toContain('simple standalone'); })); it('throws error when loadComponent is not standalone', fakeAsync(() => { TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ { path: 'home', loadComponent: () => NotStandaloneComponent, }, ]), ], }); const root = TestBed.createComponent(RootCmp); TestBed.inject(Router).navigateByUrl('/home'); expect(() => advance(root)).toThrowError(/.*home.*component must be standalone/); })); it('throws error when loadComponent is used with a module', fakeAsync(() => { @NgModule() class LazyModule {} TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ { path: 'home', loadComponent: () => LazyModule, }, ]), ], }); const root = TestBed.createComponent(RootCmp); TestBed.inject(Router).navigateByUrl('/home'); expect(() => advance(root)).toThrowError(/.*home.*Use 'loadChildren' instead/); })); }); describe('default export unwrapping', () => { it('should work for loadComponent', async () => { TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ { path: 'home', loadComponent: () => import('./default_export_component'), }, ]), ], }); const root = TestBed.createComponent(RootCmp); await TestBed.inject(Router).navigateByUrl('/home'); root.detectChanges(); expect(root.nativeElement.innerHTML).toContain('default exported'); }); it('should work for loadChildren', async () => { TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ { path: 'home', loadChildren: () => import('./default_export_routes'), }, ]), ], }); const root = TestBed.createComponent(RootCmp); await TestBed.inject(Router).navigateByUrl('/home'); root.detectChanges(); expect(root.nativeElement.innerHTML).toContain('default exported'); }); }); }); describe('provideRoutes', () => { it('warns if provideRoutes is used without provideRouter, RouterModule, or RouterModule.forRoot', () => { spyOn(console, 'warn'); TestBed.configureTestingModule({providers: [provideRoutes([])]}); TestBed.inject(ROUTES); expect(console.warn).toHaveBeenCalled(); }); }); function advance(fixture: ComponentFixture<unknown>) { tick(); fixture.detectChanges(); }
{ "end_byte": 13215, "start_byte": 9371, "url": "https://github.com/angular/angular/blob/main/packages/router/test/standalone.spec.ts" }
angular/packages/router/test/router_link_spec.ts_0_8452
/** * @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.dev/license */ import {Component, inject, signal, provideExperimentalZonelessChangeDetection} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {Router, RouterLink, RouterModule, provideRouter} from '@angular/router'; describe('RouterLink', () => { beforeEach(() => { TestBed.configureTestingModule({providers: [provideExperimentalZonelessChangeDetection()]}); }); it('does not modify tabindex if already set on non-anchor element', async () => { @Component({ template: `<div [routerLink]="link" tabindex="1"></div>`, standalone: false, }) class LinkComponent { link: string | null | undefined = '/'; } TestBed.configureTestingModule({ imports: [RouterModule.forRoot([])], declarations: [LinkComponent], }); const fixture = TestBed.createComponent(LinkComponent); await fixture.whenStable(); const link = fixture.debugElement.query(By.css('div')).nativeElement; expect(link.tabIndex).toEqual(1); fixture.nativeElement.link = null; await fixture.whenStable(); expect(link.tabIndex).toEqual(1); }); describe('on a non-anchor', () => { @Component({ template: ` <div [routerLink]="link()" [preserveFragment]="preserveFragment()" [skipLocationChange]="skipLocationChange()" [replaceUrl]="replaceUrl()"></div> `, standalone: false, }) class LinkComponent { link = signal<string | null | undefined>('/'); preserveFragment = signal<unknown>(undefined); skipLocationChange = signal<unknown>(undefined); replaceUrl = signal<unknown>(undefined); } let fixture: ComponentFixture<LinkComponent>; let link: HTMLDivElement; let router: Router; beforeEach(async () => { TestBed.configureTestingModule({ imports: [RouterModule.forRoot([])], declarations: [LinkComponent], }); fixture = TestBed.createComponent(LinkComponent); await fixture.whenStable(); link = fixture.debugElement.query(By.css('div')).nativeElement; router = TestBed.inject(Router); spyOn(router, 'navigateByUrl'); link.click(); expect(router.navigateByUrl).toHaveBeenCalled(); (router.navigateByUrl as jasmine.Spy).calls.reset(); }); it('null, removes tabIndex and does not navigate', async () => { fixture.componentInstance.link.set(null); await fixture.whenStable(); expect(link.tabIndex).toEqual(-1); link.click(); expect(router.navigateByUrl).not.toHaveBeenCalled(); }); it('undefined, removes tabIndex and does not navigate', async () => { fixture.componentInstance.link.set(undefined); await fixture.whenStable(); expect(link.tabIndex).toEqual(-1); link.click(); expect(router.navigateByUrl).not.toHaveBeenCalled(); }); it('should coerce boolean input values', async () => { const dir = fixture.debugElement.query(By.directive(RouterLink)).injector.get(RouterLink); for (const truthy of [true, '', 'true', 'anything']) { fixture.componentInstance.preserveFragment.set(truthy); fixture.componentInstance.skipLocationChange.set(truthy); fixture.componentInstance.replaceUrl.set(truthy); await fixture.whenStable(); expect(dir.preserveFragment).toBeTrue(); expect(dir.skipLocationChange).toBeTrue(); expect(dir.replaceUrl).toBeTrue(); } for (const falsy of [false, null, undefined, 'false']) { fixture.componentInstance.preserveFragment.set(falsy); fixture.componentInstance.skipLocationChange.set(falsy); fixture.componentInstance.replaceUrl.set(falsy); await fixture.whenStable(); expect(dir.preserveFragment).toBeFalse(); expect(dir.skipLocationChange).toBeFalse(); expect(dir.replaceUrl).toBeFalse(); } }); }); describe('on an anchor', () => { describe('RouterLink for elements with `href` attributes', () => { @Component({ template: ` <a [routerLink]="link()" [preserveFragment]="preserveFragment()" [skipLocationChange]="skipLocationChange()" [replaceUrl]="replaceUrl()"></a> `, standalone: false, }) class LinkComponent { link = signal<string | null | undefined>('/'); preserveFragment = signal<unknown>(undefined); skipLocationChange = signal<unknown>(undefined); replaceUrl = signal<unknown>(undefined); } let fixture: ComponentFixture<LinkComponent>; let link: HTMLAnchorElement; beforeEach(async () => { TestBed.configureTestingModule({ imports: [RouterModule.forRoot([])], declarations: [LinkComponent], }); fixture = TestBed.createComponent(LinkComponent); await fixture.whenStable(); link = fixture.debugElement.query(By.css('a')).nativeElement; }); it('null, removes href', async () => { expect(link.outerHTML).toContain('href'); fixture.componentInstance.link.set(null); await fixture.whenStable(); expect(link.outerHTML).not.toContain('href'); }); it('undefined, removes href', async () => { expect(link.outerHTML).toContain('href'); fixture.componentInstance.link.set(undefined); await fixture.whenStable(); expect(link.outerHTML).not.toContain('href'); }); it('should coerce boolean input values', async () => { const dir = fixture.debugElement.query(By.directive(RouterLink)).injector.get(RouterLink); for (const truthy of [true, '', 'true', 'anything']) { fixture.componentInstance.preserveFragment.set(truthy); fixture.componentInstance.skipLocationChange.set(truthy); fixture.componentInstance.replaceUrl.set(truthy); await fixture.whenStable(); expect(dir.preserveFragment).toBeTrue(); expect(dir.skipLocationChange).toBeTrue(); expect(dir.replaceUrl).toBeTrue(); } for (const falsy of [false, null, undefined, 'false']) { fixture.componentInstance.preserveFragment.set(falsy); fixture.componentInstance.skipLocationChange.set(falsy); fixture.componentInstance.replaceUrl.set(falsy); await fixture.whenStable(); expect(dir.preserveFragment).toBeFalse(); expect(dir.skipLocationChange).toBeFalse(); expect(dir.replaceUrl).toBeFalse(); } }); }); it('should handle routerLink in svg templates', async () => { @Component({ template: `<svg><a routerLink="test"></a></svg>`, standalone: false, }) class LinkComponent {} TestBed.configureTestingModule({ imports: [RouterModule.forRoot([])], declarations: [LinkComponent], }); const fixture = TestBed.createComponent(LinkComponent); await fixture.whenStable(); const link = fixture.debugElement.query(By.css('a')).nativeElement; expect(link.outerHTML).toContain('href'); }); }); it('can use a UrlTree as the input', async () => { @Component({ standalone: true, template: '<a [routerLink]="urlTree">link</a>', imports: [RouterLink], }) class WithUrlTree { urlTree = inject(Router).createUrlTree(['/a/b/c']); } TestBed.configureTestingModule({providers: [provideRouter([])]}); const fixture = TestBed.createComponent(WithUrlTree); await fixture.whenStable(); expect(fixture.nativeElement.innerHTML).toContain('href="/a/b/c"'); }); it('cannnot use a UrlTree with queryParams', () => { @Component({ standalone: true, template: '<a [routerLink]="urlTree" [queryParams]="{}">link</a>', imports: [RouterLink], }) class WithUrlTree { urlTree = inject(Router).createUrlTree(['/a/b/c']); } TestBed.configureTestingModule({providers: [provideRouter([])]}); const fixture = TestBed.createComponent(WithUrlTree); expect(() => fixture.changeDetectorRef.detectChanges()).toThrow(); }); });
{ "end_byte": 8452, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/router_link_spec.ts" }
angular/packages/router/test/router.spec.ts_0_6149
/** * @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.dev/license */ import {Location} from '@angular/common'; import {EnvironmentInjector} from '@angular/core'; import {inject, TestBed} from '@angular/core/testing'; import {RouterModule} from '@angular/router'; import {of} from 'rxjs'; import {ChildActivationStart} from '../src/events'; import {GuardResult, Routes} from '../src/models'; import {NavigationTransition} from '../src/navigation_transition'; import {checkGuards as checkGuardsOperator} from '../src/operators/check_guards'; import {resolveData as resolveDataOperator} from '../src/operators/resolve_data'; import {Router} from '../src/router'; import {ChildrenOutletContexts} from '../src/router_outlet_context'; import {createEmptyStateSnapshot, RouterStateSnapshot} from '../src/router_state'; 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'; describe('Router', () => { describe('resetConfig', () => { class TestComponent {} beforeEach(() => { TestBed.configureTestingModule({imports: [RouterModule.forRoot([])]}); }); it('should copy config to avoid mutations of user-provided objects', () => { const r: Router = TestBed.inject(Router); const configs: Routes = [ { path: 'a', component: TestComponent, children: [ {path: 'b', component: TestComponent}, {path: 'c', component: TestComponent}, ], }, ]; const children = configs[0].children!; r.resetConfig(configs); const rConfigs = r.config; const rChildren = rConfigs[0].children!; // routes array and shallow copy expect(configs).not.toBe(rConfigs); expect(configs[0]).not.toBe(rConfigs[0]); expect(configs[0].path).toBe(rConfigs[0].path); expect(configs[0].component).toBe(rConfigs[0].component); // children should be new array and routes shallow copied expect(children).not.toBe(rChildren); expect(children[0]).not.toBe(rChildren[0]); expect(children[0].path).toBe(rChildren[0].path); expect(children[1]).not.toBe(rChildren[1]); expect(children[1].path).toBe(rChildren[1].path); }); }); describe('resetRootComponentType', () => { class NewRootComponent {} beforeEach(() => { TestBed.configureTestingModule({imports: [RouterModule.forRoot([])]}); }); it('should not change root route when updating the root component', () => { const r: Router = TestBed.inject(Router); const root = r.routerState.root; (r as any).resetRootComponentType(NewRootComponent); expect(r.routerState.root).toBe(root); }); }); describe('setUpLocationChangeListener', () => { beforeEach(() => { TestBed.configureTestingModule({imports: [RouterModule.forRoot([])]}); }); it('should be idempotent', inject([Router, Location], (r: Router, location: Location) => { r.setUpLocationChangeListener(); const a = (<any>r).nonRouterCurrentEntryChangeSubscription; r.setUpLocationChangeListener(); const b = (<any>r).nonRouterCurrentEntryChangeSubscription; expect(a).toBe(b); r.dispose(); r.setUpLocationChangeListener(); const c = (<any>r).nonRouterCurrentEntryChangeSubscription; expect(c).not.toBe(b); })); }); describe('PreActivation', () => { const serializer = new DefaultUrlSerializer(); let empty: RouterStateSnapshot; let logger: Logger; 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'; 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'), ), ], }); }); beforeEach(inject([Logger], (_logger: Logger) => { empty = createEmptyStateSnapshot(null); logger = _logger; events = []; }));
{ "end_byte": 6149, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/router.spec.ts" }
angular/packages/router/test/router.spec.ts_6155_14591
describe('ChildActivation', () => { it('should run', () => { /** * R --> R (ChildActivationStart) * \ * child */ let result = false; const childSnapshot = createActivatedRouteSnapshot({ component: 'child', routeConfig: {path: 'child'}, }); const futureState = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [new TreeNode(childSnapshot, [])]), ); // Since we only test the guards, we don't need to provide a full navigation // transition object with all properties set. const testTransition = { guards: getAllRouteGuards( futureState, empty, new ChildrenOutletContexts(TestBed.inject(EnvironmentInjector)), ), } as NavigationTransition; of(testTransition) .pipe( checkGuardsOperator(TestBed.inject(EnvironmentInjector), (evt) => { events.push(evt); }), ) .subscribe( (x) => (result = !!x.guardsResult), (e) => { throw e; }, ); expect(result).toBe(true); expect(events.length).toEqual(2); expect(events[0].snapshot).toBe(events[0].snapshot.root); expect(events[1].snapshot.routeConfig.path).toBe('child'); }); it('should run from top to bottom', () => { /** * R --> R (ChildActivationStart) * \ * child (ChildActivationStart) * \ * grandchild (ChildActivationStart) * \ * great grandchild */ let result = false; const childSnapshot = createActivatedRouteSnapshot({ component: 'child', routeConfig: {path: 'child'}, }); const grandchildSnapshot = createActivatedRouteSnapshot({ component: 'grandchild', routeConfig: {path: 'grandchild'}, }); const greatGrandchildSnapshot = createActivatedRouteSnapshot({ component: 'great-grandchild', routeConfig: {path: 'great-grandchild'}, }); const futureState = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [ new TreeNode(childSnapshot, [ new TreeNode(grandchildSnapshot, [new TreeNode(greatGrandchildSnapshot, [])]), ]), ]), ); // Since we only test the guards, we don't need to provide a full navigation // transition object with all properties set. const testTransition = { guards: getAllRouteGuards( futureState, empty, new ChildrenOutletContexts(TestBed.inject(EnvironmentInjector)), ), } as NavigationTransition; of(testTransition) .pipe( checkGuardsOperator(TestBed.inject(EnvironmentInjector), (evt) => { events.push(evt); }), ) .subscribe( (x) => (result = !!x.guardsResult), (e) => { throw e; }, ); expect(result).toBe(true); expect(events.length).toEqual(6); expect(events[0].snapshot).toBe(events[0].snapshot.root); expect(events[2].snapshot.routeConfig.path).toBe('child'); expect(events[4].snapshot.routeConfig.path).toBe('grandchild'); expect(events[5].snapshot.routeConfig.path).toBe('great-grandchild'); }); it('should not run for unchanged routes', () => { /** * R --> R * / \ * child child (ChildActivationStart) * \ * grandchild */ let result = false; const childSnapshot = createActivatedRouteSnapshot({ component: 'child', routeConfig: {path: 'child'}, }); const grandchildSnapshot = createActivatedRouteSnapshot({ component: 'grandchild', routeConfig: {path: 'grandchild'}, }); const currentState = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [new TreeNode(childSnapshot, [])]), ); const futureState = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [ new TreeNode(childSnapshot, [new TreeNode(grandchildSnapshot, [])]), ]), ); // Since we only test the guards, we don't need to provide a full navigation // transition object with all properties set. const testTransition = { guards: getAllRouteGuards( futureState, currentState, new ChildrenOutletContexts(TestBed.inject(EnvironmentInjector)), ), } as NavigationTransition; of(testTransition) .pipe( checkGuardsOperator(TestBed.inject(EnvironmentInjector), (evt) => { events.push(evt); }), ) .subscribe( (x) => (result = !!x.guardsResult), (e) => { throw e; }, ); expect(result).toBe(true); expect(events.length).toEqual(2); expect(events[0].snapshot).not.toBe(events[0].snapshot.root); expect(events[0].snapshot.routeConfig.path).toBe('child'); }); it('should skip multiple unchanged routes but fire for all changed routes', () => { /** * R --> R * / \ * child child * / \ * grandchild grandchild (ChildActivationStart) * \ * greatgrandchild (ChildActivationStart) * \ * great-greatgrandchild */ let result = false; const childSnapshot = createActivatedRouteSnapshot({ component: 'child', routeConfig: {path: 'child'}, }); const grandchildSnapshot = createActivatedRouteSnapshot({ component: 'grandchild', routeConfig: {path: 'grandchild'}, }); const greatGrandchildSnapshot = createActivatedRouteSnapshot({ component: 'greatgrandchild', routeConfig: {path: 'greatgrandchild'}, }); const greatGreatGrandchildSnapshot = createActivatedRouteSnapshot({ component: 'great-greatgrandchild', routeConfig: {path: 'great-greatgrandchild'}, }); const currentState = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [ new TreeNode(childSnapshot, [new TreeNode(grandchildSnapshot, [])]), ]), ); const futureState = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [ new TreeNode(childSnapshot, [ new TreeNode(grandchildSnapshot, [ new TreeNode(greatGrandchildSnapshot, [ new TreeNode(greatGreatGrandchildSnapshot, []), ]), ]), ]), ]), ); // Since we only test the guards, we don't need to provide a full navigation // transition object with all properties set. const testTransition = { guards: getAllRouteGuards( futureState, currentState, new ChildrenOutletContexts(TestBed.inject(EnvironmentInjector)), ), } as NavigationTransition; of(testTransition) .pipe( checkGuardsOperator(TestBed.inject(EnvironmentInjector), (evt) => { events.push(evt); }), ) .subscribe( (x) => (result = !!x.guardsResult), (e) => { throw e; }, ); expect(result).toBe(true); expect(events.length).toEqual(4); expect(events[0] instanceof ChildActivationStart).toBe(true); expect(events[0].snapshot).not.toBe(events[0].snapshot.root); expect(events[0].snapshot.routeConfig.path).toBe('grandchild'); expect(events[2].snapshot.routeConfig.path).toBe('greatgrandchild'); }); });
{ "end_byte": 14591, "start_byte": 6155, "url": "https://github.com/angular/angular/blob/main/packages/router/test/router.spec.ts" }
angular/packages/router/test/router.spec.ts_14597_22525
describe('guards', () => { it('should run CanActivate checks', () => { /** * R --> R * \ * child (CA, CAC) * \ * grandchild (CA) */ const childSnapshot = createActivatedRouteSnapshot({ component: 'child', routeConfig: { canActivate: [CA_CHILD], canActivateChild: [CAC_CHILD], }, }); const grandchildSnapshot = createActivatedRouteSnapshot({ component: 'grandchild', routeConfig: {canActivate: [CA_GRANDCHILD]}, }); const futureState = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [ new TreeNode(childSnapshot, [new TreeNode(grandchildSnapshot, [])]), ]), ); checkGuards(futureState, empty, TestBed.inject(EnvironmentInjector), (result) => { expect(result).toBe(true); expect(logger.logs).toEqual([CA_CHILD, CAC_CHILD, CA_GRANDCHILD]); }); }); it('should not run grandchild guards if child fails', () => { /** * R --> R * \ * child (CA: x, CAC) * \ * grandchild (CA) */ const childSnapshot = createActivatedRouteSnapshot({ component: 'child', routeConfig: {canActivate: [CA_CHILD_FALSE], canActivateChild: [CAC_CHILD]}, }); const grandchildSnapshot = createActivatedRouteSnapshot({ component: 'grandchild', routeConfig: {canActivate: [CA_GRANDCHILD]}, }); const futureState = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [ new TreeNode(childSnapshot, [new TreeNode(grandchildSnapshot, [])]), ]), ); checkGuards(futureState, empty, TestBed.inject(EnvironmentInjector), (result) => { expect(result).toBe(false); expect(logger.logs).toEqual([CA_CHILD_FALSE]); }); }); it('should not run grandchild guards if child canActivateChild fails', () => { /** * R --> R * \ * child (CA, CAC: x) * \ * grandchild (CA) */ const childSnapshot = createActivatedRouteSnapshot({ component: 'child', routeConfig: {canActivate: [CA_CHILD], canActivateChild: [CAC_CHILD_FALSE]}, }); const grandchildSnapshot = createActivatedRouteSnapshot({ component: 'grandchild', routeConfig: {canActivate: [CA_GRANDCHILD]}, }); const futureState = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [ new TreeNode(childSnapshot, [new TreeNode(grandchildSnapshot, [])]), ]), ); checkGuards(futureState, empty, TestBed.inject(EnvironmentInjector), (result) => { expect(result).toBe(false); expect(logger.logs).toEqual([CA_CHILD, CAC_CHILD_FALSE]); }); }); it('should run deactivate guards before activate guards', () => { /** * R --> R * / \ * prev (CDA) child (CA) * \ * grandchild (CA) */ const prevSnapshot = createActivatedRouteSnapshot({ component: 'prev', routeConfig: {canDeactivate: [CDA_CHILD]}, }); const childSnapshot = createActivatedRouteSnapshot({ component: 'child', routeConfig: {canActivate: [CA_CHILD], canActivateChild: [CAC_CHILD]}, }); const grandchildSnapshot = createActivatedRouteSnapshot({ component: 'grandchild', routeConfig: {canActivate: [CA_GRANDCHILD]}, }); const currentState = new (RouterStateSnapshot as any)( 'prev', new TreeNode(empty.root, [new TreeNode(prevSnapshot, [])]), ); const futureState = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [ new TreeNode(childSnapshot, [new TreeNode(grandchildSnapshot, [])]), ]), ); checkGuards(futureState, currentState, TestBed.inject(EnvironmentInjector), (result) => { expect(logger.logs).toEqual([CDA_CHILD, CA_CHILD, CAC_CHILD, CA_GRANDCHILD]); }); }); it('should not run activate if deactivate fails guards', () => { /** * R --> R * / \ * prev (CDA: x) child (CA) * \ * grandchild (CA) */ const prevSnapshot = createActivatedRouteSnapshot({ component: 'prev', routeConfig: {canDeactivate: [CDA_CHILD_FALSE]}, }); const childSnapshot = createActivatedRouteSnapshot({ component: 'child', routeConfig: {canActivate: [CA_CHILD], canActivateChild: [CAC_CHILD]}, }); const grandchildSnapshot = createActivatedRouteSnapshot({ component: 'grandchild', routeConfig: {canActivate: [CA_GRANDCHILD]}, }); const currentState = new (RouterStateSnapshot as any)( 'prev', new TreeNode(empty.root, [new TreeNode(prevSnapshot, [])]), ); const futureState = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [ new TreeNode(childSnapshot, [new TreeNode(grandchildSnapshot, [])]), ]), ); checkGuards(futureState, currentState, TestBed.inject(EnvironmentInjector), (result) => { expect(result).toBe(false); expect(logger.logs).toEqual([CDA_CHILD_FALSE]); }); }); it('should deactivate from bottom up, then activate top down', () => { /** * R --> R * / \ * prevChild (CDA) child (CA) * / \ * prevGrandchild(CDA) grandchild (CA) */ const prevChildSnapshot = createActivatedRouteSnapshot({ component: 'prev_child', routeConfig: {canDeactivate: [CDA_CHILD]}, }); const prevGrandchildSnapshot = createActivatedRouteSnapshot({ component: 'prev_grandchild', routeConfig: {canDeactivate: [CDA_GRANDCHILD]}, }); const childSnapshot = createActivatedRouteSnapshot({ component: 'child', routeConfig: {canActivate: [CA_CHILD], canActivateChild: [CAC_CHILD]}, }); const grandchildSnapshot = createActivatedRouteSnapshot({ component: 'grandchild', routeConfig: {canActivate: [CA_GRANDCHILD]}, }); const currentState = new (RouterStateSnapshot as any)( 'prev', new TreeNode(empty.root, [ new TreeNode(prevChildSnapshot, [new TreeNode(prevGrandchildSnapshot, [])]), ]), ); const futureState = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [ new TreeNode(childSnapshot, [new TreeNode(grandchildSnapshot, [])]), ]), ); 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, ]); }); logger.empty(); checkGuards(currentState, futureState, TestBed.inject(EnvironmentInjector), (result) => { expect(result).toBe(true); expect(logger.logs).toEqual([]); }); });
{ "end_byte": 22525, "start_byte": 14597, "url": "https://github.com/angular/angular/blob/main/packages/router/test/router.spec.ts" }
angular/packages/router/test/router.spec.ts_22533_31329
describe('UrlTree', () => { it('should allow return of UrlTree from CanActivate', () => { /** * R --> R * \ * child (CA: redirect) */ const childSnapshot = createActivatedRouteSnapshot({ component: 'child', routeConfig: { canActivate: [CA_CHILD_REDIRECT], }, }); const futureState = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [new TreeNode(childSnapshot, [])]), ); checkGuards(futureState, empty, TestBed.inject(EnvironmentInjector), (result) => { expect(serializer.serialize(result as UrlTree)).toBe('/' + CA_CHILD_REDIRECT); expect(logger.logs).toEqual([CA_CHILD_REDIRECT]); }); }); it('should allow return of UrlTree from CanActivateChild', () => { /** * R --> R * \ * child (CAC: redirect) * \ * grandchild (CA) */ const childSnapshot = createActivatedRouteSnapshot({ component: 'child', routeConfig: {canActivateChild: [CAC_CHILD_REDIRECT]}, }); const grandchildSnapshot = createActivatedRouteSnapshot({ component: 'grandchild', routeConfig: {canActivate: [CA_GRANDCHILD]}, }); const futureState = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [ new TreeNode(childSnapshot, [new TreeNode(grandchildSnapshot, [])]), ]), ); checkGuards(futureState, empty, TestBed.inject(EnvironmentInjector), (result) => { expect(serializer.serialize(result as UrlTree)).toBe('/' + CAC_CHILD_REDIRECT); expect(logger.logs).toEqual([CAC_CHILD_REDIRECT]); }); }); it('should allow return of UrlTree from a child CanActivate', () => { /** * R --> R * \ * child (CAC) * \ * grandchild (CA: redirect) */ const childSnapshot = createActivatedRouteSnapshot({ component: 'child', routeConfig: {canActivateChild: [CAC_CHILD]}, }); const grandchildSnapshot = createActivatedRouteSnapshot({ component: 'grandchild', routeConfig: {canActivate: [CA_GRANDCHILD_REDIRECT]}, }); const futureState = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [ new TreeNode(childSnapshot, [new TreeNode(grandchildSnapshot, [])]), ]), ); 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]); }); }); it('should allow return of UrlTree from a child CanDeactivate', () => { /** * R --> R * / \ * prev (CDA: redirect) child (CA) * \ * grandchild (CA) */ const prevSnapshot = createActivatedRouteSnapshot({ component: 'prev', routeConfig: {canDeactivate: [CDA_CHILD_REDIRECT]}, }); const childSnapshot = createActivatedRouteSnapshot({ component: 'child', routeConfig: {canActivate: [CA_CHILD], canActivateChild: [CAC_CHILD]}, }); const grandchildSnapshot = createActivatedRouteSnapshot({ component: 'grandchild', routeConfig: {canActivate: [CA_GRANDCHILD]}, }); const currentState = new (RouterStateSnapshot as any)( 'prev', new TreeNode(empty.root, [new TreeNode(prevSnapshot, [])]), ); const futureState = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [ new TreeNode(childSnapshot, [new TreeNode(grandchildSnapshot, [])]), ]), ); checkGuards(futureState, currentState, TestBed.inject(EnvironmentInjector), (result) => { expect(serializer.serialize(result as UrlTree)).toBe('/' + CDA_CHILD_REDIRECT); expect(logger.logs).toEqual([CDA_CHILD_REDIRECT]); }); }); }); }); describe('resolve', () => { it('should resolve data', () => { /** * R --> R * \ * a */ const r = {data: () => 'resolver_value'}; const n = createActivatedRouteSnapshot({component: 'a', resolve: r}); const s = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [new TreeNode(n, [])]), ); checkResolveData(s, empty, TestBed.inject(EnvironmentInjector), () => { expect(s.root.firstChild!.data).toEqual({data: 'resolver_value'}); }); }); it('should wait for the parent resolve to complete', () => { /** * R --> R * \ * null (resolve: parentResolve) * \ * b (resolve: childResolve) */ const parentResolve = {data: () => 'resolver_value'}; const childResolve = {}; const parent = createActivatedRouteSnapshot({component: null!, resolve: parentResolve}); const child = createActivatedRouteSnapshot({component: 'b', resolve: childResolve}); const s = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [new TreeNode(parent, [new TreeNode(child, [])])]), ); checkResolveData(s, empty, TestBed.inject(EnvironmentInjector), () => { expect(s.root.firstChild!.firstChild!.data).toEqual({data: 'resolver_value'}); }); }); it('should copy over data when creating a snapshot', () => { /** * R --> R --> R * \ \ * n1 (resolve: r1) n21 (resolve: r1) * \ * n22 (resolve: r2) */ const r1 = {data: () => 'resolver1_value'}; const r2 = {data: () => 'resolver2_value'}; const n1 = createActivatedRouteSnapshot({component: 'a', resolve: r1}); const s1 = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [new TreeNode(n1, [])]), ); checkResolveData(s1, empty, TestBed.inject(EnvironmentInjector), () => {}); const n21 = createActivatedRouteSnapshot({component: 'a', resolve: r1}); const n22 = createActivatedRouteSnapshot({component: 'b', resolve: r2}); const s2 = new (RouterStateSnapshot as any)( 'url', new TreeNode(empty.root, [new TreeNode(n21, [new TreeNode(n22, [])])]), ); checkResolveData(s2, s1, TestBed.inject(EnvironmentInjector), () => { expect(s2.root.firstChild!.data).toEqual({data: 'resolver1_value'}); expect(s2.root.firstChild!.firstChild!.data).toEqual({data: 'resolver2_value'}); }); }); }); }); }); function checkResolveData( future: RouterStateSnapshot, curr: RouterStateSnapshot, injector: EnvironmentInjector, check: any, ): void { // Since we only test the guards and their resolve data function, we don't need to provide // a full navigation transition object with all properties set. of({ guards: getAllRouteGuards(future, curr, new ChildrenOutletContexts(injector)), } as NavigationTransition) .pipe(resolveDataOperator('emptyOnly', injector)) .subscribe(check, (e) => { throw e; }); } function checkGuards( future: RouterStateSnapshot, curr: RouterStateSnapshot, injector: EnvironmentInjector, check: (result: GuardResult) => void, ): void { // Since we only test the guards, we don't need to provide a full navigation // transition object with all properties set. of({ guards: getAllRouteGuards(future, curr, new ChildrenOutletContexts(injector)), } as NavigationTransition) .pipe(checkGuardsOperator(injector)) .subscribe({ next(t) { if (t.guardsResult === null) throw new Error('Guard result expected'); return check(t.guardsResult); }, error(e) { throw e; }, }); }
{ "end_byte": 31329, "start_byte": 22533, "url": "https://github.com/angular/angular/blob/main/packages/router/test/router.spec.ts" }
angular/packages/router/test/url_tree.spec.ts_0_4994
/** * @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.dev/license */ import {exactMatchOptions, subsetMatchOptions} from '../src/router'; import {containsTree, DefaultUrlSerializer} from '../src/url_tree'; describe('UrlTree', () => { const serializer = new DefaultUrlSerializer(); describe('DefaultUrlSerializer', () => { let serializer: DefaultUrlSerializer; beforeEach(() => { serializer = new DefaultUrlSerializer(); }); it('should parse query parameters', () => { const tree = serializer.parse('/path/to?k=v&k/(a;b)=c'); expect(tree.queryParams).toEqual({ 'k': 'v', 'k/(a;b)': 'c', }); }); it('should allow question marks in query param values', () => { const tree = serializer.parse('/path/to?first=http://foo/bar?baz=true&second=123'); expect(tree.queryParams).toEqual({'first': 'http://foo/bar?baz=true', 'second': '123'}); }); }); describe('containsTree', () => { describe('exact = true', () => { it('should return true when two tree are the same', () => { const url = '/one/(one//left:three)(right:four)'; const t1 = serializer.parse(url); const t2 = serializer.parse(url); expect(containsTree(t1, t2, exactMatchOptions)).toBe(true); expect(containsTree(t2, t1, exactMatchOptions)).toBe(true); }); it('should return true when queryParams are the same', () => { const t1 = serializer.parse('/one/two?test=1&page=5'); const t2 = serializer.parse('/one/two?test=1&page=5'); expect(containsTree(t1, t2, exactMatchOptions)).toBe(true); }); it('should return true when queryParams are the same but with different order', () => { const t1 = serializer.parse('/one/two?test=1&page=5'); const t2 = serializer.parse('/one/two?page=5&test=1'); expect(containsTree(t1, t2, exactMatchOptions)).toBe(true); }); it('should return true when queryParams contains array params that are the same', () => { const t1 = serializer.parse('/one/two?test=a&test=b&pages=5&pages=6'); const t2 = serializer.parse('/one/two?test=a&test=b&pages=5&pages=6'); expect(containsTree(t1, t2, exactMatchOptions)).toBe(true); }); it('should return false when queryParams contains array params but are not the same', () => { const t1 = serializer.parse('/one/two?test=a&test=b&pages=5&pages=6'); const t2 = serializer.parse('/one/two?test=a&test=b&pages=5&pages=7'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); it('should return false when queryParams are not the same', () => { const t1 = serializer.parse('/one/two?test=1&page=5'); const t2 = serializer.parse('/one/two?test=1'); expect(containsTree(t1, t2, exactMatchOptions)).toBe(false); }); it('should return false when queryParams are not the same', () => { const t1 = serializer.parse('/one/two?test=4&test=4&test=2'); const t2 = serializer.parse('/one/two?test=4&test=3&test=2'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); it('should return true when queryParams are the same in different order', () => { const t1 = serializer.parse('/one/two?test=4&test=3&test=2'); const t2 = serializer.parse('/one/two?test=2&test=3&test=4'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return true when queryParams are the same in different order', () => { const t1 = serializer.parse('/one/two?test=4&test=4&test=1'); const t2 = serializer.parse('/one/two?test=1&test=4&test=4'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return false when containee is missing queryParams', () => { const t1 = serializer.parse('/one/two?page=5'); const t2 = serializer.parse('/one/two'); expect(containsTree(t1, t2, exactMatchOptions)).toBe(false); }); it('should return false when paths are not the same', () => { const t1 = serializer.parse('/one/two(right:three)'); const t2 = serializer.parse('/one/two2(right:three)'); expect(containsTree(t1, t2, exactMatchOptions)).toBe(false); }); it('should return false when container has an extra child', () => { const t1 = serializer.parse('/one/two(right:three)'); const t2 = serializer.parse('/one/two'); expect(containsTree(t1, t2, exactMatchOptions)).toBe(false); }); it('should return false when containee has an extra child', () => { const t1 = serializer.parse('/one/two'); const t2 = serializer.parse('/one/two(right:three)'); expect(containsTree(t1, t2, exactMatchOptions)).toBe(false); }); });
{ "end_byte": 4994, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/url_tree.spec.ts" }
angular/packages/router/test/url_tree.spec.ts_5000_10007
describe('exact = false', () => { it('should return true when containee is missing a segment', () => { const t1 = serializer.parse('/one/(two//left:three)(right:four)'); const t2 = serializer.parse('/one/(two//left:three)'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return true when containee is missing some paths', () => { const t1 = serializer.parse('/one/two/three'); const t2 = serializer.parse('/one/two'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return true container has its paths split into multiple segments', () => { const t1 = serializer.parse('/one/(two//left:three)'); const t2 = serializer.parse('/one/two'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return false when containee has extra segments', () => { const t1 = serializer.parse('/one/two'); const t2 = serializer.parse('/one/(two//left:three)'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); it('should return false containee has segments that the container does not have', () => { const t1 = serializer.parse('/one/(two//left:three)'); const t2 = serializer.parse('/one/(two//right:four)'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); it('should return false when containee has extra paths', () => { const t1 = serializer.parse('/one'); const t2 = serializer.parse('/one/two'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); it('should return true when queryParams are the same', () => { const t1 = serializer.parse('/one/two?test=1&page=5'); const t2 = serializer.parse('/one/two?test=1&page=5'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return true when container contains containees queryParams', () => { const t1 = serializer.parse('/one/two?test=1&u=5'); const t2 = serializer.parse('/one/two?u=5'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return true when containee does not have queryParams', () => { const t1 = serializer.parse('/one/two?page=5'); const t2 = serializer.parse('/one/two'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return false when containee has but container does not have queryParams', () => { const t1 = serializer.parse('/one/two'); const t2 = serializer.parse('/one/two?page=1'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); it('should return true when container has array params but containee does not have', () => { const t1 = serializer.parse('/one/two?test=a&test=b&pages=5&pages=6'); const t2 = serializer.parse('/one/two?test=a&test=b'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(true); }); it('should return false when containee has array params but container does not have', () => { const t1 = serializer.parse('/one/two?test=a&test=b'); const t2 = serializer.parse('/one/two?test=a&test=b&pages=5&pages=6'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); it('should return false when containee has different queryParams', () => { const t1 = serializer.parse('/one/two?page=5'); const t2 = serializer.parse('/one/two?test=1'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); it('should return false when containee has more queryParams than container', () => { const t1 = serializer.parse('/one/two?page=5'); const t2 = serializer.parse('/one/two?page=5&test=1'); expect(containsTree(t1, t2, subsetMatchOptions)).toBe(false); }); }); describe('ignored query params', () => { it('should return true when queryParams differ but are ignored', () => { const t1 = serializer.parse('/?test=1&page=2'); const t2 = serializer.parse('/?test=3&page=4&x=y'); expect(containsTree(t1, t2, {...exactMatchOptions, queryParams: 'ignored'})).toBe(true); }); }); describe('fragment', () => { it('should return false when fragments differ but options require exact match', () => { const t1 = serializer.parse('/#fragment1'); const t2 = serializer.parse('/#fragment2'); expect(containsTree(t1, t2, {...exactMatchOptions, fragment: 'exact'})).toBe(false); }); it('should return true when fragments differ but options ignore the fragment', () => { const t1 = serializer.parse('/#fragment1'); const t2 = serializer.parse('/#fragment2'); expect(containsTree(t1, t2, {...exactMatchOptions, fragment: 'ignored'})).toBe(true); }); });
{ "end_byte": 10007, "start_byte": 5000, "url": "https://github.com/angular/angular/blob/main/packages/router/test/url_tree.spec.ts" }
angular/packages/router/test/url_tree.spec.ts_10013_13491
describe('matrix params', () => { describe('ignored', () => { it('returns true when matrix params differ but are ignored', () => { const t1 = serializer.parse('/a;id=15;foo=foo'); const t2 = serializer.parse('/a;abc=123'); expect(containsTree(t1, t2, {...exactMatchOptions, matrixParams: 'ignored'})).toBe(true); }); }); describe('exact match', () => { const matrixParams = 'exact'; it('returns true when matrix params match', () => { const t1 = serializer.parse('/a;id=15;foo=foo'); const t2 = serializer.parse('/a;id=15;foo=foo'); expect(containsTree(t1, t2, {...exactMatchOptions, matrixParams})).toBe(true); }); it('returns false when matrix params differ', () => { const t1 = serializer.parse('/a;id=15;foo=foo'); const t2 = serializer.parse('/a;abc=123'); expect(containsTree(t1, t2, {...exactMatchOptions, matrixParams})).toBe(false); }); it('returns true when matrix params match on the subset of the matched url tree', () => { const t1 = serializer.parse('/a;id=15;foo=bar/c'); const t2 = serializer.parse('/a;id=15;foo=bar'); expect(containsTree(t1, t2, {...subsetMatchOptions, matrixParams})).toBe(true); }); it( 'should return true when matrix params match on subset of urlTree match ' + 'with container paths split into multiple segments', () => { const t1 = serializer.parse('/one;a=1/(two;b=2//left:three)'); const t2 = serializer.parse('/one;a=1/two;b=2'); expect(containsTree(t1, t2, {...subsetMatchOptions, matrixParams})).toBe(true); }, ); }); describe('subset match', () => { const matrixParams = 'subset'; it('returns true when matrix params match', () => { const t1 = serializer.parse('/a;id=15;foo=foo'); const t2 = serializer.parse('/a;id=15;foo=foo'); expect(containsTree(t1, t2, {...exactMatchOptions, matrixParams})).toBe(true); }); it('returns true when container has extra matrix params', () => { const t1 = serializer.parse('/a;id=15;foo=foo'); const t2 = serializer.parse('/a;id=15'); expect(containsTree(t1, t2, {...exactMatchOptions, matrixParams})).toBe(true); }); it('returns false when matrix params differ', () => { const t1 = serializer.parse('/a;id=15;foo=foo'); const t2 = serializer.parse('/a;abc=123'); expect(containsTree(t1, t2, {...exactMatchOptions, matrixParams})).toBe(false); }); it('returns true when matrix params match on the subset of the matched url tree', () => { const t1 = serializer.parse('/a;id=15;foo=bar/c'); const t2 = serializer.parse('/a;id=15;foo=bar'); expect(containsTree(t1, t2, {...subsetMatchOptions, matrixParams})).toBe(true); }); it( 'should return true when matrix params match on subset of urlTree match ' + 'with container paths split into multiple segments', () => { const t1 = serializer.parse('/one;a=1/(two;b=2//left:three)'); const t2 = serializer.parse('/one;a=1/two'); expect(containsTree(t1, t2, {...subsetMatchOptions, matrixParams})).toBe(true); }, ); }); }); }); });
{ "end_byte": 13491, "start_byte": 10013, "url": "https://github.com/angular/angular/blob/main/packages/router/test/url_tree.spec.ts" }
angular/packages/router/test/recognize.spec.ts_0_5866
/** * @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.dev/license */ import {EnvironmentInjector} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {Routes, UrlMatcher} from '../src/models'; import {Recognizer} from '../src/recognize'; import {RouterConfigLoader} from '../src/router_config_loader'; import {ActivatedRouteSnapshot, RouterStateSnapshot} from '../src/router_state'; import {Params, PRIMARY_OUTLET} from '../src/shared'; import {DefaultUrlSerializer, UrlTree} from '../src/url_tree'; describe('recognize', async () => { it('should work', async () => { const s = await recognize([{path: 'a', component: ComponentA}], 'a'); checkActivatedRoute(s.root, '', {}, RootComponent); checkActivatedRoute(s.root.firstChild!, 'a', {}, ComponentA); }); it('should freeze params object', async () => { const s: RouterStateSnapshot = await recognize( [{path: 'a/:id', component: ComponentA}], 'a/10', ); checkActivatedRoute(s.root, '', {}, RootComponent); const child = s.root.firstChild!; expect(Object.isFrozen(child.params)).toBeTruthy(); }); it('should freeze data object (but not original route data)', async () => { const someData = {a: 1}; const s: RouterStateSnapshot = await recognize( [{path: '**', component: ComponentA, data: someData}], 'a', ); checkActivatedRoute(s.root, '', {}, RootComponent); const child = s.root.firstChild!; expect(Object.isFrozen(child.data)).toBeTruthy(); expect(Object.isFrozen(someData)).toBeFalsy(); }); it('should support secondary routes', async () => { const s: RouterStateSnapshot = await recognize( [ {path: 'a', component: ComponentA}, {path: 'b', component: ComponentB, outlet: 'left'}, {path: 'c', component: ComponentC, outlet: 'right'}, ], 'a(left:b//right:c)', ); const c = s.root.children; checkActivatedRoute(c[0], 'a', {}, ComponentA); checkActivatedRoute(c[1], 'b', {}, ComponentB, 'left'); checkActivatedRoute(c[2], 'c', {}, ComponentC, 'right'); }); it('should set url segment and index properly', async () => { const url = tree('a(left:b//right:c)'); const s = await recognize( [ {path: 'a', component: ComponentA}, {path: 'b', component: ComponentB, outlet: 'left'}, {path: 'c', component: ComponentC, outlet: 'right'}, ], 'a(left:b//right:c)', ); expect(s.root.url.toString()).toEqual(url.root.toString()); const c = s.root.children; expect(c[0].url.toString()).toEqual(url.root.children[PRIMARY_OUTLET].toString()); expect(c[1].url.toString()).toEqual(url.root.children['left'].toString()); expect(c[2].url.toString()).toEqual(url.root.children['right'].toString()); }); it('should match routes in the depth first order', async () => { const s = await recognize( [ {path: 'a', component: ComponentA, children: [{path: ':id', component: ComponentB}]}, {path: 'a/:id', component: ComponentC}, ], 'a/paramA', ); checkActivatedRoute(s.root, '', {}, RootComponent); checkActivatedRoute(s.root.firstChild!, 'a', {}, ComponentA); checkActivatedRoute(s.root.firstChild!.firstChild!, 'paramA', {id: 'paramA'}, ComponentB); const s2 = await recognize( [ {path: 'a', component: ComponentA}, {path: 'a/:id', component: ComponentC}, ], 'a/paramA', ); checkActivatedRoute(s2.root, '', {}, RootComponent); checkActivatedRoute(s2.root.firstChild!, 'a/paramA', {id: 'paramA'}, ComponentC); }); it('should use outlet name when matching secondary routes', async () => { const s = await recognize( [ {path: 'a', component: ComponentA}, {path: 'b', component: ComponentB, outlet: 'left'}, {path: 'b', component: ComponentC, outlet: 'right'}, ], 'a(right:b)', ); const c = s.root.children; checkActivatedRoute(c[0], 'a', {}, ComponentA); checkActivatedRoute(c[1], 'b', {}, ComponentC, 'right'); }); it('should handle non top-level secondary routes', async () => { const s = await recognize( [ { path: 'a', component: ComponentA, children: [ {path: 'b', component: ComponentB}, {path: 'c', component: ComponentC, outlet: 'left'}, ], }, ], 'a/(b//left:c)', ); const c = s.root.firstChild!.children; checkActivatedRoute(c[0], 'b', {}, ComponentB, PRIMARY_OUTLET); checkActivatedRoute(c[1], 'c', {}, ComponentC, 'left'); }); it('should sort routes by outlet name', async () => { const s = await recognize( [ {path: 'a', component: ComponentA}, {path: 'c', component: ComponentC, outlet: 'c'}, {path: 'b', component: ComponentB, outlet: 'b'}, ], 'a(c:c//b:b)', ); const c = s.root.children; checkActivatedRoute(c[0], 'a', {}, ComponentA); checkActivatedRoute(c[1], 'b', {}, ComponentB, 'b'); checkActivatedRoute(c[2], 'c', {}, ComponentC, 'c'); }); it('should support matrix parameters', async () => { const s = await recognize( [ {path: 'a', component: ComponentA, children: [{path: 'b', component: ComponentB}]}, {path: 'c', component: ComponentC, outlet: 'left'}, ], 'a;a1=11;a2=22/b;b1=111;b2=222(left:c;c1=1111;c2=2222)', ); const c = s.root.children; checkActivatedRoute(c[0], 'a', {a1: '11', a2: '22'}, ComponentA); checkActivatedRoute(c[0].firstChild!, 'b', {b1: '111', b2: '222'}, ComponentB); checkActivatedRoute(c[1], 'c', {c1: '1111', c2: '2222'}, ComponentC, 'left'); });
{ "end_byte": 5866, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/recognize.spec.ts" }
angular/packages/router/test/recognize.spec.ts_5870_8306
describe('data', async () => { it('should set static data', async () => { const s = await recognize([{path: 'a', data: {one: 1}, component: ComponentA}], 'a'); const r: ActivatedRouteSnapshot = s.root.firstChild!; expect(r.data).toEqual({one: 1}); }); it("should inherit componentless route's data", async () => { const s = await recognize( [ { path: 'a', data: {one: 1}, children: [{path: 'b', data: {two: 2}, component: ComponentB}], }, ], 'a/b', ); const r: ActivatedRouteSnapshot = s.root.firstChild!.firstChild!; expect(r.data).toEqual({one: 1, two: 2}); }); it("should not inherit route's data if it has component", async () => { const s = await recognize( [ { path: 'a', component: ComponentA, data: {one: 1}, children: [{path: 'b', data: {two: 2}, component: ComponentB}], }, ], 'a/b', ); const r: ActivatedRouteSnapshot = s.root.firstChild!.firstChild!; expect(r.data).toEqual({two: 2}); }); it("should not inherit route's data if it has loadComponent", async () => { const s = await recognize( [ { path: 'a', loadComponent: () => ComponentA, data: {one: 1}, children: [{path: 'b', data: {two: 2}, component: ComponentB}], }, ], 'a/b', ); const r: ActivatedRouteSnapshot = s.root.firstChild!.firstChild!; expect(r.data).toEqual({two: 2}); }); it("should inherit route's data if paramsInheritanceStrategy is 'always'", async () => { const s = await recognize( [ { path: 'a', component: ComponentA, data: {one: 1}, children: [{path: 'b', data: {two: 2}, component: ComponentB}], }, ], 'a/b', 'always', ); const r: ActivatedRouteSnapshot = s.root.firstChild!.firstChild!; expect(r.data).toEqual({one: 1, two: 2}); }); it('should set resolved data', async () => { const s = await recognize( [{path: 'a', resolve: {one: 'some-token'}, component: ComponentA}], 'a', ); const r: any = s.root.firstChild!; expect(r._resolve).toEqual({one: 'some-token'}); }); });
{ "end_byte": 8306, "start_byte": 5870, "url": "https://github.com/angular/angular/blob/main/packages/router/test/recognize.spec.ts" }
angular/packages/router/test/recognize.spec.ts_8310_15914
describe('empty path', async () => { describe('root', async () => { it('should work', async () => { const s = await recognize([{path: '', component: ComponentA}], ''); checkActivatedRoute(s.root.firstChild!, '', {}, ComponentA); }); it('should match when terminal', async () => { const s = await recognize([{path: '', pathMatch: 'full', component: ComponentA}], ''); checkActivatedRoute(s.root.firstChild!, '', {}, ComponentA); }); it('should work (nested case)', async () => { const s = await recognize( [{path: '', component: ComponentA, children: [{path: '', component: ComponentB}]}], '', ); checkActivatedRoute(s.root.firstChild!, '', {}, ComponentA); checkActivatedRoute(s.root.firstChild!.firstChild!, '', {}, ComponentB); }); it('should inherit params', async () => { const s = await recognize( [ { path: 'a', component: ComponentA, children: [ {path: '', component: ComponentB, children: [{path: '', component: ComponentC}]}, ], }, ], '/a;p=1', ); checkActivatedRoute(s.root.firstChild!, 'a', {p: '1'}, ComponentA); checkActivatedRoute(s.root.firstChild!.firstChild!, '', {p: '1'}, ComponentB); checkActivatedRoute(s.root.firstChild!.firstChild!.firstChild!, '', {p: '1'}, ComponentC); }); }); describe('aux split is in the middle', async () => { it('should match (non-terminal)', async () => { const s = await recognize( [ { path: 'a', component: ComponentA, children: [ {path: 'b', component: ComponentB}, {path: '', component: ComponentC, outlet: 'aux'}, ], }, ], 'a/b', ); checkActivatedRoute(s.root.firstChild!, 'a', {}, ComponentA); const c = s.root.firstChild!.children; checkActivatedRoute(c[0], 'b', {}, ComponentB); checkActivatedRoute(c[1], '', {}, ComponentC, 'aux'); }); it('should match (non-terminal) when both primary and secondary and primary has a child', async () => { const config = [ { path: 'parent', children: [ { path: '', component: ComponentA, children: [ {path: 'b', component: ComponentB}, {path: 'c', component: ComponentC}, ], }, { path: '', component: ComponentD, outlet: 'secondary', }, ], }, ]; const s = await recognize(config, 'parent/b'); checkActivatedRoute(s.root, '', {}, RootComponent); checkActivatedRoute(s.root.firstChild!, 'parent', {}, null); const cc = s.root.firstChild!.children; checkActivatedRoute(cc[0], '', {}, ComponentA); checkActivatedRoute(cc[1], '', {}, ComponentD, 'secondary'); checkActivatedRoute(cc[0].firstChild!, 'b', {}, ComponentB); }); it('should match (terminal)', async () => { const s = await recognize( [ { path: 'a', component: ComponentA, children: [ {path: 'b', component: ComponentB}, {path: '', pathMatch: 'full', component: ComponentC, outlet: 'aux'}, ], }, ], 'a/b', ); checkActivatedRoute(s.root.firstChild!, 'a', {}, ComponentA); const c = s.root.firstChild!.children; expect(c.length).toEqual(1); checkActivatedRoute(c[0], 'b', {}, ComponentB); }); }); describe('aux split at the end (no right child)', async () => { it('should match (non-terminal)', async () => { const s = await recognize( [ { path: 'a', component: ComponentA, children: [ {path: '', component: ComponentB}, {path: '', component: ComponentC, outlet: 'aux'}, ], }, ], 'a', ); checkActivatedRoute(s.root.firstChild!, 'a', {}, ComponentA); const c = s.root.firstChild!.children; checkActivatedRoute(c[0], '', {}, ComponentB); checkActivatedRoute(c[1], '', {}, ComponentC, 'aux'); }); it('should match (terminal)', async () => { const s = await recognize( [ { path: 'a', component: ComponentA, children: [ {path: '', pathMatch: 'full', component: ComponentB}, {path: '', pathMatch: 'full', component: ComponentC, outlet: 'aux'}, ], }, ], 'a', ); checkActivatedRoute(s.root.firstChild!, 'a', {}, ComponentA); const c = s.root.firstChild!.children; checkActivatedRoute(c[0], '', {}, ComponentB); checkActivatedRoute(c[1], '', {}, ComponentC, 'aux'); }); it('should work only only primary outlet', async () => { const s = await recognize( [ { path: 'a', component: ComponentA, children: [ {path: '', component: ComponentB}, {path: 'c', component: ComponentC, outlet: 'aux'}, ], }, ], 'a/(aux:c)', ); checkActivatedRoute(s.root.firstChild!, 'a', {}, ComponentA); const c = s.root.firstChild!.children; checkActivatedRoute(c[0], '', {}, ComponentB); checkActivatedRoute(c[1], 'c', {}, ComponentC, 'aux'); }); it('should work when split is at the root level', async () => { const s = await recognize( [ {path: '', component: ComponentA}, {path: 'b', component: ComponentB}, {path: 'c', component: ComponentC, outlet: 'aux'}, ], '(aux:c)', ); checkActivatedRoute(s.root, '', {}, RootComponent); const children = s.root.children; expect(children.length).toEqual(2); checkActivatedRoute(children[0], '', {}, ComponentA); checkActivatedRoute(children[1], 'c', {}, ComponentC, 'aux'); }); }); describe('split at the end (right child)', async () => { it('should match (non-terminal)', async () => { const s = await recognize( [ { path: 'a', component: ComponentA, children: [ {path: '', component: ComponentB, children: [{path: 'd', component: ComponentD}]}, { path: '', component: ComponentC, outlet: 'aux', children: [{path: 'e', component: ComponentE}], }, ], }, ], 'a/(d//aux:e)', ); checkActivatedRoute(s.root.firstChild!, 'a', {}, ComponentA); const c = s.root.firstChild!.children; checkActivatedRoute(c[0], '', {}, ComponentB); checkActivatedRoute(c[0].firstChild!, 'd', {}, ComponentD); checkActivatedRoute(c[1], '', {}, ComponentC, 'aux'); checkActivatedRoute(c[1].firstChild!, 'e', {}, ComponentE); }); });
{ "end_byte": 15914, "start_byte": 8310, "url": "https://github.com/angular/angular/blob/main/packages/router/test/recognize.spec.ts" }
angular/packages/router/test/recognize.spec.ts_15920_23069
describe('with outlets', async () => { it('should work when outlet is a child of empty path parent', async () => { const s = await recognize( [ { path: '', component: ComponentA, children: [{path: 'b', outlet: 'b', component: ComponentB}], }, ], '(b:b)', ); checkActivatedRoute(s.root.children[0], '', {}, ComponentA); checkActivatedRoute(s.root.children[0].children[0], 'b', {}, ComponentB, 'b'); }); it('should work for outlets adjacent to empty path', async () => { const s = await recognize( [ { path: '', component: ComponentA, children: [{path: '', component: ComponentC}], }, {path: 'b', outlet: 'b', component: ComponentB}, ], '(b:b)', ); const [primaryChild, outletChild] = s.root.children; checkActivatedRoute(primaryChild, '', {}, ComponentA); checkActivatedRoute(outletChild, 'b', {}, ComponentB, 'b'); checkActivatedRoute(primaryChild.children[0], '', {}, ComponentC); }); it('should work with named outlets both adjecent to and as a child of empty path', async () => { const s = await recognize( [ { path: '', component: ComponentA, children: [{path: 'b', outlet: 'b', component: ComponentB}], }, {path: 'c', outlet: 'c', component: ComponentC}, ], '(b:b//c:c)', ); checkActivatedRoute(s.root.children[0], '', {}, ComponentA); checkActivatedRoute(s.root.children[1], 'c', {}, ComponentC, 'c'); checkActivatedRoute(s.root.children[0].children[0], 'b', {}, ComponentB, 'b'); }); it('should work with children outlets within two levels of empty parents', async () => { const s = await recognize( [ { path: '', component: ComponentA, children: [ { path: '', component: ComponentB, children: [{path: 'c', outlet: 'c', component: ComponentC}], }, ], }, ], '(c:c)', ); const [compAConfig] = s.root.children; checkActivatedRoute(compAConfig, '', {}, ComponentA); expect(compAConfig.children.length).toBe(1); const [compBConfig] = compAConfig.children; checkActivatedRoute(compBConfig, '', {}, ComponentB); expect(compBConfig.children.length).toBe(1); const [compCConfig] = compBConfig.children; checkActivatedRoute(compCConfig, 'c', {}, ComponentC, 'c'); }); it('should not persist a primary segment beyond the boundary of a named outlet match', async () => { const recognizePromise = new Recognizer( TestBed.inject(EnvironmentInjector), TestBed.inject(RouterConfigLoader), RootComponent, [ { path: '', component: ComponentA, outlet: 'a', children: [{path: 'b', component: ComponentB}], }, ], tree('/b'), 'emptyOnly', new DefaultUrlSerializer(), ) .recognize() .toPromise(); await expectAsync(recognizePromise).toBeRejected(); }); }); }); describe('wildcards', async () => { it('should support simple wildcards', async () => { const s = await recognize([{path: '**', component: ComponentA}], 'a/b/c/d;a1=11'); checkActivatedRoute(s.root.firstChild!, 'a/b/c/d', {a1: '11'}, ComponentA); }); }); describe('componentless routes', async () => { it('should work', async () => { const s = await recognize( [ { path: 'p/:id', children: [ {path: 'a', component: ComponentA}, {path: 'b', component: ComponentB, outlet: 'aux'}, ], }, ], 'p/11;pp=22/(a;pa=33//aux:b;pb=44)', ); const p = s.root.firstChild!; checkActivatedRoute(p, 'p/11', {id: '11', pp: '22'}, null); const c = p.children; checkActivatedRoute(c[0], 'a', {id: '11', pp: '22', pa: '33'}, ComponentA); checkActivatedRoute(c[1], 'b', {id: '11', pp: '22', pb: '44'}, ComponentB, 'aux'); }); it('should inherit params until encounters a normal route', async () => { const s = await recognize( [ { path: 'p/:id', children: [ { path: 'a/:name', children: [ { path: 'b', component: ComponentB, children: [{path: 'c', component: ComponentC}], }, ], }, ], }, ], 'p/11/a/victor/b/c', ); const p = s.root.firstChild!; checkActivatedRoute(p, 'p/11', {id: '11'}, null); const a = p.firstChild!; checkActivatedRoute(a, 'a/victor', {id: '11', name: 'victor'}, null); const b = a.firstChild!; checkActivatedRoute(b, 'b', {id: '11', name: 'victor'}, ComponentB); const c = b.firstChild!; checkActivatedRoute(c, 'c', {}, ComponentC); }); it("should inherit all params if paramsInheritanceStrategy is 'always'", async () => { const s = await recognize( [ { path: 'p/:id', children: [ { path: 'a/:name', children: [ { path: 'b', component: ComponentB, children: [{path: 'c', component: ComponentC}], }, ], }, ], }, ], 'p/11/a/victor/b/c', 'always', ); const c = s.root.firstChild!.firstChild!.firstChild!.firstChild!; checkActivatedRoute(c, 'c', {id: '11', name: 'victor'}, ComponentC); }); }); describe('empty URL leftovers', async () => { it('should not throw when no children matching', async () => { const s = await recognize( [{path: 'a', component: ComponentA, children: [{path: 'b', component: ComponentB}]}], '/a', ); const a = s.root.firstChild; checkActivatedRoute(a!, 'a', {}, ComponentA); }); it('should not throw when no children matching (aux routes)', async () => { const s = await recognize( [ { path: 'a', component: ComponentA, children: [ {path: 'b', component: ComponentB}, {path: '', component: ComponentC, outlet: 'aux'}, ], }, ], '/a', ); const a = s.root.firstChild!; checkActivatedRoute(a, 'a', {}, ComponentA); checkActivatedRoute(a.children[0], '', {}, ComponentC, 'aux'); }); });
{ "end_byte": 23069, "start_byte": 15920, "url": "https://github.com/angular/angular/blob/main/packages/router/test/recognize.spec.ts" }
angular/packages/router/test/recognize.spec.ts_23073_27562
describe('custom path matchers', async () => { it('should run once', async () => { let calls = 0; const matcher: UrlMatcher = (s) => { calls++; return {consumed: s}; }; const s = await recognize( [ { matcher, component: ComponentA, }, ], '/a/1/b', ); const a = s.root.firstChild!; checkActivatedRoute(a, 'a/1/b', {}, ComponentA); expect(calls).toBe(1); }); it('should use custom path matcher', async () => { const matcher = (s: any, g: any, r: any) => { if (s[0].path === 'a') { return {consumed: s.slice(0, 2), posParams: {id: s[1]}}; } else { return null; } }; const s = await recognize( [ { matcher: matcher, component: ComponentA, children: [{path: 'b', component: ComponentB}], }, ] as any, '/a/1;p=99/b', ); const a = s.root.firstChild!; checkActivatedRoute(a, 'a/1', {id: '1', p: '99'}, ComponentA); checkActivatedRoute(a.firstChild!, 'b', {}, ComponentB); }); it('should work with terminal route', async () => { const matcher = (s: any, g: any, r: any) => (s.length === 0 ? {consumed: s} : null); const s = await recognize([{matcher, component: ComponentA}], ''); const a = s.root.firstChild!; checkActivatedRoute(a, '', {}, ComponentA); }); it('should work with child terminal route', async () => { const matcher = (s: any, g: any, r: any) => (s.length === 0 ? {consumed: s} : null); const s = await recognize( [{path: 'a', component: ComponentA, children: [{matcher, component: ComponentB}]}], 'a', ); const a = s.root.firstChild!; checkActivatedRoute(a, 'a', {}, ComponentA); }); }); describe('query parameters', async () => { it('should support query params', async () => { const config = [{path: 'a', component: ComponentA}]; const s = await recognize(config, 'a?q=11'); expect(s.root.queryParams).toEqual({q: '11'}); expect(s.root.queryParamMap.get('q')).toEqual('11'); }); it('should freeze query params object', async () => { const s = await recognize([{path: 'a', component: ComponentA}], 'a?q=11'); expect(Object.isFrozen(s.root.queryParams)).toBeTruthy(); }); it('should not freeze UrlTree query params', async () => { const url = tree('a?q=11'); const s = await recognize([{path: 'a', component: ComponentA}], 'a?q=11'); expect(Object.isFrozen(url.queryParams)).toBe(false); }); }); describe('fragment', async () => { it('should support fragment', async () => { const config = [{path: 'a', component: ComponentA}]; const s = await recognize(config, 'a#f1'); expect(s.root.fragment).toEqual('f1'); }); }); describe('guards', () => { it('should run canMatch guards on wildcard routes', async () => { const config = [ {path: '**', component: ComponentA, data: {id: 'a'}, canMatch: [() => false]}, {path: '**', component: ComponentB, data: {id: 'b'}}, ]; const s = await recognize(config, 'a'); expect(s.root.firstChild!.data['id']).toEqual('b'); }); }); }); async function recognize( config: Routes, url: string, paramsInheritanceStrategy: 'emptyOnly' | 'always' = 'emptyOnly', ): Promise<RouterStateSnapshot> { const serializer = new DefaultUrlSerializer(); const result = await new Recognizer( TestBed.inject(EnvironmentInjector), TestBed.inject(RouterConfigLoader), RootComponent, config, tree(url), paramsInheritanceStrategy, serializer, ) .recognize() .toPromise(); return result!.state; } function checkActivatedRoute( actual: ActivatedRouteSnapshot, url: string, params: Params, cmp: Function | null, outlet: string = PRIMARY_OUTLET, ): void { if (actual === null) { expect(actual).not.toBeNull(); } else { expect(actual.url.map((s) => s.path).join('/')).toEqual(url); expect(actual.params).toEqual(params); expect(actual.component).toBe(cmp); expect(actual.outlet).toEqual(outlet); } } function tree(url: string): UrlTree { return new DefaultUrlSerializer().parse(url); } class RootComponent {} class ComponentA {} class ComponentB {} class ComponentC {} class ComponentD {} class ComponentE {}
{ "end_byte": 27562, "start_byte": 23073, "url": "https://github.com/angular/angular/blob/main/packages/router/test/recognize.spec.ts" }
angular/packages/router/test/create_router_state.spec.ts_0_6832
/** * @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.dev/license */ import {EnvironmentInjector} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {map} from 'rxjs/operators'; import {createRouterState} from '../src/create_router_state'; import {Routes} from '../src/models'; import {recognize} from '../src/recognize'; import {DefaultRouteReuseStrategy} from '../src/route_reuse_strategy'; import {RouterConfigLoader} from '../src/router_config_loader'; import { ActivatedRoute, advanceActivatedRoute, createEmptyState, RouterState, RouterStateSnapshot, } from '../src/router_state'; import {PRIMARY_OUTLET} from '../src/shared'; import {DefaultUrlSerializer, UrlTree} from '../src/url_tree'; import {TreeNode} from '../src/utils/tree'; describe('create router state', async () => { let reuseStrategy: DefaultRouteReuseStrategy; beforeEach(() => { reuseStrategy = new DefaultRouteReuseStrategy(); }); const emptyState = () => createEmptyState(RootComponent); it('should create new state', async () => { const state = createRouterState( reuseStrategy, await createState( [ {path: 'a', component: ComponentA}, {path: 'b', component: ComponentB, outlet: 'left'}, {path: 'c', component: ComponentC, outlet: 'right'}, ], 'a(left:b//right:c)', ), emptyState(), ); checkActivatedRoute(state.root, RootComponent); const c = (state as any).children(state.root); checkActivatedRoute(c[0], ComponentA); checkActivatedRoute(c[1], ComponentB, 'left'); checkActivatedRoute(c[2], ComponentC, 'right'); }); it('should reuse existing nodes when it can', async () => { const config = [ {path: 'a', component: ComponentA}, {path: 'b', component: ComponentB, outlet: 'left'}, {path: 'c', component: ComponentC, outlet: 'left'}, ]; const prevState = createRouterState( reuseStrategy, await createState(config, 'a(left:b)'), emptyState(), ); advanceState(prevState); const state = createRouterState( reuseStrategy, await createState(config, 'a(left:c)'), prevState, ); expect(prevState.root).toBe(state.root); const prevC = (prevState as any).children(prevState.root); const currC = (state as any).children(state.root); expect(prevC[0]).toBe(currC[0]); expect(prevC[1]).not.toBe(currC[1]); checkActivatedRoute(currC[1], ComponentC, 'left'); }); it('should handle componentless routes', async () => { const config = [ { path: 'a/:id', children: [ {path: 'b', component: ComponentA}, {path: 'c', component: ComponentB, outlet: 'right'}, ], }, ]; const prevState = createRouterState( reuseStrategy, await createState(config, 'a/1;p=11/(b//right:c)'), emptyState(), ); advanceState(prevState); const state = createRouterState( reuseStrategy, await createState(config, 'a/2;p=22/(b//right:c)'), prevState, ); expect(prevState.root).toBe(state.root); const prevP = (prevState as any).firstChild(prevState.root)!; const currP = (state as any).firstChild(state.root)!; expect(prevP).toBe(currP); const currC = (state as any).children(currP); expect(currP._futureSnapshot.params).toEqual({id: '2', p: '22'}); expect(currP._futureSnapshot.paramMap.get('id')).toEqual('2'); expect(currP._futureSnapshot.paramMap.get('p')).toEqual('22'); checkActivatedRoute(currC[0], ComponentA); checkActivatedRoute(currC[1], ComponentB, 'right'); }); it('should not retrieve routes when `shouldAttach` is always false', async () => { const config: Routes = [ {path: 'a', component: ComponentA}, {path: 'b', component: ComponentB, outlet: 'left'}, {path: 'c', component: ComponentC, outlet: 'left'}, ]; spyOn(reuseStrategy, 'retrieve'); const prevState = createRouterState( reuseStrategy, await createState(config, 'a(left:b)'), emptyState(), ); advanceState(prevState); createRouterState(reuseStrategy, await createState(config, 'a(left:c)'), prevState); expect(reuseStrategy.retrieve).not.toHaveBeenCalled(); }); it('should consistently represent future and current state', async () => { const config: Routes = [ {path: '', pathMatch: 'full', component: ComponentA}, {path: 'product/:id', component: ComponentB}, ]; spyOn(reuseStrategy, 'shouldReuseRoute').and.callThrough(); const previousState = createRouterState( reuseStrategy, await createState(config, ''), emptyState(), ); advanceState(previousState); (reuseStrategy.shouldReuseRoute as jasmine.Spy).calls.reset(); createRouterState(reuseStrategy, await createState(config, 'product/30'), previousState); // One call for the root and one call for each of the children expect(reuseStrategy.shouldReuseRoute).toHaveBeenCalledTimes(2); const reuseCalls = (reuseStrategy.shouldReuseRoute as jasmine.Spy).calls; const future1 = reuseCalls.argsFor(0)[0]; const current1 = reuseCalls.argsFor(0)[1]; const future2 = reuseCalls.argsFor(1)[0]; const current2 = reuseCalls.argsFor(1)[1]; // Routing from '' to 'product/30' expect(current1._routerState.url).toEqual(tree('').toString()); expect(future1._routerState.url).toEqual(tree('product/30').toString()); expect(current2._routerState.url).toEqual(tree('').toString()); expect(future2._routerState.url).toEqual(tree('product/30').toString()); }); }); function advanceState(state: RouterState): void { advanceNode((state as any)._root); } function advanceNode(node: TreeNode<ActivatedRoute>): void { advanceActivatedRoute(node.value); node.children.forEach(advanceNode); } async function createState(config: Routes, url: string): Promise<RouterStateSnapshot> { return recognize( TestBed.inject(EnvironmentInjector), TestBed.inject(RouterConfigLoader), RootComponent, config, tree(url), new DefaultUrlSerializer(), ) .pipe(map((result) => result.state)) .toPromise() as Promise<RouterStateSnapshot>; } function checkActivatedRoute( actual: ActivatedRoute, cmp: Function, outlet: string = PRIMARY_OUTLET, ): void { if (actual === null) { expect(actual).toBeDefined(); } else { expect(actual.component as any).toBe(cmp); expect(actual.outlet).toEqual(outlet); } } function tree(url: string): UrlTree { return new DefaultUrlSerializer().parse(url); } class RootComponent {} class ComponentA {} class ComponentB {} class ComponentC {}
{ "end_byte": 6832, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/create_router_state.spec.ts" }
angular/packages/router/test/router_state.spec.ts_0_8328
/** * @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.dev/license */ import {BehaviorSubject} from 'rxjs'; import { ActivatedRoute, ActivatedRouteSnapshot, advanceActivatedRoute, equalParamsAndUrlSegments, RouterState, RouterStateSnapshot, } from '../src/router_state'; import {Params, RouteTitleKey} from '../src/shared'; import {UrlSegment} from '../src/url_tree'; import {TreeNode} from '../src/utils/tree'; describe('RouterState & Snapshot', () => { describe('RouterStateSnapshot', () => { let state: RouterStateSnapshot; let a: ActivatedRouteSnapshot; let b: ActivatedRouteSnapshot; let c: ActivatedRouteSnapshot; beforeEach(() => { a = createActivatedRouteSnapshot('a'); b = createActivatedRouteSnapshot('b'); c = createActivatedRouteSnapshot('c'); const root = new TreeNode(a, [new TreeNode(b, []), new TreeNode(c, [])]); state = new (RouterStateSnapshot as any)('url', root); }); it('should return first child', () => { expect(state.root.firstChild).toBe(b); }); it('should return children', () => { const cc = state.root.children; expect(cc[0]).toBe(b); expect(cc[1]).toBe(c); }); it('should return root', () => { const b = state.root.firstChild!; expect(b.root).toBe(state.root); }); it('should return parent', () => { const b = state.root.firstChild!; expect(b.parent).toBe(state.root); }); it('should return path from root', () => { const b = state.root.firstChild!; const p = b.pathFromRoot; expect(p[0]).toBe(state.root); expect(p[1]).toBe(b); }); }); describe('RouterState', () => { let state: RouterState; let a: ActivatedRoute; let b: ActivatedRoute; let c: ActivatedRoute; beforeEach(() => { a = createActivatedRoute('a'); b = createActivatedRoute('b'); c = createActivatedRoute('c'); const root = new TreeNode(a, [new TreeNode(b, []), new TreeNode(c, [])]); state = new (RouterState as any)(root, null); }); it('should return first child', () => { expect(state.root.firstChild).toBe(b); }); it('should return children', () => { const cc = state.root.children; expect(cc[0]).toBe(b); expect(cc[1]).toBe(c); }); it('should return root', () => { const b = state.root.firstChild!; expect(b.root).toBe(state.root); }); it('should return parent', () => { const b = state.root.firstChild!; expect(b.parent).toBe(state.root); }); it('should return path from root', () => { const b = state.root.firstChild!; const p = b.pathFromRoot; expect(p[0]).toBe(state.root); expect(p[1]).toBe(b); }); }); describe('equalParamsAndUrlSegments', () => { function createSnapshot(params: Params, url: UrlSegment[]): ActivatedRouteSnapshot { const snapshot = new (ActivatedRouteSnapshot as any)( url, params, null, null, null, null, null, null, null, -1, null, ); snapshot._routerState = new (RouterStateSnapshot as any)('', new TreeNode(snapshot, [])); return snapshot; } function createSnapshotPairWithParent( params: [Params, Params], parentParams: [Params, Params], urls: [string, string], ): [ActivatedRouteSnapshot, ActivatedRouteSnapshot] { const snapshot1 = createSnapshot(params[0], []); const snapshot2 = createSnapshot(params[1], []); const snapshot1Parent = createSnapshot(parentParams[0], [new UrlSegment(urls[0], {})]); const snapshot2Parent = createSnapshot(parentParams[1], [new UrlSegment(urls[1], {})]); (snapshot1 as any)._routerState = new (RouterStateSnapshot as any)( '', new TreeNode(snapshot1Parent, [new TreeNode(snapshot1, [])]), ); (snapshot2 as any)._routerState = new (RouterStateSnapshot as any)( '', new TreeNode(snapshot2Parent, [new TreeNode(snapshot2, [])]), ); return [snapshot1, snapshot2]; } it('should return false when params are different', () => { expect( equalParamsAndUrlSegments(createSnapshot({a: '1'}, []), createSnapshot({a: '2'}, [])), ).toEqual(false); }); it('should return false when urls are different', () => { expect( equalParamsAndUrlSegments( createSnapshot({a: '1'}, [new UrlSegment('a', {})]), createSnapshot({a: '1'}, [new UrlSegment('b', {})]), ), ).toEqual(false); }); it('should return true othewise', () => { expect( equalParamsAndUrlSegments( createSnapshot({a: '1'}, [new UrlSegment('a', {})]), createSnapshot({a: '1'}, [new UrlSegment('a', {})]), ), ).toEqual(true); }); it('should return false when upstream params are different', () => { const [snapshot1, snapshot2] = createSnapshotPairWithParent( [{a: '1'}, {a: '1'}], [{b: '1'}, {c: '1'}], ['a', 'a'], ); expect(equalParamsAndUrlSegments(snapshot1, snapshot2)).toEqual(false); }); it('should return false when upstream urls are different', () => { const [snapshot1, snapshot2] = createSnapshotPairWithParent( [{a: '1'}, {a: '1'}], [{b: '1'}, {b: '1'}], ['a', 'b'], ); expect(equalParamsAndUrlSegments(snapshot1, snapshot2)).toEqual(false); }); it('should return true when upstream urls and params are equal', () => { const [snapshot1, snapshot2] = createSnapshotPairWithParent( [{a: '1'}, {a: '1'}], [{b: '1'}, {b: '1'}], ['a', 'a'], ); expect(equalParamsAndUrlSegments(snapshot1, snapshot2)).toEqual(true); }); }); describe('advanceActivatedRoute', () => { let route: ActivatedRoute; beforeEach(() => { route = createActivatedRoute('a'); }); function createSnapshot(params: Params, url: UrlSegment[]): ActivatedRouteSnapshot { const queryParams = {}; const fragment = ''; const data = {}; const snapshot = new (ActivatedRouteSnapshot as any)( url, params, queryParams, fragment, data, null, null, null, null, -1, null, ); const state = new (RouterStateSnapshot as any)('', new TreeNode(snapshot, [])); snapshot._routerState = state; return snapshot; } it('should call change observers', () => { const firstPlace = createSnapshot({a: '1'}, []); const secondPlace = createSnapshot({a: '2'}, []); route.snapshot = firstPlace; (route as any)._futureSnapshot = secondPlace; let hasSeenDataChange = false; route.data.forEach((data) => { hasSeenDataChange = true; }); advanceActivatedRoute(route); expect(hasSeenDataChange).toEqual(true); }); }); describe('ActivatedRoute', () => { it('should get resolved route title', () => { const data = {[RouteTitleKey]: 'resolved title'}; const route = createActivatedRoute('a'); const snapshot = new (ActivatedRouteSnapshot as any)( [], null, null, null, data, null, 'test', null, null, -1, null!, ); let resolvedTitle: string | undefined; route.data.next(data); route.title.forEach((title: string | undefined) => { resolvedTitle = title; }); expect(resolvedTitle).toEqual('resolved title'); expect(snapshot.title).toEqual('resolved title'); }); }); }); function createActivatedRouteSnapshot(cmp: string) { return new (ActivatedRouteSnapshot as any)( [], null, null, null, null, null, cmp, null, null, -1, null!, ); } function createActivatedRoute(cmp: string) { return new (ActivatedRoute as any)( new BehaviorSubject([new UrlSegment('', {})]), new BehaviorSubject({}), null, null, new BehaviorSubject({}), null, cmp, null, ); }
{ "end_byte": 8328, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/router_state.spec.ts" }
angular/packages/router/test/router_preloader.spec.ts_0_9098
/** * @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.dev/license */ import {provideLocationMocks} from '@angular/common/testing'; import { Compiler, Component, Injectable, InjectionToken, Injector, NgModule, NgModuleFactory, NgModuleRef, Type, EnvironmentInjector, } from '@angular/core'; import {fakeAsync, inject, TestBed, tick} from '@angular/core/testing'; import { PreloadAllModules, PreloadingStrategy, RouterPreloader, ROUTES, withPreloading, } from '@angular/router'; import {BehaviorSubject, Observable, of, throwError} from 'rxjs'; import {catchError, delay, filter, switchMap, take} from 'rxjs/operators'; import {Route, RouteConfigLoadEnd, RouteConfigLoadStart, Router, RouterModule} from '../index'; import {provideRouter} from '../src/provide_router'; import { getLoadedComponent, getLoadedInjector, getLoadedRoutes, getProvidersInjector, } from '../src/utils/config'; describe('RouterPreloader', () => { @Component({ template: '', standalone: false, }) class LazyLoadedCmp {} describe('should properly handle', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ provideLocationMocks(), provideRouter( [{path: 'lazy', loadChildren: jasmine.createSpy('expected'), canLoad: ['someGuard']}], withPreloading(PreloadAllModules), ), ], }); }); it('being destroyed before expected', () => { const preloader: RouterPreloader = TestBed.get(RouterPreloader); // Calling the RouterPreloader's ngOnDestroy method is done to simulate what would happen if // the containing NgModule is destroyed. expect(() => preloader.ngOnDestroy()).not.toThrow(); }); }); describe('configurations with canLoad guard', () => { @NgModule({ declarations: [LazyLoadedCmp], providers: [ { provide: ROUTES, multi: true, useValue: [{path: 'LoadedModule1', component: LazyLoadedCmp}], }, ], }) class LoadedModule {} beforeEach(() => { TestBed.configureTestingModule({ providers: [ provideLocationMocks(), provideRouter( [{path: 'lazy', loadChildren: () => LoadedModule, canLoad: ['someGuard']}], withPreloading(PreloadAllModules), ), ], }); }); it('should not load children', fakeAsync( inject([RouterPreloader, Router], (preloader: RouterPreloader, router: Router) => { preloader.preload().subscribe(() => {}); tick(); const c = router.config; expect((c[0] as any)._loadedRoutes).not.toBeDefined(); }), )); it('should not call the preloading method because children will not be loaded anyways', fakeAsync(() => { const preloader = TestBed.inject(RouterPreloader); const preloadingStrategy = TestBed.inject(PreloadingStrategy); spyOn(preloadingStrategy, 'preload').and.callThrough(); preloader.preload().subscribe(() => {}); tick(); expect(preloadingStrategy.preload).not.toHaveBeenCalled(); })); }); describe('should preload configurations', () => { let lazySpy: jasmine.Spy; beforeEach(() => { lazySpy = jasmine.createSpy('expected'); TestBed.configureTestingModule({ providers: [ provideLocationMocks(), provideRouter([{path: 'lazy', loadChildren: lazySpy}], withPreloading(PreloadAllModules)), ], }); }); it('should work', fakeAsync( inject( [RouterPreloader, Router, NgModuleRef], ( preloader: RouterPreloader, router: Router, testModule: {_r3Injector: EnvironmentInjector}, ) => { const events: Array<RouteConfigLoadStart | RouteConfigLoadEnd> = []; @NgModule({ declarations: [LazyLoadedCmp], imports: [RouterModule.forChild([{path: 'LoadedModule2', component: LazyLoadedCmp}])], }) class LoadedModule2 {} @NgModule({ imports: [ RouterModule.forChild([{path: 'LoadedModule1', loadChildren: () => LoadedModule2}]), ], }) class LoadedModule1 {} router.events.subscribe((e) => { if (e instanceof RouteConfigLoadEnd || e instanceof RouteConfigLoadStart) { events.push(e); } }); lazySpy.and.returnValue(LoadedModule1); preloader.preload().subscribe(() => {}); tick(); const c = router.config; const injector: any = getLoadedInjector(c[0]); const loadedRoutes: Route[] = getLoadedRoutes(c[0])!; expect(loadedRoutes[0].path).toEqual('LoadedModule1'); expect(injector.parent).toBe(testModule._r3Injector); const injector2: any = getLoadedInjector(loadedRoutes[0]); const loadedRoutes2: Route[] = getLoadedRoutes(loadedRoutes[0])!; expect(loadedRoutes2[0].path).toEqual('LoadedModule2'); expect(injector2.parent).toBe(injector); expect(events.map((e) => e.toString())).toEqual([ 'RouteConfigLoadStart(path: lazy)', 'RouteConfigLoadEnd(path: lazy)', 'RouteConfigLoadStart(path: LoadedModule1)', 'RouteConfigLoadEnd(path: LoadedModule1)', ]); }, ), )); }); it('should handle providers on a route', fakeAsync(() => { const TOKEN = new InjectionToken<string>('test token'); const CHILD_TOKEN = new InjectionToken<string>('test token for child'); @NgModule({ imports: [RouterModule.forChild([{path: 'child', redirectTo: ''}])], providers: [{provide: CHILD_TOKEN, useValue: 'child'}], }) class Child {} TestBed.configureTestingModule({ providers: [ provideLocationMocks(), provideRouter( [ { path: 'parent', providers: [{provide: TOKEN, useValue: 'parent'}], loadChildren: () => Child, }, ], withPreloading(PreloadAllModules), ), ], }); TestBed.inject(RouterPreloader) .preload() .subscribe(() => {}); tick(); const parentConfig = TestBed.inject(Router).config[0]; // preloading needs to create the injector const providersInjector = getProvidersInjector(parentConfig); expect(providersInjector).toBeDefined(); // Throws error because there is no provider for CHILD_TOKEN here expect(() => providersInjector?.get(CHILD_TOKEN)).toThrow(); const loadedInjector = getLoadedInjector(parentConfig)!; // // The loaded injector should be a child of the one created from providers expect(loadedInjector.get(TOKEN)).toEqual('parent'); expect(loadedInjector.get(CHILD_TOKEN)).toEqual('child'); })); describe('should support modules that have already been loaded', () => { let lazySpy: jasmine.Spy; beforeEach(() => { lazySpy = jasmine.createSpy('expected'); TestBed.configureTestingModule({ providers: [ provideLocationMocks(), provideRouter([{path: 'lazy', loadChildren: lazySpy}], withPreloading(PreloadAllModules)), ], }); }); it('should work', fakeAsync( inject( [RouterPreloader, Router, NgModuleRef, Compiler], ( preloader: RouterPreloader, router: Router, testModule: {_r3Injector: EnvironmentInjector}, compiler: Compiler, ) => { @NgModule() class LoadedModule2 {} const module2 = compiler.compileModuleSync(LoadedModule2).create(null); @NgModule({ imports: [ RouterModule.forChild([ <Route>{ path: 'LoadedModule2', loadChildren: jasmine.createSpy('no'), _loadedRoutes: [{path: 'LoadedModule3', loadChildren: () => LoadedModule3}], _loadedInjector: module2.injector, }, ]), ], }) class LoadedModule1 {} @NgModule({imports: [RouterModule.forChild([])]}) class LoadedModule3 {} lazySpy.and.returnValue(LoadedModule1); preloader.preload().subscribe(() => {}); tick(); const c = router.config; const injector = getLoadedInjector(c[0]) as unknown as {parent: EnvironmentInjector}; const loadedRoutes = getLoadedRoutes(c[0])!; expect(injector.parent).toBe(testModule._r3Injector); const loadedRoutes2: Route[] = getLoadedRoutes(loadedRoutes[0])!; const injector3 = getLoadedInjector(loadedRoutes2[0]) as unknown as { parent: EnvironmentInjector; }; expect(injector3.parent).toBe(module2.injector); }, ), )); });
{ "end_byte": 9098, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/router_preloader.spec.ts" }
angular/packages/router/test/router_preloader.spec.ts_9102_17231
describe('should support preloading strategies', () => { let delayLoadUnPaused: BehaviorSubject<string[]>; let delayLoadObserver$: Observable<string[]>; let events: Array<RouteConfigLoadStart | RouteConfigLoadEnd>; const subLoadChildrenSpy = jasmine.createSpy('submodule'); const lazyLoadChildrenSpy = jasmine.createSpy('lazymodule'); const mockPreloaderFactory = (): PreloadingStrategy => { class DelayedPreLoad implements PreloadingStrategy { preload(route: Route, fn: () => Observable<unknown>): Observable<unknown> { const routeName = route.loadChildren ? (route.loadChildren as jasmine.Spy).and.identity : 'noChildren'; return delayLoadObserver$.pipe( filter((unpauseList) => unpauseList.indexOf(routeName) !== -1), take(1), switchMap(() => { return fn().pipe(catchError(() => of(null))); }), ); } } return new DelayedPreLoad(); }; @NgModule({ declarations: [LazyLoadedCmp], }) class SharedModule {} @NgModule({ imports: [ SharedModule, RouterModule.forChild([ {path: 'LoadedModule1', component: LazyLoadedCmp}, {path: 'sub', loadChildren: subLoadChildrenSpy}, ]), ], }) class LoadedModule1 {} @NgModule({ imports: [ SharedModule, RouterModule.forChild([{path: 'LoadedModule2', component: LazyLoadedCmp}]), ], }) class LoadedModule2 {} beforeEach(() => { delayLoadUnPaused = new BehaviorSubject<string[]>([]); delayLoadObserver$ = delayLoadUnPaused.asObservable(); subLoadChildrenSpy.calls.reset(); lazyLoadChildrenSpy.calls.reset(); TestBed.configureTestingModule({ providers: [ provideLocationMocks(), provideRouter([{path: 'lazy', loadChildren: lazyLoadChildrenSpy}]), {provide: PreloadingStrategy, useFactory: mockPreloaderFactory}, ], }); events = []; }); it('without reloading loaded modules', fakeAsync(() => { const preloader = TestBed.inject(RouterPreloader); const router = TestBed.inject(Router); router.events.subscribe((e) => { if (e instanceof RouteConfigLoadEnd || e instanceof RouteConfigLoadStart) { events.push(e); } }); lazyLoadChildrenSpy.and.returnValue(of(LoadedModule1)); // App start activation of preloader preloader.preload().subscribe((x) => {}); tick(); expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(0); // Initial navigation cause route load router.navigateByUrl('/lazy/LoadedModule1'); tick(); expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(1); // Secondary load or navigation should use same loaded object ( // ie this is a noop as the module should already be loaded) delayLoadUnPaused.next(['lazymodule']); tick(); expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(1); expect(subLoadChildrenSpy).toHaveBeenCalledTimes(0); expect(events.map((e) => e.toString())).toEqual([ 'RouteConfigLoadStart(path: lazy)', 'RouteConfigLoadEnd(path: lazy)', ]); })); it('and cope with the loader throwing exceptions during module load but allow retry', fakeAsync(() => { const preloader = TestBed.inject(RouterPreloader); const router = TestBed.inject(Router); router.events.subscribe((e) => { if (e instanceof RouteConfigLoadEnd || e instanceof RouteConfigLoadStart) { events.push(e); } }); lazyLoadChildrenSpy.and.returnValue( throwError('Error: Fake module load error (expectedreload)'), ); preloader.preload().subscribe((x) => {}); tick(); expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(0); delayLoadUnPaused.next(['lazymodule']); tick(); expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(1); lazyLoadChildrenSpy.and.returnValue(of(LoadedModule1)); router.navigateByUrl('/lazy/LoadedModule1').catch(() => { fail('navigation should not throw'); }); tick(); expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(2); expect(subLoadChildrenSpy).toHaveBeenCalledTimes(0); expect(events.map((e) => e.toString())).toEqual([ 'RouteConfigLoadStart(path: lazy)', 'RouteConfigLoadStart(path: lazy)', 'RouteConfigLoadEnd(path: lazy)', ]); })); it('and cope with the loader throwing exceptions but allow retry', fakeAsync(() => { const preloader = TestBed.inject(RouterPreloader); const router = TestBed.inject(Router); router.events.subscribe((e) => { if (e instanceof RouteConfigLoadEnd || e instanceof RouteConfigLoadStart) { events.push(e); } }); lazyLoadChildrenSpy.and.returnValue( throwError('Error: Fake module load error (expectedreload)'), ); preloader.preload().subscribe((x) => {}); tick(); expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(0); router.navigateByUrl('/lazy/LoadedModule1').catch((reason) => { expect(reason).toEqual('Error: Fake module load error (expectedreload)'); }); tick(); expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(1); lazyLoadChildrenSpy.and.returnValue(of(LoadedModule1)); router.navigateByUrl('/lazy/LoadedModule1').catch(() => { fail('navigation should not throw'); }); tick(); expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(2); expect(subLoadChildrenSpy).toHaveBeenCalledTimes(0); expect(events.map((e) => e.toString())).toEqual([ 'RouteConfigLoadStart(path: lazy)', 'RouteConfigLoadStart(path: lazy)', 'RouteConfigLoadEnd(path: lazy)', ]); })); it('without autoloading loading submodules', fakeAsync(() => { const preloader = TestBed.inject(RouterPreloader); const router = TestBed.inject(Router); router.events.subscribe((e) => { if (e instanceof RouteConfigLoadEnd || e instanceof RouteConfigLoadStart) { events.push(e); } }); lazyLoadChildrenSpy.and.returnValue(of(LoadedModule1)); subLoadChildrenSpy.and.returnValue(of(LoadedModule2)); preloader.preload().subscribe((x) => {}); tick(); router.navigateByUrl('/lazy/LoadedModule1'); tick(); expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(1); expect(subLoadChildrenSpy).toHaveBeenCalledTimes(0); expect(events.map((e) => e.toString())).toEqual([ 'RouteConfigLoadStart(path: lazy)', 'RouteConfigLoadEnd(path: lazy)', ]); // Release submodule to check it does in fact load delayLoadUnPaused.next(['lazymodule', 'submodule']); tick(); expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(1); expect(subLoadChildrenSpy).toHaveBeenCalledTimes(1); expect(events.map((e) => e.toString())).toEqual([ 'RouteConfigLoadStart(path: lazy)', 'RouteConfigLoadEnd(path: lazy)', 'RouteConfigLoadStart(path: sub)', 'RouteConfigLoadEnd(path: sub)', ]); })); it('and close the preload obsservable ', fakeAsync(() => { const preloader = TestBed.inject(RouterPreloader); const router = TestBed.inject(Router); router.events.subscribe((e) => { if (e instanceof RouteConfigLoadEnd || e instanceof RouteConfigLoadStart) { events.push(e); } }); lazyLoadChildrenSpy.and.returnValue(of(LoadedModule1)); subLoadChildrenSpy.and.returnValue(of(LoadedModule2)); const preloadSubscription = preloader.preload().subscribe((x) => {}); router.navigateByUrl('/lazy/LoadedModule1'); tick(); delayLoadUnPaused.next(['lazymodule', 'submodule']); tick(); expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(1); expect(subLoadChildrenSpy).toHaveBeenCalledTimes(1); expect(preloadSubscription.closed).toBeTruthy(); }));
{ "end_byte": 17231, "start_byte": 9102, "url": "https://github.com/angular/angular/blob/main/packages/router/test/router_preloader.spec.ts" }
angular/packages/router/test/router_preloader.spec.ts_17237_23535
it('with overlapping loads from navigation and the preloader', fakeAsync(() => { const preloader = TestBed.inject(RouterPreloader); const router = TestBed.inject(Router); router.events.subscribe((e) => { if (e instanceof RouteConfigLoadEnd || e instanceof RouteConfigLoadStart) { events.push(e); } }); lazyLoadChildrenSpy.and.returnValue(of(LoadedModule1)); subLoadChildrenSpy.and.returnValue(of(LoadedModule2).pipe(delay(5))); preloader.preload().subscribe((x) => {}); tick(); // Load the out modules at start of test and ensure it and only // it is loaded delayLoadUnPaused.next(['lazymodule']); tick(); expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(1); expect(events.map((e) => e.toString())).toEqual([ 'RouteConfigLoadStart(path: lazy)', 'RouteConfigLoadEnd(path: lazy)', ]); // Cause the load from router to start (has 5 tick delay) router.navigateByUrl('/lazy/sub/LoadedModule2'); tick(); // T1 // Cause the load from preloader to start delayLoadUnPaused.next(['lazymodule', 'submodule']); tick(); // T2 expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(1); expect(subLoadChildrenSpy).toHaveBeenCalledTimes(1); tick(5); // T2 to T7 enough time for mutiple loads to finish expect(subLoadChildrenSpy).toHaveBeenCalledTimes(1); expect(events.map((e) => e.toString())).toEqual([ 'RouteConfigLoadStart(path: lazy)', 'RouteConfigLoadEnd(path: lazy)', 'RouteConfigLoadStart(path: sub)', 'RouteConfigLoadEnd(path: sub)', ]); })); it('cope with factory fail from broken modules', fakeAsync(() => { const preloader = TestBed.inject(RouterPreloader); const router = TestBed.inject(Router); router.events.subscribe((e) => { if (e instanceof RouteConfigLoadEnd || e instanceof RouteConfigLoadStart) { events.push(e); } }); class BrokenModuleFactory extends NgModuleFactory<unknown> { override moduleType: Type<unknown> = LoadedModule1; constructor() { super(); } override create(_parentInjector: Injector | null): NgModuleRef<unknown> { throw 'Error: Broken module'; } } lazyLoadChildrenSpy.and.returnValue(of(new BrokenModuleFactory())); preloader.preload().subscribe((x) => {}); tick(); expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(0); router.navigateByUrl('/lazy/LoadedModule1').catch((reason) => { expect(reason).toEqual('Error: Broken module'); }); tick(); expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(1); lazyLoadChildrenSpy.and.returnValue(of(LoadedModule1)); router.navigateByUrl('/lazy/LoadedModule1').catch(() => { fail('navigation should not throw'); }); tick(); expect(lazyLoadChildrenSpy).toHaveBeenCalledTimes(2); expect(subLoadChildrenSpy).toHaveBeenCalledTimes(0); expect(events.map((e) => e.toString())).toEqual([ 'RouteConfigLoadStart(path: lazy)', 'RouteConfigLoadEnd(path: lazy)', 'RouteConfigLoadStart(path: lazy)', 'RouteConfigLoadEnd(path: lazy)', ]); })); }); describe('should ignore errors', () => { @NgModule({ declarations: [LazyLoadedCmp], imports: [RouterModule.forChild([{path: 'LoadedModule1', component: LazyLoadedCmp}])], }) class LoadedModule {} beforeEach(() => { TestBed.configureTestingModule({ providers: [ { provide: ROUTES, multi: true, useValue: [ {path: 'lazy1', loadChildren: jasmine.createSpy('expected1')}, {path: 'lazy2', loadChildren: () => LoadedModule}, ], }, {provide: PreloadingStrategy, useExisting: PreloadAllModules}, ], }); }); it('should work', fakeAsync( inject([RouterPreloader, Router], (preloader: RouterPreloader, router: Router) => { preloader.preload().subscribe(() => {}); tick(); const c = router.config; expect(getLoadedRoutes(c[0])).not.toBeDefined(); expect(getLoadedRoutes(c[1])).toBeDefined(); }), )); }); describe('should copy loaded configs', () => { const configs = [{path: 'LoadedModule1', component: LazyLoadedCmp}]; @NgModule({ declarations: [LazyLoadedCmp], providers: [{provide: ROUTES, multi: true, useValue: configs}], }) class LoadedModule {} beforeEach(() => { TestBed.configureTestingModule({ providers: [ provideLocationMocks(), provideRouter( [{path: 'lazy1', loadChildren: () => LoadedModule}], withPreloading(PreloadAllModules), ), ], }); }); it('should work', fakeAsync( inject([RouterPreloader, Router], (preloader: RouterPreloader, router: Router) => { preloader.preload().subscribe(() => {}); tick(); const c = router.config; expect(getLoadedRoutes(c[0])).toBeDefined(); expect(getLoadedRoutes(c[0])).not.toBe(configs); expect(getLoadedRoutes(c[0])![0]).not.toBe(configs[0]); expect(getLoadedRoutes(c[0])![0].component).toBe(configs[0].component); }), )); }); describe("should work with lazy loaded modules that don't provide RouterModule.forChild()", () => { @NgModule({ declarations: [LazyLoadedCmp], providers: [ { provide: ROUTES, multi: true, useValue: [{path: 'LoadedModule1', component: LazyLoadedCmp}], }, ], }) class LoadedModule {} @NgModule({}) class EmptyModule {} beforeEach(() => { TestBed.configureTestingModule({ providers: [ provideLocationMocks(), provideRouter( [{path: 'lazyEmptyModule', loadChildren: () => EmptyModule}], withPreloading(PreloadAllModules), ), ], }); }); it('should work', fakeAsync( inject([RouterPreloader], (preloader: RouterPreloader) => { preloader.preload().subscribe(); }), )); });
{ "end_byte": 23535, "start_byte": 17237, "url": "https://github.com/angular/angular/blob/main/packages/router/test/router_preloader.spec.ts" }
angular/packages/router/test/router_preloader.spec.ts_23539_29573
describe('should preload loadComponent configs', () => { let lazyComponentSpy: jasmine.Spy; beforeEach(() => { lazyComponentSpy = jasmine.createSpy('expected'); TestBed.configureTestingModule({ providers: [ provideLocationMocks(), provideRouter( [{path: 'lazy', loadComponent: lazyComponentSpy}], withPreloading(PreloadAllModules), ), ], }); }); it('base case', fakeAsync(() => { @Component({template: '', standalone: true}) class LoadedComponent {} const preloader = TestBed.inject(RouterPreloader); lazyComponentSpy.and.returnValue(LoadedComponent); preloader.preload().subscribe(() => {}); tick(); const component = getLoadedComponent(TestBed.inject(Router).config[0]); expect(component).toEqual(LoadedComponent); })); it('throws error when loadComponent is not standalone', fakeAsync(() => { @Component({template: '', standalone: false}) class LoadedComponent {} @Injectable({providedIn: 'root'}) class ErrorTrackingPreloadAllModules implements PreloadingStrategy { errors: Error[] = []; preload(route: Route, fn: () => Observable<unknown>): Observable<unknown> { return fn().pipe( catchError((e: Error) => { this.errors.push(e); return of(null); }), ); } } TestBed.overrideProvider(PreloadingStrategy, { useFactory: () => new ErrorTrackingPreloadAllModules(), }); const preloader = TestBed.inject(RouterPreloader); lazyComponentSpy.and.returnValue(LoadedComponent); preloader.preload().subscribe(() => {}); tick(); const strategy = TestBed.inject(PreloadingStrategy) as ErrorTrackingPreloadAllModules; expect(strategy.errors[0]?.message).toMatch(/.*lazy.*must be standalone/); })); it('should recover from errors', fakeAsync(() => { @Component({template: '', standalone: true}) class LoadedComponent {} const preloader = TestBed.inject(RouterPreloader); lazyComponentSpy.and.returnValue(throwError('error loading chunk')); preloader.preload().subscribe(() => {}); tick(); const router = TestBed.inject(Router); const c = router.config; expect(lazyComponentSpy.calls.count()).toBe(1); expect(getLoadedComponent(c[0])).not.toBeDefined(); lazyComponentSpy.and.returnValue(LoadedComponent); router.navigateByUrl('/lazy'); tick(); expect(lazyComponentSpy.calls.count()).toBe(2); expect(getLoadedComponent(c[0])).toBeDefined(); })); it('works when there is both loadComponent and loadChildren', fakeAsync(() => { @Component({template: '', standalone: true}) class LoadedComponent {} @NgModule({ providers: [ provideLocationMocks(), provideRouter([{path: 'child', component: LoadedComponent}]), ], }) class LoadedModule {} const router = TestBed.inject(Router); router.config[0].loadChildren = () => LoadedModule; const preloader = TestBed.inject(RouterPreloader); lazyComponentSpy.and.returnValue(LoadedComponent); preloader.preload().subscribe(() => {}); tick(); const component = getLoadedComponent(router.config[0]); expect(component).toEqual(LoadedComponent); const childRoutes = getLoadedRoutes(router.config[0]); expect(childRoutes).toBeDefined(); expect(childRoutes![0].path).toEqual('child'); })); it('loadComponent does not block loadChildren', fakeAsync(() => { @Component({template: '', standalone: true}) class LoadedComponent {} lazyComponentSpy.and.returnValue(of(LoadedComponent).pipe(delay(5))); @NgModule({ providers: [ provideLocationMocks(), provideRouter([ { path: 'child', loadChildren: () => of([{path: 'grandchild', children: []}]).pipe(delay(1)), }, ]), ], }) class LoadedModule {} const router = TestBed.inject(Router); const baseRoute = router.config[0]; baseRoute.loadChildren = () => of(LoadedModule).pipe(delay(1)); const preloader = TestBed.inject(RouterPreloader); preloader.preload().subscribe(() => {}); tick(1); // Loading should have started but not completed yet expect(getLoadedComponent(baseRoute)).not.toBeDefined(); const childRoutes = getLoadedRoutes(baseRoute); expect(childRoutes).toBeDefined(); // Loading should have started but not completed yet expect(getLoadedRoutes(childRoutes![0])).not.toBeDefined(); tick(1); // Loading should have started but not completed yet expect(getLoadedComponent(baseRoute)).not.toBeDefined(); expect(getLoadedRoutes(childRoutes![0])).toBeDefined(); tick(3); expect(getLoadedComponent(baseRoute)).toBeDefined(); })); it('loads nested components', () => { @Component({template: '', standalone: true}) class LoadedComponent {} lazyComponentSpy.and.returnValue(LoadedComponent); TestBed.inject(Router).resetConfig([ { path: 'a', loadComponent: lazyComponentSpy, children: [ { path: 'b', loadComponent: lazyComponentSpy, children: [ { path: 'c', loadComponent: lazyComponentSpy, children: [ { path: 'd', loadComponent: lazyComponentSpy, }, ], }, ], }, ], }, ]); const preloader = TestBed.inject(RouterPreloader); preloader.preload().subscribe(() => {}); expect(lazyComponentSpy).toHaveBeenCalledTimes(4); }); }); });
{ "end_byte": 29573, "start_byte": 23539, "url": "https://github.com/angular/angular/blob/main/packages/router/test/router_preloader.spec.ts" }
angular/packages/router/test/default_export_routes.ts_0_487
/** * @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.dev/license */ import {Component} from '@angular/core'; import {Routes} from '@angular/router'; @Component({ standalone: true, template: 'default exported', selector: 'test-route', }) export class TestRoute {} export default [{path: '', pathMatch: 'full', component: TestRoute}] as Routes;
{ "end_byte": 487, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/default_export_routes.ts" }
angular/packages/router/test/router_scroller.spec.ts_0_714
/** * @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.dev/license */ import {TestBed, fakeAsync, tick} from '@angular/core/testing'; import {DefaultUrlSerializer, Event, NavigationEnd, NavigationStart} from '@angular/router'; import {Subject} from 'rxjs'; import {filter, switchMap, take} from 'rxjs/operators'; import {Scroll} from '../src/events'; import {RouterScroller} from '../src/router_scroller'; import {ApplicationRef, ɵNoopNgZone as NoopNgZone} from '@angular/core'; // TODO: add tests that exercise the `withInMemoryScrolling` feature of the provideRouter function
{ "end_byte": 714, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/router_scroller.spec.ts" }
angular/packages/router/test/router_scroller.spec.ts_715_8763
escribe('RouterScroller', () => { it('defaults to disabled', () => { const events = new Subject<Event>(); const viewportScroller = jasmine.createSpyObj('viewportScroller', [ 'getScrollPosition', 'scrollToPosition', 'scrollToAnchor', 'setHistoryScrollRestoration', ]); setScroll(viewportScroller, 0, 0); const scroller = TestBed.runInInjectionContext( () => new RouterScroller( new DefaultUrlSerializer(), {events} as any, viewportScroller, new NoopNgZone(), ), ); expect((scroller as any).options.scrollPositionRestoration).toBe('disabled'); expect((scroller as any).options.anchorScrolling).toBe('disabled'); }); function nextScrollEvent(events: Subject<Event>): Promise<Scroll> { return events .pipe( filter((e): e is Scroll => e instanceof Scroll), take(1), ) .toPromise() as Promise<Scroll>; } describe('scroll to top', () => { it('should scroll to the top', async () => { const {events, viewportScroller} = createRouterScroller({ scrollPositionRestoration: 'top', anchorScrolling: 'disabled', }); events.next(new NavigationStart(1, '/a')); events.next(new NavigationEnd(1, '/a', '/a')); await nextScrollEvent(events); expect(viewportScroller.scrollToPosition).toHaveBeenCalledWith([0, 0]); events.next(new NavigationStart(2, '/a')); events.next(new NavigationEnd(2, '/b', '/b')); await nextScrollEvent(events); expect(viewportScroller.scrollToPosition).toHaveBeenCalledWith([0, 0]); events.next(new NavigationStart(3, '/a', 'popstate')); events.next(new NavigationEnd(3, '/a', '/a')); await nextScrollEvent(events); expect(viewportScroller.scrollToPosition).toHaveBeenCalledWith([0, 0]); }); }); describe('scroll to the stored position', () => { it('should scroll to the stored position on popstate', async () => { const {events, viewportScroller} = createRouterScroller({ scrollPositionRestoration: 'enabled', anchorScrolling: 'disabled', }); events.next(new NavigationStart(1, '/a')); events.next(new NavigationEnd(1, '/a', '/a')); await nextScrollEvent(events); setScroll(viewportScroller, 10, 100); expect(viewportScroller.scrollToPosition).toHaveBeenCalledWith([0, 0]); events.next(new NavigationStart(2, '/b')); events.next(new NavigationEnd(2, '/b', '/b')); await nextScrollEvent(events); setScroll(viewportScroller, 20, 200); expect(viewportScroller.scrollToPosition).toHaveBeenCalledWith([0, 0]); events.next(new NavigationStart(3, '/a', 'popstate', {navigationId: 1})); events.next(new NavigationEnd(3, '/a', '/a')); await nextScrollEvent(events); expect(viewportScroller.scrollToPosition).toHaveBeenCalledWith([10, 100]); }); }); describe('anchor scrolling', () => { it('should work (scrollPositionRestoration is disabled)', async () => { const {events, viewportScroller} = createRouterScroller({ scrollPositionRestoration: 'disabled', anchorScrolling: 'enabled', }); events.next(new NavigationStart(1, '/a#anchor')); events.next(new NavigationEnd(1, '/a#anchor', '/a#anchor')); await nextScrollEvent(events); expect(viewportScroller.scrollToAnchor).toHaveBeenCalledWith('anchor'); events.next(new NavigationStart(2, '/a#anchor2')); events.next(new NavigationEnd(2, '/a#anchor2', '/a#anchor2')); await nextScrollEvent(events); expect(viewportScroller.scrollToAnchor).toHaveBeenCalledWith('anchor2'); viewportScroller.scrollToAnchor.calls.reset(); // we never scroll to anchor when navigating back. events.next(new NavigationStart(3, '/a#anchor', 'popstate')); events.next(new NavigationEnd(3, '/a#anchor', '/a#anchor')); await nextScrollEvent(events); expect(viewportScroller.scrollToAnchor).not.toHaveBeenCalled(); expect(viewportScroller.scrollToPosition).not.toHaveBeenCalled(); }); it('should work (scrollPositionRestoration is enabled)', async () => { const {events, viewportScroller} = createRouterScroller({ scrollPositionRestoration: 'enabled', anchorScrolling: 'enabled', }); events.next(new NavigationStart(1, '/a#anchor')); events.next(new NavigationEnd(1, '/a#anchor', '/a#anchor')); await nextScrollEvent(events); expect(viewportScroller.scrollToAnchor).toHaveBeenCalledWith('anchor'); events.next(new NavigationStart(2, '/a#anchor2')); events.next(new NavigationEnd(2, '/a#anchor2', '/a#anchor2')); await nextScrollEvent(events); expect(viewportScroller.scrollToAnchor).toHaveBeenCalledWith('anchor2'); viewportScroller.scrollToAnchor.calls.reset(); // we never scroll to anchor when navigating back events.next(new NavigationStart(3, '/a#anchor', 'popstate', {navigationId: 1})); events.next(new NavigationEnd(3, '/a#anchor', '/a#anchor')); await nextScrollEvent(events); expect(viewportScroller.scrollToAnchor).not.toHaveBeenCalled(); expect(viewportScroller.scrollToPosition).toHaveBeenCalledWith([0, 0]); }); }); describe('extending a scroll service', () => { it('work', fakeAsync(() => { const {events, viewportScroller} = createRouterScroller({ scrollPositionRestoration: 'disabled', anchorScrolling: 'disabled', }); events .pipe( filter((e): e is Scroll => e instanceof Scroll && !!e.position), switchMap((p) => { // can be any delay (e.g., we can wait for NgRx store to emit an event) const r = new Subject<Scroll>(); setTimeout(() => { r.next(p); r.complete(); }, 1000); return r; }), ) .subscribe((e: Scroll) => { viewportScroller.scrollToPosition(e.position); }); events.next(new NavigationStart(1, '/a')); events.next(new NavigationEnd(1, '/a', '/a')); tick(); setScroll(viewportScroller, 10, 100); events.next(new NavigationStart(2, '/b')); events.next(new NavigationEnd(2, '/b', '/b')); tick(); setScroll(viewportScroller, 20, 200); events.next(new NavigationStart(3, '/c')); events.next(new NavigationEnd(3, '/c', '/c')); tick(); setScroll(viewportScroller, 30, 300); events.next(new NavigationStart(4, '/a', 'popstate', {navigationId: 1})); events.next(new NavigationEnd(4, '/a', '/a')); tick(500); expect(viewportScroller.scrollToPosition).not.toHaveBeenCalled(); events.next(new NavigationStart(5, '/a', 'popstate', {navigationId: 1})); events.next(new NavigationEnd(5, '/a', '/a')); tick(5000); expect(viewportScroller.scrollToPosition).toHaveBeenCalledWith([10, 100]); })); }); function createRouterScroller({ scrollPositionRestoration, anchorScrolling, }: { scrollPositionRestoration: 'disabled' | 'enabled' | 'top'; anchorScrolling: 'disabled' | 'enabled'; }) { const events = new Subject<Event>(); const transitions: any = {events}; const viewportScroller = jasmine.createSpyObj('viewportScroller', [ 'getScrollPosition', 'scrollToPosition', 'scrollToAnchor', 'setHistoryScrollRestoration', ]); setScroll(viewportScroller, 0, 0); const scroller = TestBed.runInInjectionContext( () => new RouterScroller( new DefaultUrlSerializer(), transitions, viewportScroller, new NoopNgZone(), {scrollPositionRestoration, anchorScrolling}, ), ); scroller.init(); return {events, viewportScroller}; } function setScroll(viewportScroller: any, x: number, y: number) { viewportScroller.getScrollPosition.and.returnValue([x, y]); } });
{ "end_byte": 8763, "start_byte": 715, "url": "https://github.com/angular/angular/blob/main/packages/router/test/router_scroller.spec.ts" }
angular/packages/router/test/regression_integration.spec.ts_0_1044
/** * @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.dev/license */ import {CommonModule, HashLocationStrategy, Location, LocationStrategy} from '@angular/common'; import {provideLocationMocks, SpyLocation} from '@angular/common/testing'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Injectable, NgModule, TemplateRef, Type, ViewChild, ViewContainerRef, } from '@angular/core'; import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'; import { ChildrenOutletContexts, DefaultUrlSerializer, NavigationCancel, NavigationError, Router, RouterModule, RouterOutlet, UrlSerializer, UrlTree, } from '@angular/router'; import {of} from 'rxjs'; import {delay, filter, mapTo, take} from 'rxjs/operators'; import {provideRouter, withRouterConfig} from '../src/provide_router'; import {afterNextNavigation} from '../src/utils/navigations';
{ "end_byte": 1044, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/regression_integration.spec.ts" }
angular/packages/router/test/regression_integration.spec.ts_1046_9876
describe('Integration', () => { describe('routerLinkActive', () => { it('should update when the associated routerLinks change - #18469', fakeAsync(() => { @Component({ template: ` <a id="first-link" [routerLink]="[firstLink]" routerLinkActive="active">{{firstLink}}</a> <div id="second-link" routerLinkActive="active"> <a [routerLink]="[secondLink]">{{secondLink}}</a> </div> `, standalone: false, }) class LinkComponent { firstLink = 'link-a'; secondLink = 'link-b'; changeLinks(): void { const temp = this.secondLink; this.secondLink = this.firstLink; this.firstLink = temp; } } @Component({ template: 'simple', standalone: false, }) class SimpleCmp {} TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ {path: 'link-a', component: SimpleCmp}, {path: 'link-b', component: SimpleCmp}, ]), ], declarations: [LinkComponent, SimpleCmp], }); const router: Router = TestBed.inject(Router); const fixture = createRoot(router, LinkComponent); const firstLink = fixture.debugElement.query((p) => p.nativeElement.id === 'first-link'); const secondLink = fixture.debugElement.query((p) => p.nativeElement.id === 'second-link'); router.navigateByUrl('/link-a'); advance(fixture); expect(firstLink.nativeElement.classList).toContain('active'); expect(secondLink.nativeElement.classList).not.toContain('active'); fixture.componentInstance.changeLinks(); fixture.detectChanges(); advance(fixture); expect(firstLink.nativeElement.classList).not.toContain('active'); expect(secondLink.nativeElement.classList).toContain('active'); })); it('should not cause infinite loops in the change detection - #15825', fakeAsync(() => { @Component({ selector: 'simple', template: 'simple', standalone: false, }) class SimpleCmp {} @Component({ selector: 'some-root', template: ` <div *ngIf="show"> <ng-container *ngTemplateOutlet="tpl"></ng-container> </div> <router-outlet></router-outlet> <ng-template #tpl> <a routerLink="/simple" routerLinkActive="active"></a> </ng-template>`, standalone: false, }) class MyCmp { show: boolean = false; } @NgModule({ imports: [CommonModule, RouterModule.forRoot([])], declarations: [MyCmp, SimpleCmp], }) class MyModule {} TestBed.configureTestingModule({imports: [MyModule]}); const router: Router = TestBed.inject(Router); const fixture = createRoot(router, MyCmp); router.resetConfig([{path: 'simple', component: SimpleCmp}]); router.navigateByUrl('/simple'); advance(fixture); const instance = fixture.componentInstance; instance.show = true; expect(() => advance(fixture)).not.toThrow(); })); it('should set isActive right after looking at its children -- #18983', fakeAsync(() => { @Component({ template: ` <div #rla="routerLinkActive" routerLinkActive> isActive: {{rla.isActive}} <ng-template let-data> <a [routerLink]="data">link</a> </ng-template> <ng-container #container></ng-container> </div> `, standalone: false, }) class ComponentWithRouterLink { @ViewChild(TemplateRef, {static: true}) templateRef?: TemplateRef<unknown>; @ViewChild('container', {read: ViewContainerRef, static: true}) container?: ViewContainerRef; addLink() { if (this.templateRef) { this.container?.createEmbeddedView(this.templateRef, {$implicit: '/simple'}); } } removeLink() { this.container?.clear(); } } @Component({ template: 'simple', standalone: false, }) class SimpleCmp {} TestBed.configureTestingModule({ imports: [RouterModule.forRoot([{path: 'simple', component: SimpleCmp}])], declarations: [ComponentWithRouterLink, SimpleCmp], }); const router: Router = TestBed.inject(Router); const fixture = createRoot(router, ComponentWithRouterLink); router.navigateByUrl('/simple'); advance(fixture); fixture.componentInstance.addLink(); fixture.detectChanges(); fixture.componentInstance.removeLink(); advance(fixture); advance(fixture); expect(fixture.nativeElement.innerHTML).toContain('isActive: false'); })); it('should set isActive with OnPush change detection - #19934', fakeAsync(() => { @Component({ template: ` <div routerLink="/simple" #rla="routerLinkActive" routerLinkActive> isActive: {{rla.isActive}} </div> `, changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class OnPushComponent {} @Component({ template: 'simple', standalone: false, }) class SimpleCmp {} TestBed.configureTestingModule({ imports: [RouterModule.forRoot([{path: 'simple', component: SimpleCmp}])], declarations: [OnPushComponent, SimpleCmp], }); const router: Router = TestBed.get(Router); const fixture = createRoot(router, OnPushComponent); router.navigateByUrl('/simple'); advance(fixture); expect(fixture.nativeElement.innerHTML).toContain('isActive: true'); })); }); it('should not reactivate a deactivated outlet when destroyed and recreated - #41379', fakeAsync(() => { @Component({ template: 'simple', standalone: false, }) class SimpleComponent {} @Component({ template: ` <router-outlet *ngIf="outletVisible" name="aux"></router-outlet> `, standalone: false, }) class AppComponent { outletVisible = true; } TestBed.configureTestingModule({ imports: [RouterModule.forRoot([{path: ':id', component: SimpleComponent, outlet: 'aux'}])], declarations: [SimpleComponent, AppComponent], }); const router = TestBed.inject(Router); const fixture = createRoot(router, AppComponent); const componentCdr = fixture.componentRef.injector.get<ChangeDetectorRef>(ChangeDetectorRef); router.navigate([{outlets: {aux: ['1234']}}]); advance(fixture); expect(fixture.nativeElement.innerHTML).toContain('simple'); router.navigate([{outlets: {aux: null}}]); advance(fixture); expect(fixture.nativeElement.innerHTML).not.toContain('simple'); fixture.componentInstance.outletVisible = false; componentCdr.detectChanges(); expect(fixture.nativeElement.innerHTML).not.toContain('simple'); expect(fixture.nativeElement.innerHTML).not.toContain('router-outlet'); fixture.componentInstance.outletVisible = true; componentCdr.detectChanges(); expect(fixture.nativeElement.innerHTML).toContain('router-outlet'); expect(fixture.nativeElement.innerHTML).not.toContain('simple'); })); describe('useHash', () => { it('should restore hash to match current route - #28561', fakeAsync(() => { @Component({ selector: 'root-cmp', template: `<router-outlet></router-outlet>`, standalone: false, }) class RootCmp {} @Component({ template: 'simple', standalone: false, }) class SimpleCmp {} @Component({ template: 'one', standalone: false, }) class OneCmp {} TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ {path: '', component: SimpleCmp}, {path: 'one', component: OneCmp, canActivate: ['returnRootUrlTree']}, ]), ], declarations: [SimpleCmp, RootCmp, OneCmp], providers: [ provideLocationMocks(), { provide: 'returnRootUrlTree', useFactory: (router: Router) => () => { return router.parseUrl('/'); }, deps: [Router], }, ], }); const router = TestBed.inject(Router); const location = TestBed.inject(Location) as SpyLocation; router.navigateByUrl('/'); // Will setup location change listeners const fixture = createRoot(router, RootCmp); location.simulateHashChange('/one'); advance(fixture); expect(location.path()).toEqual('/'); expect(fixture.nativeElement.innerHTML).toContain('one'); })); });
{ "end_byte": 9876, "start_byte": 1046, "url": "https://github.com/angular/angular/blob/main/packages/router/test/regression_integration.spec.ts" }
angular/packages/router/test/regression_integration.spec.ts_9880_16271
describe('duplicate navigation handling (#43447, #43446)', () => { let location: Location; let router: Router; let fixture: ComponentFixture<{}>; beforeEach(fakeAsync(() => { @Injectable() class DelayedResolve { resolve() { return of('').pipe(delay(1000), mapTo(true)); } } @Component({ selector: 'root-cmp', template: `<router-outlet></router-outlet>`, standalone: false, }) class RootCmp {} @Component({ template: 'simple', standalone: false, }) class SimpleCmp {} @Component({ template: 'one', standalone: false, }) class OneCmp {} TestBed.configureTestingModule({ declarations: [SimpleCmp, RootCmp, OneCmp], imports: [RouterOutlet], providers: [ DelayedResolve, provideLocationMocks(), provideRouter([ {path: '', component: SimpleCmp}, {path: 'one', component: OneCmp, resolve: {x: DelayedResolve}}, ]), {provide: LocationStrategy, useClass: HashLocationStrategy}, ], }); router = TestBed.inject(Router); location = TestBed.inject(Location); router.navigateByUrl('/'); // Will setup location change listeners fixture = createRoot(router, RootCmp); })); it('duplicate navigation to same url', fakeAsync(() => { location.go('/one'); tick(100); location.go('/one'); tick(1000); advance(fixture); expect(location.path()).toEqual('/one'); expect(fixture.nativeElement.innerHTML).toContain('one'); })); it('works with a duplicate popstate/hashchange navigation (as seen in firefox)', fakeAsync(() => { (location as any)._subject.next({'url': 'one', 'pop': true, 'type': 'popstate'}); tick(1); (location as any)._subject.next({'url': 'one', 'pop': true, 'type': 'hashchange'}); tick(1000); advance(fixture); expect(router.routerState.toString()).toContain(`url:'one'`); expect(fixture.nativeElement.innerHTML).toContain('one'); })); }); it('should not unregister outlet if a different one already exists #36711, 32453', async () => { @Component({ template: ` <router-outlet *ngIf="outlet1"></router-outlet> <router-outlet *ngIf="outlet2"></router-outlet> `, standalone: false, }) class TestCmp { outlet1 = true; outlet2 = false; } @Component({ template: '', standalone: false, }) class EmptyCmp {} TestBed.configureTestingModule({ imports: [CommonModule, RouterModule.forRoot([{path: '**', component: EmptyCmp}])], declarations: [TestCmp, EmptyCmp], }); const fixture = TestBed.createComponent(TestCmp); const contexts = TestBed.inject(ChildrenOutletContexts); await TestBed.inject(Router).navigateByUrl('/'); fixture.detectChanges(); expect(contexts.getContext('primary')).toBeDefined(); expect(contexts.getContext('primary')?.outlet).not.toBeNull(); // Show the second outlet. Applications shouldn't really have more than one outlet but there can // be timing issues between destroying and recreating a second one in some cases: // https://github.com/angular/angular/issues/36711, // https://github.com/angular/angular/issues/32453 fixture.componentInstance.outlet2 = true; fixture.detectChanges(); expect(contexts.getContext('primary')?.outlet).not.toBeNull(); fixture.componentInstance.outlet1 = false; fixture.detectChanges(); // Destroying the first one show not clear the outlet context because the second one takes over // as the registered outlet. expect(contexts.getContext('primary')?.outlet).not.toBeNull(); }); it('should respect custom serializer all the way to the final url on state', async () => { const QUERY_VALUE = {user: 'atscott'}; const SPECIAL_SERIALIZATION = 'special'; class CustomSerializer extends DefaultUrlSerializer { override serialize(tree: UrlTree): string { const mutableCopy = new UrlTree(tree.root, {...tree.queryParams}, tree.fragment); mutableCopy.queryParams['q'] &&= SPECIAL_SERIALIZATION; return new DefaultUrlSerializer().serialize(mutableCopy); } } TestBed.configureTestingModule({ providers: [provideRouter([]), {provide: UrlSerializer, useValue: new CustomSerializer()}], }); const router = TestBed.inject(Router); const tree = router.createUrlTree([]); tree.queryParams = {q: QUERY_VALUE}; await router.navigateByUrl(tree); expect(router.url).toEqual(`/?q=${SPECIAL_SERIALIZATION}`); }); it('navigation works when a redirecting NavigationCancel event causes another synchronous navigation', async () => { TestBed.configureTestingModule({ providers: [ provideRouter( [ {path: 'a', children: []}, {path: 'b', children: []}, {path: 'c', children: []}, ], withRouterConfig({resolveNavigationPromiseOnError: true}), ), ], }); let errors: NavigationError[] = []; let cancellations: NavigationCancel[] = []; const router = TestBed.inject(Router); router.events .pipe(filter((e): e is NavigationError => e instanceof NavigationError)) .subscribe((e) => errors.push(e)); router.events .pipe(filter((e): e is NavigationCancel => e instanceof NavigationCancel)) .subscribe((e) => cancellations.push(e)); router.events .pipe( filter((e) => e instanceof NavigationCancel), take(1), ) .subscribe(() => { router.navigateByUrl('/c'); }); router.navigateByUrl('/a'); router.navigateByUrl('/b'); await new Promise<void>((resolve) => afterNextNavigation(router, resolve)); expect(router.url).toEqual('/c'); expect(errors).toEqual([]); // navigations to a and b were both cancelled. expect(cancellations.length).toEqual(2); }); }); function advance<T>(fixture: ComponentFixture<T>): void { tick(); fixture.detectChanges(); } function createRoot<T>(router: Router, type: Type<T>): ComponentFixture<T> { const f = TestBed.createComponent(type); advance(f); router.initialNavigation(); advance(f); return f; }
{ "end_byte": 16271, "start_byte": 9880, "url": "https://github.com/angular/angular/blob/main/packages/router/test/regression_integration.spec.ts" }
angular/packages/router/test/shared.spec.ts_0_2023
/** * @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.dev/license */ import {convertToParamMap, ParamMap, Params} from '../src/shared'; describe('ParamsMap', () => { it('should returns whether a parameter is present', () => { const map = convertToParamMap({single: 's', multiple: ['m1', 'm2']}); expect(map.has('single')).toEqual(true); expect(map.has('multiple')).toEqual(true); expect(map.has('not here')).toEqual(false); }); it('should returns the name of the parameters', () => { const map = convertToParamMap({single: 's', multiple: ['m1', 'm2']}); expect(map.keys).toEqual(['single', 'multiple']); }); it('should support single valued parameters', () => { const map = convertToParamMap({single: 's', multiple: ['m1', 'm2']}); expect(map.get('single')).toEqual('s'); expect(map.get('multiple')).toEqual('m1'); }); it('should support multiple valued parameters', () => { const map = convertToParamMap({single: 's', multiple: ['m1', 'm2']}); expect(map.getAll('single')).toEqual(['s']); expect(map.getAll('multiple')).toEqual(['m1', 'm2']); }); it('should return `null` when a single valued element is absent', () => { const map = convertToParamMap({}); expect(map.get('name')).toEqual(null); }); it('should return `[]` when a multiple valued element is absent', () => { const map = convertToParamMap({}); expect(map.getAll('name')).toEqual([]); }); it('should not error when trying to call ParamMap.get function using an object created with Object.create() function', () => { const objectToMap: Params = Object.create(null); objectToMap['single'] = 's'; objectToMap['multiple'] = ['m1', 'm2']; const paramMaps: ParamMap = convertToParamMap(objectToMap); expect(() => paramMaps.get('single')).not.toThrow(); expect(paramMaps.get('single')).toEqual('s'); }); });
{ "end_byte": 2023, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/shared.spec.ts" }
angular/packages/router/test/url_serializer.spec.ts_0_403
/** * @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.dev/license */ import {PRIMARY_OUTLET} from '../src/shared'; import { DefaultUrlSerializer, encodeUriFragment, encodeUriQuery, encodeUriSegment, serializePath, UrlSegmentGroup, } from '../src/url_tree';
{ "end_byte": 403, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/url_serializer.spec.ts" }
angular/packages/router/test/url_serializer.spec.ts_405_8199
describe('url serializer', () => { const url = new DefaultUrlSerializer(); it('should parse the root url', () => { const tree = url.parse('/'); expectSegment(tree.root, ''); expect(url.serialize(tree)).toEqual('/'); }); it('should parse non-empty urls', () => { const tree = url.parse('one/two'); expectSegment(tree.root.children[PRIMARY_OUTLET], 'one/two'); expect(url.serialize(tree)).toEqual('/one/two'); }); it('should parse multiple secondary segments', () => { const tree = url.parse('/one/two(left:three//right:four)'); expectSegment(tree.root.children[PRIMARY_OUTLET], 'one/two'); expectSegment(tree.root.children['left'], 'three'); expectSegment(tree.root.children['right'], 'four'); expect(url.serialize(tree)).toEqual('/one/two(left:three//right:four)'); }); it('should parse secondary segments with an = in the name', () => { const tree = url.parse('/path/to/some=file'); expect(tree.root.children['primary'].segments[2].path).toEqual('some=file'); }); it('should parse segments with matrix parameters when the name contains an =', () => { const tree = url.parse('/path/to/some=file;test=11'); expect(tree.root.children['primary'].segments[2].path).toEqual('some=file'); expect(tree.root.children['primary'].segments[2].parameterMap.keys).toHaveSize(1); expect(tree.root.children['primary'].segments[2].parameterMap.get('test')).toEqual('11'); }); it('should parse segments that end with an =', () => { const tree = url.parse('/password/de/MDAtMNTk='); expect(tree.root.children['primary'].segments[2].path).toEqual('MDAtMNTk='); }); it('should parse segments that only contain an =', () => { const tree = url.parse('example.com/prefix/='); expect(tree.root.children['primary'].segments[2].path).toEqual('='); }); it('should parse segments with matrix parameter values containing an =', () => { const tree = url.parse('/path/to/something;query=file=test;query2=test2'); expect(tree.root.children['primary'].segments[2].path).toEqual('something'); expect(tree.root.children['primary'].segments[2].parameterMap.keys).toHaveSize(2); expect(tree.root.children['primary'].segments[2].parameterMap.get('query')).toEqual( 'file=test', ); expect(tree.root.children['primary'].segments[2].parameterMap.get('query2')).toEqual('test2'); }); it('should parse top-level nodes with only secondary segment', () => { const tree = url.parse('/(left:one)'); expect(tree.root.numberOfChildren).toEqual(1); expectSegment(tree.root.children['left'], 'one'); expect(url.serialize(tree)).toEqual('/(left:one)'); }); it('should parse nodes with only secondary segment', () => { const tree = url.parse('/one/(left:two)'); const one = tree.root.children[PRIMARY_OUTLET]; expectSegment(one, 'one', true); expect(one.numberOfChildren).toEqual(1); expectSegment(one.children['left'], 'two'); expect(url.serialize(tree)).toEqual('/one/(left:two)'); }); it('should not parse empty path segments with params', () => { expect(() => url.parse('/one/two/(;a=1//right:;b=2)')).toThrowError( /Empty path url segment cannot have parameters/, ); }); it('should parse scoped secondary segments', () => { const tree = url.parse('/one/(two//left:three)'); const primary = tree.root.children[PRIMARY_OUTLET]; expectSegment(primary, 'one', true); expectSegment(primary.children[PRIMARY_OUTLET], 'two'); expectSegment(primary.children['left'], 'three'); expect(url.serialize(tree)).toEqual('/one/(two//left:three)'); }); it('should parse scoped secondary segments with unscoped ones', () => { const tree = url.parse('/one/(two//left:three)(right:four)'); const primary = tree.root.children[PRIMARY_OUTLET]; expectSegment(primary, 'one', true); expectSegment(primary.children[PRIMARY_OUTLET], 'two'); expectSegment(primary.children['left'], 'three'); expectSegment(tree.root.children['right'], 'four'); expect(url.serialize(tree)).toEqual('/one/(two//left:three)(right:four)'); }); it('should parse secondary segments that have children', () => { const tree = url.parse('/one(left:two/three)'); expectSegment(tree.root.children[PRIMARY_OUTLET], 'one'); expectSegment(tree.root.children['left'], 'two/three'); expect(url.serialize(tree)).toEqual('/one(left:two/three)'); }); it('should parse an empty secondary segment group', () => { const tree = url.parse('/one()'); expectSegment(tree.root.children[PRIMARY_OUTLET], 'one'); expect(url.serialize(tree)).toEqual('/one'); }); it('should parse key-value matrix params', () => { const tree = url.parse('/one;a=11a;b=11b(left:two;c=22//right:three;d=33)'); expectSegment(tree.root.children[PRIMARY_OUTLET], 'one;a=11a;b=11b'); expectSegment(tree.root.children['left'], 'two;c=22'); expectSegment(tree.root.children['right'], 'three;d=33'); expect(url.serialize(tree)).toEqual('/one;a=11a;b=11b(left:two;c=22//right:three;d=33)'); }); it('should parse key only matrix params', () => { const tree = url.parse('/one;a'); expectSegment(tree.root.children[PRIMARY_OUTLET], 'one;a='); expect(url.serialize(tree)).toEqual('/one;a='); }); it('should parse query params (root)', () => { const tree = url.parse('/?a=1&b=2'); expect(tree.root.children).toEqual({}); expect(tree.queryParams).toEqual({a: '1', b: '2'}); expect(url.serialize(tree)).toEqual('/?a=1&b=2'); }); it('should parse query params', () => { const tree = url.parse('/one?a=1&b=2'); expect(tree.queryParams).toEqual({a: '1', b: '2'}); }); it('should parse query params when with parenthesis', () => { const tree = url.parse('/one?a=(11)&b=(22)'); expect(tree.queryParams).toEqual({a: '(11)', b: '(22)'}); }); it('should parse query params when with slashes', () => { const tree = url.parse('/one?a=1/2&b=3/4'); expect(tree.queryParams).toEqual({a: '1/2', b: '3/4'}); }); it('should parse key only query params', () => { const tree = url.parse('/one?a'); expect(tree.queryParams).toEqual({a: ''}); }); it('should parse a value-empty query param', () => { const tree = url.parse('/one?a='); expect(tree.queryParams).toEqual({a: ''}); }); it('should parse value-empty query params', () => { const tree = url.parse('/one?a=&b='); expect(tree.queryParams).toEqual({a: '', b: ''}); }); it('should serializer query params', () => { const tree = url.parse('/one?a'); expect(url.serialize(tree)).toEqual('/one?a='); }); it('should handle multiple query params of the same name into an array', () => { const tree = url.parse('/one?a=foo&a=bar&a=swaz'); expect(tree.queryParams).toEqual({a: ['foo', 'bar', 'swaz']}); expect(tree.queryParamMap.get('a')).toEqual('foo'); expect(tree.queryParamMap.getAll('a')).toEqual(['foo', 'bar', 'swaz']); expect(url.serialize(tree)).toEqual('/one?a=foo&a=bar&a=swaz'); }); it('should parse fragment', () => { const tree = url.parse('/one#two'); expect(tree.fragment).toEqual('two'); expect(url.serialize(tree)).toEqual('/one#two'); }); it('should parse fragment (root)', () => { const tree = url.parse('/#one'); expectSegment(tree.root, ''); expect(url.serialize(tree)).toEqual('/#one'); }); it('should parse empty fragment', () => { const tree = url.parse('/one#'); expect(tree.fragment).toEqual(''); expect(url.serialize(tree)).toEqual('/one#'); }); it('should parse no fragment', () => { const tree = url.parse('/one'); expect(tree.fragment).toEqual(null); expect(url.serialize(tree)).toEqual('/one'); });
{ "end_byte": 8199, "start_byte": 405, "url": "https://github.com/angular/angular/blob/main/packages/router/test/url_serializer.spec.ts" }
angular/packages/router/test/url_serializer.spec.ts_8203_15681
describe('encoding/decoding', () => { it('should encode/decode path segments and parameters', () => { const u = `/${encodeUriSegment('one two')};${encodeUriSegment('p 1')}=${encodeUriSegment( 'v 1', )};${encodeUriSegment('p 2')}=${encodeUriSegment('v 2')}`; const tree = url.parse(u); expect(tree.root.children[PRIMARY_OUTLET].segments[0].path).toEqual('one two'); expect(tree.root.children[PRIMARY_OUTLET].segments[0].parameters).toEqual({ ['p 1']: 'v 1', ['p 2']: 'v 2', }); expect(url.serialize(tree)).toEqual(u); }); it('should encode/decode "slash" in path segments and parameters', () => { const u = `/${encodeUriSegment('one/two')};${encodeUriSegment('p/1')}=${encodeUriSegment( 'v/1', )}/three`; const tree = url.parse(u); const segment = tree.root.children[PRIMARY_OUTLET].segments[0]; expect(segment.path).toEqual('one/two'); expect(segment.parameters).toEqual({'p/1': 'v/1'}); expect(segment.parameterMap.get('p/1')).toEqual('v/1'); expect(segment.parameterMap.getAll('p/1')).toEqual(['v/1']); expect(url.serialize(tree)).toEqual(u); }); it('should encode/decode query params', () => { const u = `/one?${encodeUriQuery('p 1')}=${encodeUriQuery('v 1')}&${encodeUriQuery( 'p 2', )}=${encodeUriQuery('v 2')}`; const tree = url.parse(u); expect(tree.queryParams).toEqual({'p 1': 'v 1', 'p 2': 'v 2'}); expect(tree.queryParamMap.get('p 1')).toEqual('v 1'); expect(tree.queryParamMap.get('p 2')).toEqual('v 2'); expect(url.serialize(tree)).toEqual(u); }); it('should decode spaces in query as %20 or +', () => { const u1 = `/one?foo=bar baz`; const u2 = `/one?foo=bar+baz`; const u3 = `/one?foo=bar%20baz`; const u1p = url.parse(u1); const u2p = url.parse(u2); const u3p = url.parse(u3); expect(url.serialize(u1p)).toBe(url.serialize(u2p)); expect(url.serialize(u2p)).toBe(url.serialize(u3p)); expect(u1p.queryParamMap.get('foo')).toBe('bar baz'); expect(u2p.queryParamMap.get('foo')).toBe('bar baz'); expect(u3p.queryParamMap.get('foo')).toBe('bar baz'); }); it('should encode query params leaving sub-delimiters intact', () => { const percentChars = '/?#&+=[] '; const percentCharsEncoded = '%2F%3F%23%26%2B%3D%5B%5D%20'; const intactChars = "!$'()*,;:"; const params = percentChars + intactChars; const paramsEncoded = percentCharsEncoded + intactChars; const mixedCaseString = 'sTrInG'; expect(percentCharsEncoded).toEqual(encodeUriQuery(percentChars)); expect(intactChars).toEqual(encodeUriQuery(intactChars)); // Verify it replaces repeated characters correctly expect(paramsEncoded + paramsEncoded).toEqual(encodeUriQuery(params + params)); // Verify it doesn't change the case of alpha characters expect(mixedCaseString + paramsEncoded).toEqual(encodeUriQuery(mixedCaseString + params)); }); it('should encode/decode fragment', () => { const u = `/one#${encodeUriFragment('one two=three four')}`; const tree = url.parse(u); expect(tree.fragment).toEqual('one two=three four'); expect(url.serialize(tree)).toEqual('/one#one%20two=three%20four'); }); }); describe('special character encoding/decoding', () => { // Tests specific to https://github.com/angular/angular/issues/10280 it('should parse encoded parens in matrix params', () => { const auxRoutesUrl = '/abc;foo=(other:val)'; const fooValueUrl = '/abc;foo=%28other:val%29'; const auxParsed = url.parse(auxRoutesUrl).root; const fooParsed = url.parse(fooValueUrl).root; // Test base case expect(auxParsed.children[PRIMARY_OUTLET].segments.length).toBe(1); expect(auxParsed.children[PRIMARY_OUTLET].segments[0].path).toBe('abc'); expect(auxParsed.children[PRIMARY_OUTLET].segments[0].parameters).toEqual({foo: ''}); expect(auxParsed.children['other'].segments.length).toBe(1); expect(auxParsed.children['other'].segments[0].path).toBe('val'); // Confirm matrix params are URL decoded expect(fooParsed.children[PRIMARY_OUTLET].segments.length).toBe(1); expect(fooParsed.children[PRIMARY_OUTLET].segments[0].path).toBe('abc'); expect(fooParsed.children[PRIMARY_OUTLET].segments[0].parameters).toEqual({ foo: '(other:val)', }); }); it('should serialize encoded parens in matrix params', () => { const testUrl = '/abc;foo=%28one%29'; const parsed = url.parse(testUrl); expect(url.serialize(parsed)).toBe('/abc;foo=%28one%29'); }); it('should not serialize encoded parens in query params', () => { const testUrl = '/abc?foo=%28one%29'; const parsed = url.parse(testUrl); expect(parsed.queryParams).toEqual({foo: '(one)'}); expect(url.serialize(parsed)).toBe('/abc?foo=(one)'); }); // Test special characters in general // From https://tools.ietf.org/html/rfc3986 const unreserved = `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`; it('should encode a minimal set of special characters in queryParams', () => { const notEncoded = unreserved + `:@!$'*,();`; const encode = ` +%&=#[]/?`; const encoded = `%20%2B%25%26%3D%23%5B%5D%2F%3F`; const parsed = url.parse('/foo'); parsed.queryParams = {notEncoded, encode}; expect(url.serialize(parsed)).toBe(`/foo?notEncoded=${notEncoded}&encode=${encoded}`); }); it('should encode a minimal set of special characters in fragment', () => { const notEncoded = unreserved + `:@!$'*,();+&=#/?`; const encode = ' %<>`"[]'; const encoded = `%20%25%3C%3E%60%22%5B%5D`; const parsed = url.parse('/foo'); parsed.fragment = notEncoded + encode; expect(url.serialize(parsed)).toBe(`/foo#${notEncoded}${encoded}`); }); it('should encode minimal special characters plus parens and semi-colon in matrix params', () => { const notEncoded = unreserved + `:@!$'*,&`; const encode = ` /%=#()[];?+`; const encoded = `%20%2F%25%3D%23%28%29%5B%5D%3B%3F%2B`; const parsed = url.parse('/foo'); parsed.root.children[PRIMARY_OUTLET].segments[0].parameters = {notEncoded, encode}; expect(url.serialize(parsed)).toBe(`/foo;notEncoded=${notEncoded};encode=${encoded}`); }); it('should encode special characters in the path the same as matrix params', () => { const notEncoded = unreserved + `:@!$'*,&`; const encode = ` /%=#()[];?+`; const encoded = `%20%2F%25%3D%23%28%29%5B%5D%3B%3F%2B`; const parsed = url.parse('/foo'); parsed.root.children[PRIMARY_OUTLET].segments[0].path = notEncoded + encode; expect(url.serialize(parsed)).toBe(`/${notEncoded}${encoded}`); }); it('should correctly encode ampersand in segments', () => { const testUrl = '/parent&child'; const parsed = url.parse(testUrl); expect(url.serialize(parsed)).toBe(testUrl); }); }); describe('error handling', () => { it('should throw when invalid characters inside children', () => { expect(() => url.parse('/one/(left#one)')).toThrowError(); }); it('should throw when missing closing )', () => { expect(() => url.parse('/one/(left')).toThrowError(); }); }); });
{ "end_byte": 15681, "start_byte": 8203, "url": "https://github.com/angular/angular/blob/main/packages/router/test/url_serializer.spec.ts" }
angular/packages/router/test/url_serializer.spec.ts_15683_16113
function expectSegment( segment: UrlSegmentGroup, expected: string, hasChildren: boolean = false, ): void { if (segment.segments.filter((s) => s.path === '').length > 0) { throw new Error(`UrlSegments cannot be empty ${segment.segments}`); } const p = segment.segments.map((p) => serializePath(p)).join('/'); expect(p).toEqual(expected); expect(Object.keys(segment.children).length > 0).toEqual(hasChildren); }
{ "end_byte": 16113, "start_byte": 15683, "url": "https://github.com/angular/angular/blob/main/packages/router/test/url_serializer.spec.ts" }
angular/packages/router/test/create_url_tree.spec.ts_0_4384
/** * @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.dev/license */ import {Component, Injectable} from '@angular/core'; import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {createUrlTreeFromSnapshot} from '../src/create_url_tree'; import {QueryParamsHandling, Routes} from '../src/models'; import {Router} from '../src/router'; import {RouterModule} from '../src/router_module'; import {ActivatedRoute, ActivatedRouteSnapshot} from '../src/router_state'; import {Params, PRIMARY_OUTLET} from '../src/shared'; import {DefaultUrlSerializer, UrlTree} from '../src/url_tree'; import {provideRouter, withRouterConfig} from '../src'; describe('createUrlTree', async () => { const serializer = new DefaultUrlSerializer(); let router: Router; beforeEach(() => { router = TestBed.inject(Router); router.resetConfig([ { path: 'parent', children: [ {path: 'child', component: class {}}, {path: '**', outlet: 'secondary', component: class {}}, ], }, { path: 'a', children: [ {path: '**', component: class {}}, {path: '**', outlet: 'right', component: class {}}, {path: '**', outlet: 'left', component: class {}}, ], }, {path: '**', component: class {}}, {path: '**', outlet: 'right', component: class {}}, {path: '**', outlet: 'left', component: class {}}, {path: '**', outlet: 'rootSecondary', component: class {}}, ]); }); describe('query parameters', async () => { it('should support parameter with multiple values', async () => { const p1 = serializer.parse('/'); const t1 = await createRoot(p1, ['/'], {m: ['v1', 'v2']}); expect(serializer.serialize(t1)).toEqual('/?m=v1&m=v2'); await router.navigateByUrl('/a/c'); const t2 = create(router.routerState.root.children[0].children[0], ['c2'], {m: ['v1', 'v2']}); expect(serializer.serialize(t2)).toEqual('/a/c/c2?m=v1&m=v2'); }); it('should support parameter with empty arrays as values', async () => { await router.navigateByUrl('/a/c'); const t1 = create(router.routerState.root.children[0].children[0], ['c2'], {m: []}); expect(serializer.serialize(t1)).toEqual('/a/c/c2'); const t2 = create(router.routerState.root.children[0].children[0], ['c2'], {m: [], n: 1}); expect(serializer.serialize(t2)).toEqual('/a/c/c2?n=1'); }); it('should set query params', async () => { const p = serializer.parse('/'); const t = await createRoot(p, [], {a: 'hey'}); expect(t.queryParams).toEqual({a: 'hey'}); expect(t.queryParamMap.get('a')).toEqual('hey'); }); it('should stringify query params', async () => { const p = serializer.parse('/'); const t = await createRoot(p, [], {a: 1}); expect(t.queryParams).toEqual({a: '1'}); expect(t.queryParamMap.get('a')).toEqual('1'); }); }); it('should navigate to the root', async () => { const p = serializer.parse('/'); const t = await createRoot(p, ['/']); expect(serializer.serialize(t)).toEqual('/'); }); it('should error when navigating to the root segment with params', async () => { const p = serializer.parse('/'); await expectAsync(createRoot(p, ['/', {p: 11}])).toBeRejectedWithError( /Root segment cannot have matrix parameters/, ); }); it('should support nested segments', async () => { const p = serializer.parse('/a/b'); const t = await createRoot(p, ['/one', 11, 'two', 22]); expect(serializer.serialize(t)).toEqual('/one/11/two/22'); }); it('should stringify positional parameters', async () => { const p = serializer.parse('/a/b'); const t = await createRoot(p, ['/one', 11]); const params = t.root.children[PRIMARY_OUTLET].segments; expect(params[0].path).toEqual('one'); expect(params[1].path).toEqual('11'); }); it('should support first segments containing slashes', async () => { const p = serializer.parse('/'); const t = await createRoot(p, [{segmentPath: '/one'}, 'two/three']); expect(serializer.serialize(t)).toEqual('/%2Fone/two%2Fthree'); });
{ "end_byte": 4384, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/create_url_tree.spec.ts" }
angular/packages/router/test/create_url_tree.spec.ts_4388_11070
describe('named outlets', async () => { it('should preserve secondary segments', async () => { const p = serializer.parse('/a/11/b(right:c)'); const t = await createRoot(p, ['/a', 11, 'd']); expect(serializer.serialize(t)).toEqual('/a/11/d(right:c)'); }); it('should support updating secondary segments (absolute)', async () => { const p = serializer.parse('/a(right:b)'); const t = await createRoot(p, ['/', {outlets: {right: ['c']}}]); expect(serializer.serialize(t)).toEqual('/a(right:c)'); }); it('should support updating secondary segments', async () => { const p = serializer.parse('/a(right:b)'); const t = await createRoot(p, [{outlets: {right: ['c', 11, 'd']}}]); expect(serializer.serialize(t)).toEqual('/a(right:c/11/d)'); }); it('should support updating secondary segments (nested case)', async () => { const p = serializer.parse('/a/(b//right:c)'); const t = await createRoot(p, ['a', {outlets: {right: ['d', 11, 'e']}}]); expect(serializer.serialize(t)).toEqual('/a/(b//right:d/11/e)'); }); it('should support removing secondary outlet with prefix', async () => { const p = serializer.parse('/parent/(child//secondary:popup)'); const t = await createRoot(p, ['parent', {outlets: {secondary: null}}]); // - Segment index 0: // * match and keep existing 'parent' // - Segment index 1: // * 'secondary' outlet cleared with `null` // * 'primary' outlet not provided in the commands list, so the existing value is kept expect(serializer.serialize(t)).toEqual('/parent/child'); }); it('should support updating secondary and primary outlets with prefix', async () => { const p = serializer.parse('/parent/child'); const t = await createRoot(p, ['parent', {outlets: {primary: 'child', secondary: 'popup'}}]); expect(serializer.serialize(t)).toEqual('/parent/(child//secondary:popup)'); }); it('should support updating two outlets at the same time relative to non-root segment', async () => { await router.navigateByUrl('/parent/child'); const t = create(router.routerState.root.children[0], [ {outlets: {primary: 'child', secondary: 'popup'}}, ]); expect(serializer.serialize(t)).toEqual('/parent/(child//secondary:popup)'); }); it('should support adding multiple outlets with prefix', async () => { const p = serializer.parse(''); const t = await createRoot(p, ['parent', {outlets: {primary: 'child', secondary: 'popup'}}]); expect(serializer.serialize(t)).toEqual('/parent/(child//secondary:popup)'); }); it('should support updating clearing primary and secondary with prefix', async () => { const p = serializer.parse('/parent/(child//secondary:popup)'); const t = await createRoot(p, ['other']); // Because we navigate away from the 'parent' route, the children of that route are cleared // because they are note valid for the 'other' path. expect(serializer.serialize(t)).toEqual('/other'); }); it('should not clear secondary outlet when at root and prefix is used', async () => { const p = serializer.parse('/other(rootSecondary:rootPopup)'); const t = await createRoot(p, ['parent', {outlets: {primary: 'child', rootSecondary: null}}]); // We prefixed the navigation with 'parent' so we cannot clear the "rootSecondary" outlet // because once the outlets object is consumed, traversal is beyond the root segment. expect(serializer.serialize(t)).toEqual('/parent/child(rootSecondary:rootPopup)'); }); it('should not clear non-root secondary outlet when command is targeting root', async () => { const p = serializer.parse('/parent/(child//secondary:popup)'); const t = await createRoot(p, [{outlets: {secondary: null}}]); // The start segment index for the command is at 0, but the outlet lives at index 1 // so we cannot clear the outlet from processing segment index 0. expect(serializer.serialize(t)).toEqual('/parent/(child//secondary:popup)'); }); it('can clear an auxiliary outlet at the correct segment level', async () => { const p = serializer.parse('/parent/(child//secondary:popup)(rootSecondary:rootPopup)'); // ^^^^^^^^^^^^^^^^^^^^^^ // The parens here show that 'child' and 'secondary:popup' appear at the same 'level' in the // config, i.e. are part of the same children list. You can also imagine an implicit paren // group around the whole URL to visualize how 'parent' and 'rootSecondary:rootPopup' are also // defined at the same level. const t = await createRoot(p, ['parent', {outlets: {primary: 'child', secondary: null}}]); expect(serializer.serialize(t)).toEqual('/parent/child(rootSecondary:rootPopup)'); }); it('works with named children of empty path primary, relative to non-empty parent', async () => { router.resetConfig([ { path: 'case', component: class {}, children: [ { path: '', component: class {}, children: [{path: 'foo', outlet: 'foo', children: []}], }, ], }, ]); await router.navigateByUrl('/case'); expect(router.url).toEqual('/case'); expect( router .createUrlTree( [{outlets: {'foo': ['foo']}}], // relative to the 'case' route {relativeTo: router.routerState.root.firstChild}, ) .toString(), ).toEqual('/case/(foo:foo)'); }); it('can change both primary and named outlets under an empty path', async () => { router.resetConfig([ { path: 'foo', children: [ { path: '', component: class {}, children: [ {path: 'bar', component: class {}}, {path: 'baz', component: class {}, outlet: 'other'}, ], }, ], }, ]); await router.navigateByUrl('/foo/(bar//other:baz)'); expect(router.url).toEqual('/foo/(bar//other:baz)'); expect( router .createUrlTree( [ { outlets: { other: null, primary: ['bar'], }, }, ], // relative to the root '' route {relativeTo: router.routerState.root.firstChild}, ) .toString(), ).toEqual('/foo/bar'); });
{ "end_byte": 11070, "start_byte": 4388, "url": "https://github.com/angular/angular/blob/main/packages/router/test/create_url_tree.spec.ts" }
angular/packages/router/test/create_url_tree.spec.ts_11076_17592
describe('absolute navigations', () => { it('with and pathless root', async () => { router.resetConfig([ { path: '', children: [{path: '**', outlet: 'left', component: class {}}], }, ]); await router.navigateByUrl('(left:search)'); expect(router.url).toEqual('/(left:search)'); expect( router.createUrlTree(['/', {outlets: {'left': ['projects', '123']}}]).toString(), ).toEqual('/(left:projects/123)'); }); it('empty path parent and sibling with a path', async () => { router.resetConfig([ { path: '', children: [ {path: 'x', component: class {}}, {path: '**', outlet: 'left', component: class {}}, ], }, ]); await router.navigateByUrl('/x(left:search)'); expect(router.url).toEqual('/x(left:search)'); expect( router.createUrlTree(['/', {outlets: {'left': ['projects', '123']}}]).toString(), ).toEqual('/x(left:projects/123)'); expect( router .createUrlTree([ '/', { outlets: { 'primary': [ { outlets: { 'left': ['projects', '123'], }, }, ], }, }, ]) .toString(), ).toEqual('/x(left:projects/123)'); }); it('empty path parent and sibling', async () => { router.resetConfig([ { path: '', children: [ {path: '', component: class {}}, {path: '**', outlet: 'left', component: class {}}, {path: '**', outlet: 'right', component: class {}}, ], }, ]); await router.navigateByUrl('/(left:search//right:define)'); expect(router.url).toEqual('/(left:search//right:define)'); expect( router.createUrlTree(['/', {outlets: {'left': ['projects', '123']}}]).toString(), ).toEqual('/(left:projects/123//right:define)'); }); it('two pathless parents', async () => { router.resetConfig([ { path: '', children: [ { path: '', children: [{path: '**', outlet: 'left', component: class {}}], }, ], }, ]); await router.navigateByUrl('(left:search)'); expect(router.url).toEqual('/(left:search)'); expect( router.createUrlTree(['/', {outlets: {'left': ['projects', '123']}}]).toString(), ).toEqual('/(left:projects/123)'); }); it('maintains structure when primary outlet is not pathless', async () => { router.resetConfig([ { path: 'a', children: [{path: '**', outlet: 'left', component: class {}}], }, {path: '**', outlet: 'left', component: class {}}, ]); await router.navigateByUrl('/a/(left:search)'); expect(router.url).toEqual('/a/(left:search)'); expect( router.createUrlTree(['/', {outlets: {'left': ['projects', '123']}}]).toString(), ).toEqual('/a/(left:search)(left:projects/123)'); }); }); }); it('can navigate to nested route where commands is string', async () => { const p = serializer.parse('/'); const t = await createRoot(p, [ '/', {outlets: {primary: ['child', {outlets: {primary: 'nested-primary'}}]}}, ]); expect(serializer.serialize(t)).toEqual('/child/nested-primary'); }); it('should throw when outlets is not the last command', async () => { const p = serializer.parse('/a'); await expectAsync(createRoot(p, ['a', {outlets: {right: ['c']}}, 'c'])).toBeRejected(); }); it('should support updating using a string', async () => { const p = serializer.parse('/a(right:b)'); const t = await createRoot(p, [{outlets: {right: 'c/11/d'}}]); expect(serializer.serialize(t)).toEqual('/a(right:c/11/d)'); }); it('should support updating primary and secondary segments at once', async () => { const p = serializer.parse('/a(right:b)'); const t = await createRoot(p, [{outlets: {primary: 'y/z', right: 'c/11/d'}}]); expect(serializer.serialize(t)).toEqual('/y/z(right:c/11/d)'); }); it('should support removing primary segment', async () => { const p = serializer.parse('/a/(b//right:c)'); const t = await createRoot(p, ['a', {outlets: {primary: null, right: 'd'}}]); expect(serializer.serialize(t)).toEqual('/a/(right:d)'); }); it('should support removing secondary segments', async () => { const p = serializer.parse('/a(right:b)'); const t = await createRoot(p, [{outlets: {right: null}}]); expect(serializer.serialize(t)).toEqual('/a'); }); it('should support removing parenthesis for primary segment on second path element', async () => { const p = serializer.parse('/a/(b//right:c)'); const t = await createRoot(p, ['a', {outlets: {right: null}}]); expect(serializer.serialize(t)).toEqual('/a/b'); }); it('should update matrix parameters', async () => { const p = serializer.parse('/a;pp=11'); const t = await createRoot(p, ['/a', {pp: 22, dd: 33}]); expect(serializer.serialize(t)).toEqual('/a;pp=22;dd=33'); }); it('should create matrix parameters', async () => { const p = serializer.parse('/a'); const t = await createRoot(p, ['/a', {pp: 22, dd: 33}]); expect(serializer.serialize(t)).toEqual('/a;pp=22;dd=33'); }); it('should create matrix parameters together with other segments', async () => { const p = serializer.parse('/a'); const t = await createRoot(p, ['/a', 'b', {aa: 22, bb: 33}]); expect(serializer.serialize(t)).toEqual('/a/b;aa=22;bb=33'); }); it('should stringify matrix parameters', async () => { await router.navigateByUrl('/a'); const relative = create(router.routerState.root.children[0], [{pp: 22}]); const segmentR = relative.root.children[PRIMARY_OUTLET].segments[0]; expect(segmentR.parameterMap.get('pp')).toEqual('22'); const pa = serializer.parse('/a'); const absolute = await createRoot(pa, ['/b', {pp: 33}]); const segmentA = absolute.root.children[PRIMARY_OUTLET].segments[0]; expect(segmentA.parameterMap.get('pp')).toEqual('33'); });
{ "end_byte": 17592, "start_byte": 11076, "url": "https://github.com/angular/angular/blob/main/packages/router/test/create_url_tree.spec.ts" }
angular/packages/router/test/create_url_tree.spec.ts_17596_24953
describe('relative navigation', async () => { it('should work', async () => { await router.navigateByUrl('/a/(c//left:cp)(left:ap)'); const t = create(router.routerState.root.children[0], ['c2']); expect(serializer.serialize(t)).toEqual('/a/(c2//left:cp)(left:ap)'); }); it('should work when the first command starts with a ./', async () => { await router.navigateByUrl('/a/(c//left:cp)(left:ap)'); const t = create(router.routerState.root.children[0], ['./c2']); expect(serializer.serialize(t)).toEqual('/a/(c2//left:cp)(left:ap)'); }); it('should work when the first command is ./)', async () => { await router.navigateByUrl('/a/(c//left:cp)(left:ap)'); const t = create(router.routerState.root.children[0], ['./', 'c2']); expect(serializer.serialize(t)).toEqual('/a/(c2//left:cp)(left:ap)'); }); it('should support parameters-only navigation', async () => { await router.navigateByUrl('/a'); const t = create(router.routerState.root.children[0], [{k: 99}]); expect(serializer.serialize(t)).toEqual('/a;k=99'); }); it('should support parameters-only navigation (nested case)', async () => { await router.navigateByUrl('/a/(c//left:cp)(left:ap)'); const t = create(router.routerState.root.children[0], [{'x': 99}]); expect(serializer.serialize(t)).toEqual('/a;x=99(left:ap)'); }); it('should support parameters-only navigation (with a double dot)', async () => { await router.navigateByUrl('/a/(c//left:cp)(left:ap)'); const t = create(router.routerState.root.children[0].children[0], ['../', {x: 5}]); expect(serializer.serialize(t)).toEqual('/a;x=5(left:ap)'); }); it('should work when index > 0', async () => { await router.navigateByUrl('/a/c'); const t = create(router.routerState.root.children[0].children[0], ['c2']); expect(serializer.serialize(t)).toEqual('/a/c/c2'); }); it('should support going to a parent (within a segment)', async () => { await router.navigateByUrl('/a/c'); const t = create(router.routerState.root.children[0].children[0], ['../c2']); expect(serializer.serialize(t)).toEqual('/a/c2'); }); it('should support going to a parent (across segments)', async () => { await router.navigateByUrl('/q/(a/(c//left:cp)//left:qp)(left:ap)'); // The resulting URL isn't necessarily correct. Though we could never truly navigate to the // URL above, this should probably go to '/q/a/c(left:ap)' at the very least and potentially // be able to go somewhere like /q/a/c/(left:xyz)(left:ap). That is, allow matching named // outlets as long as they do not have a primary outlet sibling. Having a primary outlet // sibling isn't possible because the wildcard should consume all the primary outlet segments // so there cannot be any remaining in the children. // https://github.com/angular/angular/issues/40089 expect(router.url).toEqual('/q(left:ap)'); const t = create(router.routerState.root.children[0].children[0], ['../../q2']); expect(serializer.serialize(t)).toEqual('/q2(left:ap)'); }); it('should navigate to the root', async () => { await router.navigateByUrl('/a/c'); const t = create(router.routerState.root.children[0], ['../']); expect(serializer.serialize(t)).toEqual('/'); }); it('should work with ../ when absolute url', async () => { await router.navigateByUrl('/a/c'); const t = create(router.routerState.root.children[0].children[0], ['../', 'c2']); expect(serializer.serialize(t)).toEqual('/a/c2'); }); it('should work relative to root', async () => { await router.navigateByUrl('/'); const t = create(router.routerState.root, ['11']); expect(serializer.serialize(t)).toEqual('/11'); }); it('should throw when too many ..', async () => { await router.navigateByUrl('/a/(c//left:cp)(left:ap)'); expect(() => create(router.routerState.root.children[0], ['../../'])).toThrowError(); }); it('should support updating secondary segments', async () => { await router.navigateByUrl('/a/b'); const t = create(router.routerState.root.children[0].children[0], [ {outlets: {right: ['c']}}, ]); expect(serializer.serialize(t)).toEqual('/a/b/(right:c)'); }); }); it('should set fragment', async () => { const p = serializer.parse('/'); const t = await createRoot(p, [], {}, 'fragment'); expect(t.fragment).toEqual('fragment'); }); it('should support pathless route', async () => { const p = serializer.parse('/a'); const t = create(router.routerState.root.children[0], ['b']); expect(serializer.serialize(t)).toEqual('/b'); }); it('should support pathless route with ../ at root', async () => { const p = serializer.parse('/a'); const t = create(router.routerState.root.children[0], ['../b']); expect(serializer.serialize(t)).toEqual('/b'); }); it('should support pathless child of pathless root', async () => { router.resetConfig([ { path: '', children: [ {path: '', component: class {}}, {path: 'lazy', component: class {}}, ], }, ]); await router.navigateByUrl('/'); const t = create(router.routerState.root.children[0].children[0], ['lazy']); expect(serializer.serialize(t)).toEqual('/lazy'); }); }); describe('defaultQueryParamsHandling', () => { async function setupRouter(defaultQueryParamsHandling: QueryParamsHandling): Promise<Router> { TestBed.configureTestingModule({ providers: [ provideRouter( [{path: '**', component: class {}}], withRouterConfig({ defaultQueryParamsHandling, }), ), ], }); const router = TestBed.inject(Router); await router.navigateByUrl('/initial?a=1'); return router; } it('can use "merge" as the default', async () => { const router = await setupRouter('merge'); await router.navigate(['new'], {queryParams: {'b': 2}}); expect(router.url).toEqual('/new?a=1&b=2'); }); it('can use "perserve" as the default', async () => { const router = await setupRouter('preserve'); await router.navigate(['new'], {queryParams: {'b': 2}}); expect(router.url).toEqual('/new?a=1'); }); it('can override the default by providing a new option', async () => { const router = await setupRouter('preserve'); await router.navigate(['new'], {queryParams: {'b': 2}, queryParamsHandling: 'merge'}); expect(router.url).toEqual('/new?a=1&b=2'); await router.navigate(['replace'], {queryParamsHandling: 'replace'}); expect(router.url).toEqual('/replace'); }); }); async function createRoot( tree: UrlTree, commands: any[], queryParams?: Params, fragment?: string, ): Promise<UrlTree> { const router = TestBed.inject(Router); await router.navigateByUrl(tree); return router.createUrlTree(commands, { relativeTo: router.routerState.root, queryParams, fragment, }); } function create( relativeTo: ActivatedRoute, commands: any[], queryParams?: Params, fragment?: string, ) { return TestBed.inject(Router).createUrlTree(commands, {relativeTo, queryParams, fragment}); }
{ "end_byte": 24953, "start_byte": 17596, "url": "https://github.com/angular/angular/blob/main/packages/router/test/create_url_tree.spec.ts" }
angular/packages/router/test/create_url_tree.spec.ts_24955_27931
describe('createUrlTreeFromSnapshot', async () => { it('can create a UrlTree relative to empty path named parent', fakeAsync(() => { @Component({ template: `<router-outlet></router-outlet>`, standalone: true, imports: [RouterModule], }) class MainPageComponent { constructor( private route: ActivatedRoute, private router: Router, ) {} navigate() { this.router.navigateByUrl( createUrlTreeFromSnapshot(this.route.snapshot, ['innerRoute'], null, null), ); } } @Component({ template: 'child works!', standalone: false, }) class ChildComponent {} @Component({ template: '<router-outlet name="main-page"></router-outlet>', standalone: true, imports: [RouterModule], }) class RootCmp {} const routes: Routes = [ { path: '', component: MainPageComponent, outlet: 'main-page', children: [{path: 'innerRoute', component: ChildComponent}], }, ]; TestBed.configureTestingModule({imports: [RouterModule.forRoot(routes)]}); const router = TestBed.inject(Router); const fixture = TestBed.createComponent(RootCmp); router.initialNavigation(); advance(fixture); fixture.debugElement.query(By.directive(MainPageComponent)).componentInstance.navigate(); advance(fixture); expect(fixture.nativeElement.innerHTML).toContain('child works!'); })); it('can navigate to relative to `ActivatedRouteSnapshot` in guard', fakeAsync(() => { @Injectable({providedIn: 'root'}) class Guard { constructor(private readonly router: Router) {} canActivate(snapshot: ActivatedRouteSnapshot) { this.router.navigateByUrl(createUrlTreeFromSnapshot(snapshot, ['../sibling'], null, null)); } } @Component({ template: `main`, standalone: true, imports: [RouterModule], }) class GuardedComponent {} @Component({template: 'sibling', standalone: true}) class SiblingComponent {} @Component({ template: '<router-outlet></router-outlet>', standalone: true, imports: [RouterModule], }) class RootCmp {} const routes: Routes = [ { path: 'parent', component: RootCmp, children: [ { path: 'guarded', component: GuardedComponent, canActivate: [Guard], }, { path: 'sibling', component: SiblingComponent, }, ], }, ]; TestBed.configureTestingModule({imports: [RouterModule.forRoot(routes)]}); const router = TestBed.inject(Router); const fixture = TestBed.createComponent(RootCmp); router.navigateByUrl('parent/guarded'); advance(fixture); expect(router.url).toEqual('/parent/sibling'); })); }); function advance(fixture: ComponentFixture<unknown>) { tick(); fixture.detectChanges(); }
{ "end_byte": 27931, "start_byte": 24955, "url": "https://github.com/angular/angular/blob/main/packages/router/test/create_url_tree.spec.ts" }
angular/packages/router/test/router_navigation_extras.spec.ts_0_3491
/** * @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.dev/license */ import {Location} from '@angular/common'; import {Component, inject} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {Router, withRouterConfig} from '@angular/router'; import {provideRouter} from '../src/provide_router'; describe('`navigationExtras handling with redirects`', () => { describe(`eager url updates with navigationExtra.replaceUrl`, () => { it('should preserve `NavigationExtras.replaceUrl` when redirecting from guard using urlTree', async () => { TestBed.configureTestingModule({ providers: [ provideRouter( [ { path: 'first', component: SimpleCmp, }, { path: 'second', component: SimpleCmp, canActivate: [() => inject(Router).createUrlTree(['unguarded'])], }, { path: 'unguarded', component: SimpleCmp, }, ], withRouterConfig({ urlUpdateStrategy: 'eager', canceledNavigationResolution: 'computed', }), ), ], }); const location = TestBed.inject(Location); const router = TestBed.inject(Router); await router.navigateByUrl('first'); expect(location.path()).toEqual('/first'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 1})); const navPromise = router.navigateByUrl('/second', {replaceUrl: true}); expect(router.getCurrentNavigation()?.extras.replaceUrl).toEqual(true); await navPromise; expect(location.path()).toEqual('/unguarded'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 1})); }); }); describe(`deferred url updates function correctly when navigationExtras.replaceUrl false`, () => { it('should work when CanActivate redirects', async () => { TestBed.configureTestingModule({ providers: [ provideRouter( [ { path: 'first', component: SimpleCmp, }, { path: 'second', component: SimpleCmp, canActivate: [() => inject(Router).createUrlTree(['unguarded'])], }, { path: 'unguarded', component: SimpleCmp, }, ], withRouterConfig({ urlUpdateStrategy: 'deferred', canceledNavigationResolution: 'computed', }), ), ], }); const router = TestBed.inject(Router); await router.navigateByUrl('/first'); const location = TestBed.inject(Location); await router.navigateByUrl('/second'); expect(location.path()).toEqual('/unguarded'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 2})); location.back(); await Promise.resolve(); expect(location.path()).toEqual('/first'); expect(location.getState()).toEqual(jasmine.objectContaining({ɵrouterPageId: 1})); }); }); }); @Component({selector: 'simple-cmp', template: `simple`, standalone: true}) class SimpleCmp {}
{ "end_byte": 3491, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/router_navigation_extras.spec.ts" }
angular/packages/router/test/BUILD.bazel_0_1475
load("//tools:defaults.bzl", "karma_web_test_suite", "ts_library", "zone_compatible_jasmine_node_test") load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test") circular_dependency_test( name = "circular_deps_test", entry_point = "angular/packages/router/index.mjs", deps = ["//packages/router"], ) circular_dependency_test( name = "testing_circular_deps_test", entry_point = "angular/packages/router/testing/index.mjs", deps = ["//packages/router/testing"], ) ts_library( name = "test_lib", testonly = True, srcs = glob(["**/*.ts"]), # Visible to //:saucelabs_unit_tests_poc target visibility = ["//:__pkg__"], deps = [ "//packages/common", "//packages/common/testing", "//packages/core", "//packages/core/rxjs-interop", "//packages/core/testing", "//packages/platform-browser", "//packages/platform-browser-dynamic", "//packages/platform-browser/testing", "//packages/private/testing", "//packages/router", "//packages/router/testing", "@npm//rxjs", ], ) # Tests rely on `async/await` for change detection. # This syntax needs to be downleveled until ZoneJS supports it. zone_compatible_jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node"], deps = [ ":test_lib", ], ) karma_web_test_suite( name = "test_web", deps = [ ":test_lib", ], )
{ "end_byte": 1475, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/BUILD.bazel" }
angular/packages/router/test/config.spec.ts_0_6026
/** * @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.dev/license */ import {Routes} from '../src'; import {PRIMARY_OUTLET} from '../src/shared'; import {validateConfig} from '../src/utils/config'; describe('config', () => { describe('validateConfig', () => { it('should not throw when no errors', () => { expect(() => validateConfig([ {path: 'a', redirectTo: 'b'}, {path: 'b', component: ComponentA}, ]), ).not.toThrow(); }); it('should not throw when a matcher is provided', () => { expect(() => validateConfig([{matcher: () => null, component: ComponentA}])).not.toThrow(); }); it('should throw for undefined route', () => { expect(() => { validateConfig([ {path: 'a', component: ComponentA}, , {path: 'b', component: ComponentB}, ] as Routes); }).toThrowError(/Invalid configuration of route ''/); }); it('should throw for undefined route in children', () => { expect(() => { validateConfig([ { path: 'a', children: [{path: 'b', component: ComponentB}, ,], }, ] as Routes); }).toThrowError(/Invalid configuration of route 'a'/); }); it('should throw when Array is passed', () => { expect(() => { validateConfig([ {path: 'a', component: ComponentA}, [ {path: 'b', component: ComponentB}, {path: 'c', component: ComponentC}, ], ] as Routes); }).toThrowError(); }); it('should throw when redirectTo and children are used together', () => { expect(() => { validateConfig([ {path: 'a', redirectTo: 'b', children: [{path: 'b', component: ComponentA}]}, ]); }).toThrowError(); }); it('should validate children and report full path', () => { expect(() => validateConfig([{path: 'a', children: [{path: 'b'}]}])).toThrowError(); }); it('should properly report deeply nested path', () => { expect(() => validateConfig([ {path: 'a', children: [{path: 'b', children: [{path: 'c', children: [{path: 'd'}]}]}]}, ]), ).toThrowError(); }); it('should throw when redirectTo and loadChildren are used together', () => { expect(() => { validateConfig([{path: 'a', redirectTo: 'b', loadChildren: jasmine.createSpy('value')}]); }).toThrowError(); }); it('should throw when children and loadChildren are used together', () => { expect(() => { validateConfig([{path: 'a', children: [], loadChildren: jasmine.createSpy('value')}]); }).toThrowError(); }); it('should throw when component and redirectTo are used together', () => { expect(() => { validateConfig([{path: 'a', component: ComponentA, redirectTo: 'b'}]); }).toThrowError( new RegExp( `Invalid configuration of route 'a': redirectTo and component/loadComponent cannot be used together`, ), ); }); it('should throw when redirectTo and loadComponent are used together', () => { expect(() => { validateConfig([{path: 'a', redirectTo: 'b', loadComponent: () => ComponentA}]); }).toThrowError(); }); it('should throw when component and loadComponent are used together', () => { expect(() => { validateConfig([{path: 'a', component: ComponentA, loadComponent: () => ComponentA}]); }).toThrowError(); }); it('should throw when component and redirectTo are used together', () => { expect(() => { validateConfig([{path: 'a', redirectTo: 'b', canActivate: []}]); }).toThrowError(); }); it('should throw when path and matcher are used together', () => { expect(() => { validateConfig([{path: 'a', matcher: () => null, children: []}]); }).toThrowError(); }); it('should throw when path and matcher are missing', () => { expect(() => { validateConfig([{redirectTo: 'b'}]); }).toThrowError(); }); it('should throw when none of component and children or direct are missing', () => { expect(() => { validateConfig([{path: 'a'}]); }).toThrowError(); }); it('should throw when path starts with a slash', () => { expect(() => { validateConfig([{path: '/a', redirectTo: 'b'}]); }).toThrowError(); }); it('should throw when emptyPath is used with redirectTo without explicitly providing matching', () => { expect(() => { validateConfig([{path: '', redirectTo: 'b'}]); }).toThrowError(/Invalid configuration of route '{path: "", redirectTo: "b"}'/); }); it('should throw when path/outlet combination is invalid', () => { expect(() => { validateConfig([{path: 'a', outlet: 'aux'}]); }).toThrowError( /Invalid configuration of route 'a': a componentless route without children or loadChildren cannot have a named outlet set/, ); expect(() => validateConfig([{path: 'a', outlet: '', children: []}])).not.toThrow(); expect(() => validateConfig([{path: 'a', outlet: PRIMARY_OUTLET, children: []}]), ).not.toThrow(); }); it('should not throw when path/outlet combination is valid', () => { expect(() => { validateConfig([{path: 'a', outlet: 'aux', children: []}]); }).not.toThrow(); expect(() => { validateConfig([{path: 'a', outlet: 'aux', loadChildren: jasmine.createSpy('child')}]); }).not.toThrow(); }); it('should not throw when outlet has redirectTo', () => { expect(() => { validateConfig([{path: '', pathMatch: 'prefix', outlet: 'aux', redirectTo: 'main'}]); }).not.toThrow(); }); }); }); class ComponentA {} class ComponentB {} class ComponentC {}
{ "end_byte": 6026, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/config.spec.ts" }
angular/packages/router/test/integration.spec.ts_0_3719
/** * @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.dev/license */ import {CommonModule, HashLocationStrategy, Location, LocationStrategy} from '@angular/common'; import {ɵprovideFakePlatformNavigation} from '@angular/common/testing'; import { ChangeDetectionStrategy, Component, EnvironmentInjector, inject as coreInject, Inject, Injectable, InjectionToken, NgModule, NgModuleRef, NgZone, OnDestroy, QueryList, Type, ViewChildren, ɵConsole as Console, ɵNoopNgZone as NoopNgZone, } from '@angular/core'; import {ComponentFixture, fakeAsync, inject, TestBed, tick} from '@angular/core/testing'; import {By} from '@angular/platform-browser/src/dom/debug/by'; import {expect} from '@angular/platform-browser/testing/src/matchers'; import { ActivatedRoute, ActivatedRouteSnapshot, ActivationEnd, ActivationStart, ChildActivationEnd, ChildActivationStart, DefaultUrlSerializer, DetachedRouteHandle, Event, GuardsCheckEnd, GuardsCheckStart, Navigation, NavigationCancel, NavigationCancellationCode, NavigationEnd, NavigationError, NavigationSkipped, NavigationStart, ParamMap, Params, PreloadAllModules, PreloadingStrategy, PRIMARY_OUTLET, ResolveEnd, ResolveStart, RouteConfigLoadEnd, RouteConfigLoadStart, Router, RouteReuseStrategy, RouterEvent, RouterLink, RouterLinkActive, RouterModule, RouterOutlet, RouterPreloader, RouterStateSnapshot, RoutesRecognized, RunGuardsAndResolvers, UrlHandlingStrategy, UrlSegment, UrlSegmentGroup, UrlTree, } from '@angular/router'; import {RouterTestingHarness} from '@angular/router/testing'; import {concat, EMPTY, firstValueFrom, Observable, Observer, of, Subscription} from 'rxjs'; import {delay, filter, first, last, map, mapTo, takeWhile, tap} from 'rxjs/operators'; import { CanActivateChildFn, CanActivateFn, CanMatchFn, Data, ResolveFn, RedirectCommand, GuardResult, MaybeAsync, } from '../src/models'; import {provideRouter, withNavigationErrorHandler, withRouterConfig} from '../src/provide_router'; import {wrapIntoObservable} from '../src/utils/collection'; import {getLoadedRoutes} from '../src/utils/config'; const ROUTER_DIRECTIVES = [RouterLink, RouterLinkActive, RouterOutlet]; for (const browserAPI of ['navigation', 'history'] as const) { describe(`${browserAPI}-based routing`, () => { const noopConsole: Console = {log() {}, warn() {}}; beforeEach(() => { TestBed.configureTestingModule({ imports: [...ROUTER_DIRECTIVES, TestModule], providers: [ {provide: Console, useValue: noopConsole}, provideRouter([{path: 'simple', component: SimpleCmp}]), browserAPI === 'navigation' ? ɵprovideFakePlatformNavigation() : [], ], }); }); it('should navigate with a provided config', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.navigateByUrl('/simple'); advance(fixture); expect(location.path()).toEqual('/simple'); }), )); it('should navigate from ngOnInit hook', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'one', component: RouteCmp}, ]); const fixture = createRoot(router, RootCmpWithOnInit); expect(location.path()).toEqual('/one'); expect(fixture.nativeElement).toHaveText('route'); }), ));
{ "end_byte": 3719, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_3725_13049
ribe('navigation', function () { it('should navigate to the current URL', fakeAsync(() => { TestBed.configureTestingModule({ providers: [provideRouter([], withRouterConfig({onSameUrlNavigation: 'reload'}))], }); const router = TestBed.inject(Router); router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'simple', component: SimpleCmp}, ]); const events: (NavigationStart | NavigationEnd)[] = []; router.events.subscribe((e) => onlyNavigationStartAndEnd(e) && events.push(e)); router.navigateByUrl('/simple'); tick(); router.navigateByUrl('/simple'); tick(); expectEvents(events, [ [NavigationStart, '/simple'], [NavigationEnd, '/simple'], [NavigationStart, '/simple'], [NavigationEnd, '/simple'], ]); })); it('should override default onSameUrlNavigation with extras', async () => { TestBed.configureTestingModule({ providers: [provideRouter([], withRouterConfig({onSameUrlNavigation: 'ignore'}))], }); const router = TestBed.inject(Router); router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'simple', component: SimpleCmp}, ]); const events: (NavigationStart | NavigationEnd)[] = []; router.events.subscribe((e) => onlyNavigationStartAndEnd(e) && events.push(e)); await router.navigateByUrl('/simple'); await router.navigateByUrl('/simple'); // By default, the second navigation is ignored expectEvents(events, [ [NavigationStart, '/simple'], [NavigationEnd, '/simple'], ]); await router.navigateByUrl('/simple', {onSameUrlNavigation: 'reload'}); // We overrode the `onSameUrlNavigation` value. This navigation should be processed. expectEvents(events, [ [NavigationStart, '/simple'], [NavigationEnd, '/simple'], [NavigationStart, '/simple'], [NavigationEnd, '/simple'], ]); }); it('should override default onSameUrlNavigation with extras', async () => { TestBed.configureTestingModule({ providers: [provideRouter([], withRouterConfig({onSameUrlNavigation: 'reload'}))], }); const router = TestBed.inject(Router); router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'simple', component: SimpleCmp}, ]); const events: (NavigationStart | NavigationEnd)[] = []; router.events.subscribe((e) => onlyNavigationStartAndEnd(e) && events.push(e)); await router.navigateByUrl('/simple'); await router.navigateByUrl('/simple'); expectEvents(events, [ [NavigationStart, '/simple'], [NavigationEnd, '/simple'], [NavigationStart, '/simple'], [NavigationEnd, '/simple'], ]); events.length = 0; await router.navigateByUrl('/simple', {onSameUrlNavigation: 'ignore'}); expectEvents(events, []); }); it('should set transient navigation info', async () => { let observedInfo: unknown; const router = TestBed.inject(Router); router.resetConfig([ { path: 'simple', component: SimpleCmp, canActivate: [ () => { observedInfo = coreInject(Router).getCurrentNavigation()?.extras?.info; return true; }, ], }, ]); await router.navigateByUrl('/simple', {info: 'navigation info'}); expect(observedInfo).toEqual('navigation info'); }); it('should set transient navigation info for routerlink', async () => { let observedInfo: unknown; const router = TestBed.inject(Router); router.resetConfig([ { path: 'simple', component: SimpleCmp, canActivate: [ () => { observedInfo = coreInject(Router).getCurrentNavigation()?.extras?.info; return true; }, ], }, ]); @Component({ standalone: true, imports: [RouterLink], template: `<a #simpleLink [routerLink]="'/simple'" [info]="simpleLink"></a>`, }) class App {} const fixture = TestBed.createComponent(App); fixture.autoDetectChanges(); const anchor = fixture.nativeElement.querySelector('a'); anchor.click(); await fixture.whenStable(); // An example use-case might be to pass the clicked link along with the navigation // information expect(observedInfo).toBeInstanceOf(HTMLAnchorElement); }); it('should make transient navigation info available in redirect', async () => { let observedInfo: unknown; const router = TestBed.inject(Router); router.resetConfig([ { path: 'redirect', component: SimpleCmp, canActivate: [() => coreInject(Router).parseUrl('/simple')], }, { path: 'simple', component: SimpleCmp, canActivate: [ () => { observedInfo = coreInject(Router).getCurrentNavigation()?.extras?.info; return true; }, ], }, ]); await router.navigateByUrl('/redirect', {info: 'navigation info'}); expect(observedInfo).toBe('navigation info'); expect(router.url).toEqual('/simple'); }); it('should ignore empty paths in relative links', fakeAsync( inject([Router], (router: Router) => { router.resetConfig([ { path: 'foo', children: [{path: 'bar', children: [{path: '', component: RelativeLinkCmp}]}], }, ]); const fixture = createRoot(router, RootCmp); router.navigateByUrl('/foo/bar'); advance(fixture); const link = fixture.nativeElement.querySelector('a'); expect(link.getAttribute('href')).toEqual('/foo/simple'); }), )); it('should set the restoredState to null when executing imperative navigations', fakeAsync( inject([Router], (router: Router) => { router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'simple', component: SimpleCmp}, ]); const fixture = createRoot(router, RootCmp); let event: NavigationStart; router.events.subscribe((e) => { if (e instanceof NavigationStart) { event = e; } }); router.navigateByUrl('/simple'); tick(); expect(event!.navigationTrigger).toEqual('imperative'); expect(event!.restoredState).toEqual(null); }), )); it('should set history.state if passed using imperative navigation', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'simple', component: SimpleCmp}, ]); const fixture = createRoot(router, RootCmp); let navigation: Navigation = null!; router.events.subscribe((e) => { if (e instanceof NavigationStart) { navigation = router.getCurrentNavigation()!; } }); router.navigateByUrl('/simple', {state: {foo: 'bar'}}); tick(); const state = location.getState() as any; expect(state.foo).toBe('bar'); expect(state).toEqual({foo: 'bar', navigationId: 2}); expect(navigation.extras.state).toBeDefined(); expect(navigation.extras.state).toEqual({foo: 'bar'}); }), )); it('should set history.state when navigation with browser back and forward', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'simple', component: SimpleCmp}, ]); const fixture = createRoot(router, RootCmp); let navigation: Navigation = null!; router.events.subscribe((e) => { if (e instanceof NavigationStart) { navigation = <Navigation>router.getCurrentNavigation()!; } }); let state: Record<string, string> = {foo: 'bar'}; router.navigateByUrl('/simple', {state}); tick(); location.back(); tick(); location.forward(); tick(); expect(navigation.extras.state).toBeDefined(); expect(navigation.extras.state).toEqual(state); // Manually set state rather than using navigate() state = {bar: 'foo'}; location.replaceState(location.path(), '', state); location.back(); tick(); location.forward(); tick(); expect(navigation.extras.state).toBeDefined(); expect(navigation.extras.state).toEqual(state); }), ));
{ "end_byte": 13049, "start_byte": 3725, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_13057_17770
should navigate correctly when using `Location#historyGo', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { router.resetConfig([ {path: 'first', component: SimpleCmp}, {path: 'second', component: SimpleCmp}, ]); createRoot(router, RootCmp); router.navigateByUrl('/first'); tick(); router.navigateByUrl('/second'); tick(); expect(router.url).toEqual('/second'); location.historyGo(-1); tick(); expect(router.url).toEqual('/first'); location.historyGo(1); tick(); expect(router.url).toEqual('/second'); location.historyGo(-100); tick(); expect(router.url).toEqual('/second'); location.historyGo(100); tick(); expect(router.url).toEqual('/second'); location.historyGo(0); tick(); expect(router.url).toEqual('/second'); location.historyGo(); tick(); expect(router.url).toEqual('/second'); }), )); it('should not error if state is not {[key: string]: any}', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'simple', component: SimpleCmp}, ]); const fixture = createRoot(router, RootCmp); let navigation: Navigation = null!; router.events.subscribe((e) => { if (e instanceof NavigationStart) { navigation = <Navigation>router.getCurrentNavigation()!; } }); location.replaceState('', '', 42); router.navigateByUrl('/simple'); tick(); location.back(); advance(fixture); // Angular does not support restoring state to the primitive. expect(navigation.extras.state).toEqual(undefined); expect(location.getState()).toEqual({navigationId: 3}); }), )); it('should not pollute browser history when replaceUrl is set to true', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'a', component: SimpleCmp}, {path: 'b', component: SimpleCmp}, ]); createRoot(router, RootCmp); const replaceSpy = spyOn(location, 'replaceState'); router.navigateByUrl('/a', {replaceUrl: true}); router.navigateByUrl('/b', {replaceUrl: true}); tick(); expect(replaceSpy.calls.count()).toEqual(1); }), )); it('should skip navigation if another navigation is already scheduled', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'a', component: SimpleCmp}, {path: 'b', component: SimpleCmp}, ]); const fixture = createRoot(router, RootCmp); router.navigate(['/a'], { queryParams: {a: true}, queryParamsHandling: 'merge', replaceUrl: true, }); router.navigate(['/b'], { queryParams: {b: true}, queryParamsHandling: 'merge', replaceUrl: true, }); tick(); /** * Why do we have '/b?b=true' and not '/b?a=true&b=true'? * * This is because the router has the right to stop a navigation mid-flight if another * navigation has been already scheduled. This is why we can use a top-level guard * to perform redirects. Calling `navigate` in such a guard will stop the navigation, and * the components won't be instantiated. * * This is a fundamental property of the router: it only cares about its latest state. * * This means that components should only map params to something else, not reduce them. * In other words, the following component is asking for trouble: * * ``` * class MyComponent { * constructor(a: ActivatedRoute) { * a.params.scan(...) * } * } * ``` * * This also means "queryParamsHandling: 'merge'" should only be used to merge with * long-living query parameters (e.g., debug). */ expect(router.url).toEqual('/b?b=true'); }), )); });
{ "end_byte": 17770, "start_byte": 13057, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_17776_27225
ribe('should execute navigations serially', () => { let log: Array<string | Params> = []; 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<boolean>((r) => (res = r)); setTimeout(() => { log.push('trueIn2Seconds-end'); res(true); }, 2000); return p; }, }, ], }); }); describe('route activation', () => { @Component({ template: '<router-outlet></router-outlet>', standalone: false, }) class Parent { constructor(route: ActivatedRoute) { route.params.subscribe((s: Params) => { log.push(s); }); } } @Component({ template: ` <router-outlet (deactivate)="logDeactivate('primary')"></router-outlet> <router-outlet name="first" (deactivate)="logDeactivate('first')"></router-outlet> <router-outlet name="second" (deactivate)="logDeactivate('second')"></router-outlet> `, standalone: false, }) class NamedOutletHost { logDeactivate(route: string) { log.push(route + ' deactivate'); } } @Component({ template: 'child1', standalone: false, }) class Child1 { constructor() { log.push('child1 constructor'); } ngOnDestroy() { log.push('child1 destroy'); } } @Component({ template: 'child2', standalone: false, }) class Child2 { constructor() { log.push('child2 constructor'); } ngOnDestroy() { log.push('child2 destroy'); } } @Component({ template: 'child3', standalone: false, }) class Child3 { constructor() { log.push('child3 constructor'); } ngOnDestroy() { log.push('child3 destroy'); } } @NgModule({ declarations: [Parent, NamedOutletHost, Child1, Child2, Child3], imports: [RouterModule.forRoot([])], }) class TestModule {} it('should advance the parent route after deactivating its children', fakeAsync(() => { TestBed.configureTestingModule({imports: [TestModule]}); const router = TestBed.inject(Router); const location = TestBed.inject(Location); const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'parent/:id', component: Parent, children: [ {path: 'child1', component: Child1}, {path: 'child2', component: Child2}, ], }, ]); router.navigateByUrl('/parent/1/child1'); advance(fixture); router.navigateByUrl('/parent/2/child2'); advance(fixture); expect(location.path()).toEqual('/parent/2/child2'); expect(log).toEqual([ {id: '1'}, 'child1 constructor', 'child1 destroy', {id: '2'}, 'child2 constructor', ]); })); it('should deactivate outlet children with componentless parent', fakeAsync(() => { TestBed.configureTestingModule({imports: [TestModule]}); const router = TestBed.inject(Router); const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'named-outlets', component: NamedOutletHost, children: [ { path: 'home', children: [ {path: '', component: Child1, outlet: 'first'}, {path: '', component: Child2, outlet: 'second'}, {path: 'primary', component: Child3}, ], }, { path: 'about', children: [ {path: '', component: Child1, outlet: 'first'}, {path: '', component: Child2, outlet: 'second'}, ], }, ], }, { path: 'other', component: Parent, }, ]); router.navigateByUrl('/named-outlets/home/primary'); advance(fixture); expect(log).toEqual([ 'child3 constructor', // primary outlet always first 'child1 constructor', 'child2 constructor', ]); log.length = 0; router.navigateByUrl('/named-outlets/about'); advance(fixture); expect(log).toEqual([ 'child3 destroy', 'primary deactivate', 'child1 destroy', 'first deactivate', 'child2 destroy', 'second deactivate', 'child1 constructor', 'child2 constructor', ]); log.length = 0; router.navigateByUrl('/other'); advance(fixture); expect(log).toEqual([ 'child1 destroy', 'first deactivate', 'child2 destroy', 'second deactivate', // route param subscription from 'Parent' component {}, ]); })); it('should work between aux outlets under two levels of empty path parents', fakeAsync(() => { TestBed.configureTestingModule({imports: [TestModule]}); const router = TestBed.inject(Router); router.resetConfig([ { path: '', children: [ { path: '', component: NamedOutletHost, children: [ {path: 'one', component: Child1, outlet: 'first'}, {path: 'two', component: Child2, outlet: 'first'}, ], }, ], }, ]); const fixture = createRoot(router, RootCmp); router.navigateByUrl('/(first:one)'); advance(fixture); expect(log).toEqual(['child1 constructor']); log.length = 0; router.navigateByUrl('/(first:two)'); advance(fixture); expect(log).toEqual(['child1 destroy', 'first deactivate', 'child2 constructor']); })); }); it('should not wait for prior navigations to start a new navigation', fakeAsync( inject([Router, Location], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'a', component: SimpleCmp, canActivate: ['trueRightAway', 'trueIn2Seconds']}, {path: 'b', component: SimpleCmp, canActivate: ['trueRightAway', 'trueIn2Seconds']}, ]); router.navigateByUrl('/a'); tick(100); fixture.detectChanges(); router.navigateByUrl('/b'); tick(100); // 200 fixture.detectChanges(); expect(log).toEqual([ 'trueRightAway', 'trueIn2Seconds-start', 'trueRightAway', 'trueIn2Seconds-start', ]); tick(2000); // 2200 fixture.detectChanges(); expect(log).toEqual([ 'trueRightAway', 'trueIn2Seconds-start', 'trueRightAway', 'trueIn2Seconds-start', 'trueIn2Seconds-end', 'trueIn2Seconds-end', ]); }), )); }); it('Should work inside ChangeDetectionStrategy.OnPush components', fakeAsync(() => { @Component({ selector: 'root-cmp', template: `<router-outlet></router-outlet>`, changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class OnPushOutlet {} @Component({ selector: 'need-cd', template: `{{'it works!'}}`, standalone: false, }) class NeedCdCmp {} @NgModule({ declarations: [OnPushOutlet, NeedCdCmp], imports: [RouterModule.forRoot([])], }) class TestModule {} TestBed.configureTestingModule({imports: [TestModule]}); const router: Router = TestBed.inject(Router); const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'on', component: OnPushOutlet, children: [ { path: 'push', component: NeedCdCmp, }, ], }, ]); advance(fixture); router.navigateByUrl('on'); advance(fixture); router.navigateByUrl('on/push'); advance(fixture); expect(fixture.nativeElement).toHaveText('it works!'); }));
{ "end_byte": 27225, "start_byte": 17776, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_27231_33027
should not error when no url left and no children are matching', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [{path: 'simple', component: SimpleCmp}], }, ]); router.navigateByUrl('/team/33/simple'); advance(fixture); expect(location.path()).toEqual('/team/33/simple'); expect(fixture.nativeElement).toHaveText('team 33 [ simple, right: ]'); router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/33'); expect(fixture.nativeElement).toHaveText('team 33 [ , right: ]'); }), )); it('should work when an outlet is in an ngIf', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'child', component: OutletInNgIf, children: [{path: 'simple', component: SimpleCmp}], }, ]); router.navigateByUrl('/child/simple'); advance(fixture); expect(location.path()).toEqual('/child/simple'); }), )); it('should work when an outlet is added/removed', fakeAsync(() => { @Component({ selector: 'someRoot', template: `[<div *ngIf="cond"><router-outlet></router-outlet></div>]`, standalone: false, }) class RootCmpWithLink { cond: boolean = true; } TestBed.configureTestingModule({declarations: [RootCmpWithLink]}); const router: Router = TestBed.inject(Router); const fixture = createRoot(router, RootCmpWithLink); router.resetConfig([ {path: 'simple', component: SimpleCmp}, {path: 'blank', component: BlankCmp}, ]); router.navigateByUrl('/simple'); advance(fixture); expect(fixture.nativeElement).toHaveText('[simple]'); fixture.componentInstance.cond = false; advance(fixture); expect(fixture.nativeElement).toHaveText('[]'); fixture.componentInstance.cond = true; advance(fixture); expect(fixture.nativeElement).toHaveText('[simple]'); })); it('should update location when navigating', fakeAsync(() => { @Component({ template: `record`, standalone: false, }) class RecordLocationCmp { private storedPath: string; constructor(loc: Location) { this.storedPath = loc.path(); } } @NgModule({declarations: [RecordLocationCmp]}) class TestModule {} TestBed.configureTestingModule({imports: [TestModule]}); const router = TestBed.inject(Router); const location = TestBed.inject(Location); const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'record/:id', component: RecordLocationCmp}]); router.navigateByUrl('/record/22'); advance(fixture); const c = fixture.debugElement.children[1].componentInstance; expect(location.path()).toEqual('/record/22'); expect(c.storedPath).toEqual('/record/22'); router.navigateByUrl('/record/33'); advance(fixture); expect(location.path()).toEqual('/record/33'); })); it('should skip location update when using NavigationExtras.skipLocationChange with navigateByUrl', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = TestBed.createComponent(RootCmp); advance(fixture); router.resetConfig([{path: 'team/:id', component: TeamCmp}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]'); router.navigateByUrl('/team/33', {skipLocationChange: true}); advance(fixture); expect(location.path()).toEqual('/team/22'); expect(fixture.nativeElement).toHaveText('team 33 [ , right: ]'); }), )); it('should skip location update when using NavigationExtras.skipLocationChange with navigate', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = TestBed.createComponent(RootCmp); advance(fixture); router.resetConfig([{path: 'team/:id', component: TeamCmp}]); router.navigate(['/team/22']); advance(fixture); expect(location.path()).toEqual('/team/22'); expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]'); router.navigate(['/team/33'], {skipLocationChange: true}); advance(fixture); expect(location.path()).toEqual('/team/22'); expect(fixture.nativeElement).toHaveText('team 33 [ , right: ]'); }), )); it('should navigate after navigation with skipLocationChange', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = TestBed.createComponent(RootCmpWithNamedOutlet); advance(fixture); router.resetConfig([{path: 'show', outlet: 'main', component: SimpleCmp}]); router.navigate([{outlets: {main: 'show'}}], {skipLocationChange: true}); advance(fixture); expect(location.path()).toEqual(''); expect(fixture.nativeElement).toHaveText('main [simple]'); router.navigate([{outlets: {main: null}}], {skipLocationChange: true}); advance(fixture); expect(location.path()).toEqual(''); expect(fixture.nativeElement).toHaveText('main []'); }), ));
{ "end_byte": 33027, "start_byte": 27231, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_33033_42989
ribe('"eager" urlUpdateStrategy', () => { @Injectable() class AuthGuard { canActivateResult = true; canActivate() { return this.canActivateResult; } } @Injectable() class DelayedGuard { canActivate() { return of('').pipe(delay(1000), mapTo(true)); } } beforeEach(() => { 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, ], }); }); describe('urlUpdateStrategy: eager', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [provideRouter([], withRouterConfig({urlUpdateStrategy: 'eager'}))], }); }); it('should eagerly update the URL', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = TestBed.createComponent(RootCmp); advance(fixture); router.resetConfig([{path: 'team/:id', component: TeamCmp}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]'); router.events.subscribe((e) => { if (!(e instanceof GuardsCheckStart)) { return; } expect(location.path()).toEqual('/team/33'); expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]'); return of(null); }); router.navigateByUrl('/team/33'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 33 [ , right: ]'); }), )); it('should eagerly update the URL', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = TestBed.createComponent(RootCmp); advance(fixture); router.resetConfig([ {path: 'team/:id', component: SimpleCmp, canActivate: ['authGuardFail']}, {path: 'login', component: AbsoluteSimpleLinkCmp}, ]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); // Redirects to /login advance(fixture, 1); expect(location.path()).toEqual('/login'); // Perform the same logic again, and it should produce the same result router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); // Redirects to /login advance(fixture, 1); expect(location.path()).toEqual('/login'); }), )); it('should eagerly update URL after redirects are applied', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = TestBed.createComponent(RootCmp); advance(fixture); router.resetConfig([{path: 'team/:id', component: TeamCmp}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]'); let urlAtNavStart = ''; let urlAtRoutesRecognized = ''; router.events.subscribe((e) => { if (e instanceof NavigationStart) { urlAtNavStart = location.path(); } if (e instanceof RoutesRecognized) { urlAtRoutesRecognized = location.path(); } }); router.navigateByUrl('/team/33'); advance(fixture); expect(urlAtNavStart).toBe('/team/22'); expect(urlAtRoutesRecognized).toBe('/team/33'); expect(fixture.nativeElement).toHaveText('team 33 [ , right: ]'); }), )); it('should set `state`', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'simple', component: SimpleCmp}, ]); const fixture = createRoot(router, RootCmp); let navigation: Navigation = null!; router.events.subscribe((e) => { if (e instanceof NavigationStart) { navigation = router.getCurrentNavigation()!; } }); router.navigateByUrl('/simple', {state: {foo: 'bar'}}); tick(); const state = location.getState() as any; expect(state).toEqual({foo: 'bar', navigationId: 2}); expect(navigation.extras.state).toBeDefined(); expect(navigation.extras.state).toEqual({foo: 'bar'}); }), )); it('can renavigate to rejected URL', fakeAsync(() => { const router = TestBed.inject(Router); const canActivate = TestBed.inject(AuthGuard); const location = TestBed.inject(Location); router.resetConfig([ {path: '', component: BlankCmp}, { path: 'simple', component: SimpleCmp, canActivate: [() => coreInject(AuthGuard).canActivate()], }, ]); const fixture = createRoot(router, RootCmp); // Try to navigate to /simple but guard rejects canActivate.canActivateResult = false; router.navigateByUrl('/simple'); advance(fixture); expect(location.path()).toEqual(''); expect(fixture.nativeElement.innerHTML).not.toContain('simple'); // Renavigate to /simple without guard rejection, should succeed. canActivate.canActivateResult = true; router.navigateByUrl('/simple'); advance(fixture); expect(location.path()).toEqual('/simple'); expect(fixture.nativeElement.innerHTML).toContain('simple'); })); it('can renavigate to same URL during in-flight navigation', fakeAsync(() => { const router = TestBed.inject(Router); const location = TestBed.inject(Location); router.resetConfig([ {path: '', component: BlankCmp}, { path: 'simple', component: SimpleCmp, canActivate: [() => coreInject(DelayedGuard).canActivate()], }, ]); const fixture = createRoot(router, RootCmp); // Start navigating to /simple, but do not flush the guard delay router.navigateByUrl('/simple'); tick(); // eager update strategy so URL is already updated. expect(location.path()).toEqual('/simple'); expect(fixture.nativeElement.innerHTML).not.toContain('simple'); // Start an additional navigation to /simple and ensure at least one of those succeeds. // It's not super important which one gets processed, but in the past, the router would // cancel the in-flight one and not process the new one. router.navigateByUrl('/simple'); tick(1000); expect(location.path()).toEqual('/simple'); expect(fixture.nativeElement.innerHTML).toContain('simple'); })); }); }); it('should navigate back and forward', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: 'simple', component: SimpleCmp}, {path: 'user/:name', component: UserCmp}, ], }, ]); let event: NavigationStart; router.events.subscribe((e) => { if (e instanceof NavigationStart) { event = e; } }); router.navigateByUrl('/team/33/simple'); advance(fixture); expect(location.path()).toEqual('/team/33/simple'); const simpleNavStart = event!; router.navigateByUrl('/team/22/user/victor'); advance(fixture); const userVictorNavStart = event!; location.back(); advance(fixture); expect(location.path()).toEqual('/team/33/simple'); expect(event!.navigationTrigger).toEqual('popstate'); expect(event!.restoredState!.navigationId).toEqual(simpleNavStart.id); location.forward(); advance(fixture); expect(location.path()).toEqual('/team/22/user/victor'); expect(event!.navigationTrigger).toEqual('popstate'); expect(event!.restoredState!.navigationId).toEqual(userVictorNavStart.id); }), )); it('should navigate to the same url when config changes', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'a', component: SimpleCmp}]); router.navigate(['/a']); advance(fixture); expect(location.path()).toEqual('/a'); expect(fixture.nativeElement).toHaveText('simple'); router.resetConfig([{path: 'a', component: RouteCmp}]); router.navigate(['/a']); advance(fixture); expect(location.path()).toEqual('/a'); expect(fixture.nativeElement).toHaveText('route'); }), ));
{ "end_byte": 42989, "start_byte": 33033, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_42995_52190
should navigate when locations changes', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [{path: 'user/:name', component: UserCmp}], }, ]); const recordedEvents: (NavigationStart | NavigationEnd)[] = []; router.events.forEach((e) => onlyNavigationStartAndEnd(e) && recordedEvents.push(e)); router.navigateByUrl('/team/22/user/victor'); advance(fixture); location.go('/team/22/user/fedor'); location.historyGo(0); advance(fixture); location.go('/team/22/user/fedor'); location.historyGo(0); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ user fedor, right: ]'); expectEvents(recordedEvents, [ [NavigationStart, '/team/22/user/victor'], [NavigationEnd, '/team/22/user/victor'], [NavigationStart, '/team/22/user/fedor'], [NavigationEnd, '/team/22/user/fedor'], ]); }), )); it('should update the location when the matched route does not change', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: '**', component: CollectParamsCmp}]); router.navigateByUrl('/one/two'); advance(fixture); const cmp = fixture.debugElement.children[1].componentInstance; expect(location.path()).toEqual('/one/two'); expect(fixture.nativeElement).toHaveText('collect-params'); expect(cmp.recordedUrls()).toEqual(['one/two']); router.navigateByUrl('/three/four'); advance(fixture); expect(location.path()).toEqual('/three/four'); expect(fixture.nativeElement).toHaveText('collect-params'); expect(cmp.recordedUrls()).toEqual(['one/two', 'three/four']); }), )); describe('duplicate in-flight navigations', () => { @Injectable() class RedirectingGuard { skipLocationChange = false; constructor(private router: Router) {} canActivate() { this.router.navigate(['/simple'], {skipLocationChange: this.skipLocationChange}); return false; } } 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, ], }); }); it('should reset location if a navigation by location is successful', fakeAsync(() => { const router = TestBed.inject(Router); const location = TestBed.inject(Location); const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'simple', component: SimpleCmp, canActivate: ['in1Second']}]); // Trigger two location changes to the same URL. // Because of the guard the order will look as follows: // - location change 'simple' // - start processing the change, start a guard // - location change 'simple' // - the first location change gets canceled, the URL gets reset to '/' // - the second location change gets finished, the URL should be reset to '/simple' location.go('/simple'); location.historyGo(0); location.historyGo(0); tick(2000); advance(fixture); expect(location.path()).toEqual('/simple'); })); it('should skip duplicate location events', fakeAsync(() => { const router = TestBed.inject(Router); const location = TestBed.inject(Location); const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'blocked', component: BlankCmp, canActivate: [() => coreInject(RedirectingGuard).canActivate()], }, {path: 'simple', component: SimpleCmp}, ]); router.navigateByUrl('/simple'); advance(fixture); location.go('/blocked'); location.historyGo(0); advance(fixture); expect(fixture.nativeElement.innerHTML).toContain('simple'); })); it('should not cause URL thrashing', async () => { TestBed.configureTestingModule({ providers: [provideRouter([], withRouterConfig({urlUpdateStrategy: 'eager'}))], }); const router = TestBed.inject(Router); const location = TestBed.inject(Location); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); router.resetConfig([ {path: 'home', component: SimpleCmp}, { path: 'blocked', component: BlankCmp, canActivate: [() => coreInject(RedirectingGuard).canActivate()], }, {path: 'simple', component: SimpleCmp}, ]); await router.navigateByUrl('/home'); const urlChanges: string[] = []; location.onUrlChange((change) => { urlChanges.push(change); }); await router.navigateByUrl('/blocked'); await fixture.whenStable(); expect(fixture.nativeElement.innerHTML).toContain('simple'); // We do not want the URL to flicker to `/home` between the /blocked and /simple routes expect(urlChanges).toEqual(['/blocked', '/simple']); }); it('can render a 404 page without changing the URL', fakeAsync(() => { TestBed.configureTestingModule({ providers: [provideRouter([], withRouterConfig({urlUpdateStrategy: 'eager'}))], }); const router = TestBed.inject(Router); TestBed.inject(RedirectingGuard).skipLocationChange = true; const location = TestBed.inject(Location); const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'home', component: SimpleCmp}, { path: 'blocked', component: BlankCmp, canActivate: [() => coreInject(RedirectingGuard).canActivate()], }, {path: 'simple', redirectTo: '404'}, {path: '404', component: SimpleCmp}, ]); router.navigateByUrl('/home'); advance(fixture); location.go('/blocked'); location.historyGo(0); advance(fixture); expect(location.path()).toEqual('/blocked'); expect(fixture.nativeElement.innerHTML).toContain('simple'); })); 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']}, ]); router.events.subscribe((e) => { if (e instanceof NavigationStart) { if (e.url === '/one') { router.navigateByUrl('two'); } router.events.subscribe((e) => { if (e instanceof GuardsCheckEnd) { expect(router.getCurrentNavigation()?.extractedUrl.toString()).toEqual('/two'); expect(router.getCurrentNavigation()?.extras).toBeDefined(); } }); } }); router.navigateByUrl('one'); tick(1000); })); }); it('should support secondary routes', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'simple', component: SimpleCmp, outlet: 'right'}, ], }, ]); router.navigateByUrl('/team/22/(user/victor//right:simple)'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ user victor, right: simple ]'); }), )); it('should support secondary routes in separate commands', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'simple', component: SimpleCmp, outlet: 'right'}, ], }, ]); router.navigateByUrl('/team/22/user/victor'); advance(fixture); router.navigate(['team/22', {outlets: {right: 'simple'}}]); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ user victor, right: simple ]'); }), ));
{ "end_byte": 52190, "start_byte": 42995, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_52196_60912
should support secondary routes as child of empty path parent', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: '', component: TeamCmp, children: [{path: 'simple', component: SimpleCmp, outlet: 'right'}], }, ]); router.navigateByUrl('/(right:simple)'); advance(fixture); expect(fixture.nativeElement).toHaveText('team [ , right: simple ]'); }), )); it('should deactivate outlets', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'simple', component: SimpleCmp, outlet: 'right'}, ], }, ]); router.navigateByUrl('/team/22/(user/victor//right:simple)'); advance(fixture); router.navigateByUrl('/team/22/user/victor'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ user victor, right: ]'); }), )); it('should deactivate nested outlets', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'simple', component: SimpleCmp, outlet: 'right'}, ], }, {path: '', component: BlankCmp}, ]); router.navigateByUrl('/team/22/(user/victor//right:simple)'); advance(fixture); router.navigateByUrl('/'); advance(fixture); expect(fixture.nativeElement).toHaveText(''); }), )); it('should set query params and fragment', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'query', component: QueryParamsAndFragmentCmp}]); router.navigateByUrl('/query?name=1#fragment1'); advance(fixture); expect(fixture.nativeElement).toHaveText('query: 1 fragment: fragment1'); router.navigateByUrl('/query?name=2#fragment2'); advance(fixture); expect(fixture.nativeElement).toHaveText('query: 2 fragment: fragment2'); }), )); it('should handle empty or missing fragments', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'query', component: QueryParamsAndFragmentCmp}]); router.navigateByUrl('/query#'); advance(fixture); expect(fixture.nativeElement).toHaveText('query: fragment: '); router.navigateByUrl('/query'); advance(fixture); expect(fixture.nativeElement).toHaveText('query: fragment: null'); }), )); it('should ignore null and undefined query params', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'query', component: EmptyQueryParamsCmp}]); router.navigate(['query'], {queryParams: {name: 1, age: null, page: undefined}}); advance(fixture); const cmp = fixture.debugElement.children[1].componentInstance; expect(cmp.recordedParams).toEqual([{name: '1'}]); }), )); it('should throw an error when one of the commands is null/undefined', fakeAsync( inject([Router], (router: Router) => { createRoot(router, RootCmp); router.resetConfig([{path: 'query', component: EmptyQueryParamsCmp}]); expect(() => router.navigate([undefined, 'query'])).toThrowError( /The requested path contains undefined segment at index 0/, ); }), )); it('should push params only when they change', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [{path: 'user/:name', component: UserCmp}], }, ]); router.navigateByUrl('/team/22/user/victor'); advance(fixture); const team = fixture.debugElement.children[1].componentInstance; const user = fixture.debugElement.children[1].children[1].componentInstance; expect(team.recordedParams).toEqual([{id: '22'}]); expect(team.snapshotParams).toEqual([{id: '22'}]); expect(user.recordedParams).toEqual([{name: 'victor'}]); expect(user.snapshotParams).toEqual([{name: 'victor'}]); router.navigateByUrl('/team/22/user/fedor'); advance(fixture); expect(team.recordedParams).toEqual([{id: '22'}]); expect(team.snapshotParams).toEqual([{id: '22'}]); expect(user.recordedParams).toEqual([{name: 'victor'}, {name: 'fedor'}]); expect(user.snapshotParams).toEqual([{name: 'victor'}, {name: 'fedor'}]); }), )); it('should work when navigating to /', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: '', pathMatch: 'full', component: SimpleCmp}, {path: 'user/:name', component: UserCmp}, ]); router.navigateByUrl('/user/victor'); advance(fixture); expect(fixture.nativeElement).toHaveText('user victor'); router.navigateByUrl('/'); advance(fixture); expect(fixture.nativeElement).toHaveText('simple'); }), )); it('should cancel in-flight navigations', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'user/:name', component: UserCmp}]); const recordedEvents: Event[] = []; router.events.forEach((e) => recordedEvents.push(e)); router.navigateByUrl('/user/init'); advance(fixture); const user = fixture.debugElement.children[1].componentInstance; let r1: any, r2: any; router.navigateByUrl('/user/victor').then((_) => (r1 = _)); router.navigateByUrl('/user/fedor').then((_) => (r2 = _)); advance(fixture); expect(r1).toEqual(false); // returns false because it was canceled expect(r2).toEqual(true); // returns true because it was successful expect(fixture.nativeElement).toHaveText('user fedor'); expect(user.recordedParams).toEqual([{name: 'init'}, {name: 'fedor'}]); expectEvents(recordedEvents, [ [NavigationStart, '/user/init'], [RoutesRecognized, '/user/init'], [GuardsCheckStart, '/user/init'], [ChildActivationStart], [ActivationStart], [GuardsCheckEnd, '/user/init'], [ResolveStart, '/user/init'], [ResolveEnd, '/user/init'], [ActivationEnd], [ChildActivationEnd], [NavigationEnd, '/user/init'], [NavigationStart, '/user/victor'], [NavigationCancel, '/user/victor'], [NavigationStart, '/user/fedor'], [RoutesRecognized, '/user/fedor'], [GuardsCheckStart, '/user/fedor'], [ChildActivationStart], [ActivationStart], [GuardsCheckEnd, '/user/fedor'], [ResolveStart, '/user/fedor'], [ResolveEnd, '/user/fedor'], [ActivationEnd], [ChildActivationEnd], [NavigationEnd, '/user/fedor'], ]); }), )); it('should properly set currentNavigation when cancelling in-flight navigations', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'user/:name', component: UserCmp}]); router.navigateByUrl('/user/init'); advance(fixture); router.navigateByUrl('/user/victor'); expect(router.getCurrentNavigation()).not.toBe(null); router.navigateByUrl('/user/fedor'); // Due to https://github.com/angular/angular/issues/29389, this would be `false` // when running a second navigation. expect(router.getCurrentNavigation()).not.toBe(null); advance(fixture); expect(router.getCurrentNavigation()).toBe(null); expect(fixture.nativeElement).toHaveText('user fedor'); }), ));
{ "end_byte": 60912, "start_byte": 52196, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_60918_71165
should handle failed navigations gracefully', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'user/:name', component: UserCmp}]); const recordedEvents: Event[] = []; router.events.forEach((e) => recordedEvents.push(e)); let e: any; router.navigateByUrl('/invalid').catch((_) => (e = _)); advance(fixture); expect(e.message).toContain('Cannot match any routes'); router.navigateByUrl('/user/fedor'); advance(fixture); expect(fixture.nativeElement).toHaveText('user fedor'); expectEvents(recordedEvents, [ [NavigationStart, '/invalid'], [NavigationError, '/invalid'], [NavigationStart, '/user/fedor'], [RoutesRecognized, '/user/fedor'], [GuardsCheckStart, '/user/fedor'], [ChildActivationStart], [ActivationStart], [GuardsCheckEnd, '/user/fedor'], [ResolveStart, '/user/fedor'], [ResolveEnd, '/user/fedor'], [ActivationEnd], [ChildActivationEnd], [NavigationEnd, '/user/fedor'], ]); }), )); it('should be able to provide an error handler with DI dependencies', async () => { @Injectable({providedIn: 'root'}) class Handler { handlerCalled = false; } TestBed.configureTestingModule({ providers: [ provideRouter( [ { path: 'throw', canMatch: [ () => { throw new Error(''); }, ], component: BlankCmp, }, ], withRouterConfig({resolveNavigationPromiseOnError: true}), withNavigationErrorHandler(() => (coreInject(Handler).handlerCalled = true)), ), ], }); const router = TestBed.inject(Router); await router.navigateByUrl('/throw'); expect(TestBed.inject(Handler).handlerCalled).toBeTrue(); }); it('can redirect from error handler with RouterModule.forRoot', async () => { TestBed.configureTestingModule({ imports: [ RouterModule.forRoot( [ { path: 'throw', canMatch: [ () => { throw new Error(''); }, ], component: BlankCmp, }, {path: 'error', component: BlankCmp}, ], { resolveNavigationPromiseOnError: true, errorHandler: () => new RedirectCommand(coreInject(Router).parseUrl('/error')), }, ), ], }); const router = TestBed.inject(Router); let emitNavigationError = false; let emitNavigationCancelWithRedirect = false; router.events.subscribe((e) => { if (e instanceof NavigationError) { emitNavigationError = true; } if (e instanceof NavigationCancel && e.code === NavigationCancellationCode.Redirect) { emitNavigationCancelWithRedirect = true; } }); await router.navigateByUrl('/throw'); expect(router.url).toEqual('/error'); expect(emitNavigationError).toBe(false); expect(emitNavigationCancelWithRedirect).toBe(true); }); it('can redirect from error handler', async () => { TestBed.configureTestingModule({ providers: [ provideRouter( [ { path: 'throw', canMatch: [ () => { throw new Error(''); }, ], component: BlankCmp, }, {path: 'error', component: BlankCmp}, ], withRouterConfig({resolveNavigationPromiseOnError: true}), withNavigationErrorHandler( () => new RedirectCommand(coreInject(Router).parseUrl('/error')), ), ), ], }); const router = TestBed.inject(Router); let emitNavigationError = false; let emitNavigationCancelWithRedirect = false; router.events.subscribe((e) => { if (e instanceof NavigationError) { emitNavigationError = true; } if (e instanceof NavigationCancel && e.code === NavigationCancellationCode.Redirect) { emitNavigationCancelWithRedirect = true; } }); await router.navigateByUrl('/throw'); expect(router.url).toEqual('/error'); expect(emitNavigationError).toBe(false); expect(emitNavigationCancelWithRedirect).toBe(true); }); it('should not break navigation if an error happens in NavigationErrorHandler', async () => { TestBed.configureTestingModule({ providers: [ provideRouter( [ { path: 'throw', canMatch: [ () => { throw new Error(''); }, ], component: BlankCmp, }, {path: '**', component: BlankCmp}, ], withRouterConfig({resolveNavigationPromiseOnError: true}), withNavigationErrorHandler(() => { throw new Error('e'); }), ), ], }); const router = TestBed.inject(Router); }); // Errors should behave the same for both deferred and eager URL update strategies (['deferred', 'eager'] as const).forEach((urlUpdateStrategy) => { it('should dispatch NavigationError after the url has been reset back', fakeAsync(() => { TestBed.configureTestingModule({ providers: [provideRouter([], withRouterConfig({urlUpdateStrategy}))], }); const router: Router = TestBed.inject(Router); const location = TestBed.inject(Location); const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'simple', component: SimpleCmp}, {path: 'throwing', component: ThrowingCmp}, ]); router.navigateByUrl('/simple'); advance(fixture); let routerUrlBeforeEmittingError = ''; let locationUrlBeforeEmittingError = ''; router.events.forEach((e) => { if (e instanceof NavigationError) { routerUrlBeforeEmittingError = router.url; locationUrlBeforeEmittingError = location.path(); } }); router.navigateByUrl('/throwing').catch(() => null); advance(fixture); expect(routerUrlBeforeEmittingError).toEqual('/simple'); expect(locationUrlBeforeEmittingError).toEqual('/simple'); })); it('can renavigate to throwing component', fakeAsync(() => { TestBed.configureTestingModule({ providers: [provideRouter([], withRouterConfig({urlUpdateStrategy: 'eager'}))], }); const router = TestBed.inject(Router); const location = TestBed.inject(Location); router.resetConfig([ {path: '', component: BlankCmp}, {path: 'throwing', component: ConditionalThrowingCmp}, ]); const fixture = createRoot(router, RootCmp); // Try navigating to a component which throws an error during activation. ConditionalThrowingCmp.throwError = true; expect(() => { router.navigateByUrl('/throwing'); advance(fixture); }).toThrow(); expect(location.path()).toEqual(''); expect(fixture.nativeElement.innerHTML).not.toContain('throwing'); // Ensure we can re-navigate to that same URL and succeed. ConditionalThrowingCmp.throwError = false; router.navigateByUrl('/throwing'); advance(fixture); expect(location.path()).toEqual('/throwing'); expect(fixture.nativeElement.innerHTML).toContain('throwing'); })); it('should reset the url with the right state when navigation errors', fakeAsync(() => { TestBed.configureTestingModule({ providers: [provideRouter([], withRouterConfig({urlUpdateStrategy}))], }); const router: Router = TestBed.inject(Router); const location = TestBed.inject(Location); const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'simple1', component: SimpleCmp}, {path: 'simple2', component: SimpleCmp}, {path: 'throwing', component: ThrowingCmp}, ]); let event: NavigationStart; router.events.subscribe((e) => { if (e instanceof NavigationStart) { event = e; } }); router.navigateByUrl('/simple1'); advance(fixture); const simple1NavStart = event!; router.navigateByUrl('/throwing').catch(() => null); advance(fixture); router.navigateByUrl('/simple2'); advance(fixture); location.back(); tick(); expect(event!.restoredState!.navigationId).toEqual(simple1NavStart.id); })); it('should not trigger another navigation when resetting the url back due to a NavigationError', fakeAsync(() => { TestBed.configureTestingModule({ providers: [provideRouter([], withRouterConfig({urlUpdateStrategy}))], }); const router = TestBed.inject(Router); router.onSameUrlNavigation = 'reload'; const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'simple', component: SimpleCmp}, {path: 'throwing', component: ThrowingCmp}, ]); const events: any[] = []; router.events.forEach((e: any) => { if (e instanceof NavigationStart) { events.push(e.url); } }); router.navigateByUrl('/simple'); advance(fixture); router.navigateByUrl('/throwing').catch(() => null); advance(fixture); // we do not trigger another navigation to /simple expect(events).toEqual(['/simple', '/throwing']); })); });
{ "end_byte": 71165, "start_byte": 60918, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_71171_79865
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); const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'simple', component: SimpleCmp}, { path: 'throwing', loadChildren: jasmine.createSpy('doesnotmatter'), canLoad: ['returnsFalse'], }, ]); router.navigateByUrl('/simple'); advance(fixture); let routerUrlBeforeEmittingError = ''; let locationUrlBeforeEmittingError = ''; router.events.forEach((e) => { if (e instanceof NavigationCancel) { expect(e.code).toBe(NavigationCancellationCode.GuardRejected); routerUrlBeforeEmittingError = router.url; locationUrlBeforeEmittingError = location.path(); } }); location.go('/throwing'); location.historyGo(0); advance(fixture); expect(routerUrlBeforeEmittingError).toEqual('/simple'); expect(locationUrlBeforeEmittingError).toEqual('/simple'); })); it('should recover from malformed uri errors', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { router.resetConfig([{path: 'simple', component: SimpleCmp}]); const fixture = createRoot(router, RootCmp); router.navigateByUrl('/invalid/url%with%percent'); advance(fixture); expect(location.path()).toEqual(''); }), )); it('should not swallow errors', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'simple', component: SimpleCmp}]); router.navigateByUrl('/invalid'); expect(() => advance(fixture)).toThrow(); router.navigateByUrl('/invalid2'); expect(() => advance(fixture)).toThrow(); }), )); it('should not swallow errors from browser state update', async () => { const routerEvents: Event[] = []; TestBed.inject(Router).resetConfig([{path: '**', component: BlankCmp}]); TestBed.inject(Router).events.subscribe((e) => { routerEvents.push(e); }); spyOn(TestBed.inject(Location), 'go').and.callFake(() => { throw new Error(); }); try { await RouterTestingHarness.create('/abc123'); } catch {} // Ensure the first event is the start and that we get to the ResolveEnd event. If this is not // true, then NavigationError may have been triggered at a time we don't expect here. expect(routerEvents[0]).toBeInstanceOf(NavigationStart); expect(routerEvents[routerEvents.length - 2]).toBeInstanceOf(ResolveEnd); expect(routerEvents[routerEvents.length - 1]).toBeInstanceOf(NavigationError); }); it('should replace state when path is equal to current path', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: 'simple', component: SimpleCmp}, {path: 'user/:name', component: UserCmp}, ], }, ]); router.navigateByUrl('/team/33/simple'); advance(fixture); router.navigateByUrl('/team/22/user/victor'); advance(fixture); router.navigateByUrl('/team/22/user/victor'); advance(fixture); location.back(); advance(fixture); expect(location.path()).toEqual('/team/33/simple'); }), )); it('should handle componentless paths', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmpWithTwoOutlets); router.resetConfig([ { path: 'parent/:id', children: [ {path: 'simple', component: SimpleCmp}, {path: 'user/:name', component: UserCmp, outlet: 'right'}, ], }, {path: 'user/:name', component: UserCmp}, ]); // navigate to a componentless route router.navigateByUrl('/parent/11/(simple//right:user/victor)'); advance(fixture); expect(location.path()).toEqual('/parent/11/(simple//right:user/victor)'); expect(fixture.nativeElement).toHaveText('primary [simple] right [user victor]'); // navigate to the same route with different params (reuse) router.navigateByUrl('/parent/22/(simple//right:user/fedor)'); advance(fixture); expect(location.path()).toEqual('/parent/22/(simple//right:user/fedor)'); expect(fixture.nativeElement).toHaveText('primary [simple] right [user fedor]'); // navigate to a normal route (check deactivation) router.navigateByUrl('/user/victor'); advance(fixture); expect(location.path()).toEqual('/user/victor'); expect(fixture.nativeElement).toHaveText('primary [user victor] right []'); // navigate back to a componentless route router.navigateByUrl('/parent/11/(simple//right:user/victor)'); advance(fixture); expect(location.path()).toEqual('/parent/11/(simple//right:user/victor)'); expect(fixture.nativeElement).toHaveText('primary [simple] right [user victor]'); }), )); it('should not deactivate aux routes when navigating from a componentless routes', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, TwoOutletsCmp); router.resetConfig([ {path: 'simple', component: SimpleCmp}, {path: 'componentless', children: [{path: 'simple', component: SimpleCmp}]}, {path: 'user/:name', outlet: 'aux', component: UserCmp}, ]); router.navigateByUrl('/componentless/simple(aux:user/victor)'); advance(fixture); expect(location.path()).toEqual('/componentless/simple(aux:user/victor)'); expect(fixture.nativeElement).toHaveText('[ simple, aux: user victor ]'); router.navigateByUrl('/simple(aux:user/victor)'); advance(fixture); expect(location.path()).toEqual('/simple(aux:user/victor)'); expect(fixture.nativeElement).toHaveText('[ simple, aux: user victor ]'); }), )); it('should emit an event when an outlet gets activated', fakeAsync(() => { @Component({ selector: 'container', template: `<router-outlet (activate)="recordActivate($event)" (deactivate)="recordDeactivate($event)"></router-outlet>`, standalone: false, }) class Container { activations: any[] = []; deactivations: any[] = []; recordActivate(component: any): void { this.activations.push(component); } recordDeactivate(component: any): void { this.deactivations.push(component); } } TestBed.configureTestingModule({declarations: [Container]}); const router: Router = TestBed.inject(Router); const fixture = createRoot(router, Container); const cmp = fixture.componentInstance; router.resetConfig([ {path: 'blank', component: BlankCmp}, {path: 'simple', component: SimpleCmp}, ]); cmp.activations = []; cmp.deactivations = []; router.navigateByUrl('/blank'); advance(fixture); expect(cmp.activations.length).toEqual(1); expect(cmp.activations[0] instanceof BlankCmp).toBe(true); router.navigateByUrl('/simple'); advance(fixture); expect(cmp.activations.length).toEqual(2); expect(cmp.activations[1] instanceof SimpleCmp).toBe(true); expect(cmp.deactivations.length).toEqual(1); expect(cmp.deactivations[0] instanceof BlankCmp).toBe(true); })); it('should update url and router state before activating components', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'cmp', component: ComponentRecordingRoutePathAndUrl}]); router.navigateByUrl('/cmp'); advance(fixture); const cmp: ComponentRecordingRoutePathAndUrl = fixture.debugElement.children[1].componentInstance; expect(cmp.url).toBe('/cmp'); expect(cmp.path.length).toEqual(2); }), ));
{ "end_byte": 79865, "start_byte": 71171, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_79871_88144
ribe('data', () => { class ResolveSix { resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): number { return 6; } } @Component({ selector: 'nested-cmp', template: 'nested-cmp', standalone: false, }) class NestedComponentWithData { data: any = []; constructor(private route: ActivatedRoute) { route.data.forEach((d) => this.data.push(d)); } } beforeEach(() => { TestBed.configureTestingModule({ providers: [ {provide: 'resolveTwo', useValue: (a: any, b: any) => 2}, {provide: 'resolveFour', useValue: (a: any, b: any) => 4}, {provide: 'resolveSix', useClass: ResolveSix}, {provide: 'resolveError', useValue: (a: any, b: any) => Promise.reject('error')}, {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; }, }, ], }); }); it('should provide resolved data', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmpWithTwoOutlets); router.resetConfig([ { path: 'parent/:id', data: {one: 1}, resolve: {two: 'resolveTwo'}, children: [ {path: '', data: {three: 3}, resolve: {four: 'resolveFour'}, component: RouteCmp}, { path: '', data: {five: 5}, resolve: {six: 'resolveSix'}, component: RouteCmp, outlet: 'right', }, ], }, ]); router.navigateByUrl('/parent/1'); advance(fixture); const primaryCmp = fixture.debugElement.children[1].componentInstance; const rightCmp = fixture.debugElement.children[3].componentInstance; expect(primaryCmp.route.snapshot.data).toEqual({one: 1, two: 2, three: 3, four: 4}); expect(rightCmp.route.snapshot.data).toEqual({one: 1, two: 2, five: 5, six: 6}); const primaryRecorded: any[] = []; primaryCmp.route.data.forEach((rec: any) => primaryRecorded.push(rec)); const rightRecorded: any[] = []; rightCmp.route.data.forEach((rec: any) => rightRecorded.push(rec)); router.navigateByUrl('/parent/2'); advance(fixture); expect(primaryRecorded).toEqual([{one: 1, three: 3, two: 2, four: 4}]); expect(rightRecorded).toEqual([{one: 1, five: 5, two: 2, six: 6}]); }), )); it('should handle errors', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'simple', component: SimpleCmp, resolve: {error: 'resolveError'}}, ]); const recordedEvents: any[] = []; router.events.subscribe((e) => e instanceof RouterEvent && recordedEvents.push(e)); let e: any = null; router.navigateByUrl('/simple')!.catch((error) => (e = error)); advance(fixture); expectEvents(recordedEvents, [ [NavigationStart, '/simple'], [RoutesRecognized, '/simple'], [GuardsCheckStart, '/simple'], [GuardsCheckEnd, '/simple'], [ResolveStart, '/simple'], [NavigationError, '/simple'], ]); expect(e).toEqual('error'); }), )); it('should handle empty errors', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'simple', component: SimpleCmp, resolve: {error: 'resolveNullError'}}, ]); const recordedEvents: any[] = []; router.events.subscribe((e) => e instanceof RouterEvent && recordedEvents.push(e)); let e: any = 'some value'; router.navigateByUrl('/simple').catch((error) => (e = error)); advance(fixture); expect(e).toEqual(null); }), )); it('should not navigate when all resolvers return empty result', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'simple', component: SimpleCmp, resolve: {e1: 'resolveEmpty', e2: 'resolveEmpty'}, }, ]); const recordedEvents: any[] = []; router.events.subscribe((e) => e instanceof RouterEvent && recordedEvents.push(e)); let e: any = null; router.navigateByUrl('/simple').catch((error) => (e = error)); advance(fixture); expectEvents(recordedEvents, [ [NavigationStart, '/simple'], [RoutesRecognized, '/simple'], [GuardsCheckStart, '/simple'], [GuardsCheckEnd, '/simple'], [ResolveStart, '/simple'], [NavigationCancel, '/simple'], ]); expect((recordedEvents[recordedEvents.length - 1] as NavigationCancel).code).toBe( NavigationCancellationCode.NoDataFromResolver, ); expect(e).toEqual(null); }), )); it('should not navigate when at least one resolver returns empty result', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'simple', component: SimpleCmp, resolve: {e1: 'resolveTwo', e2: 'resolveEmpty'}}, ]); const recordedEvents: any[] = []; router.events.subscribe((e) => e instanceof RouterEvent && recordedEvents.push(e)); let e: any = null; router.navigateByUrl('/simple').catch((error) => (e = error)); advance(fixture); expectEvents(recordedEvents, [ [NavigationStart, '/simple'], [RoutesRecognized, '/simple'], [GuardsCheckStart, '/simple'], [GuardsCheckEnd, '/simple'], [ResolveStart, '/simple'], [NavigationCancel, '/simple'], ]); expect(e).toEqual(null); }), )); it('should not navigate when all resolvers for a child route from forChild() returns empty result', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); @Component({ selector: 'lazy-cmp', template: 'lazy-loaded-1', standalone: false, }) class LazyComponent1 {} @NgModule({ declarations: [LazyComponent1], imports: [ RouterModule.forChild([ { path: 'loaded', component: LazyComponent1, resolve: {e1: 'resolveEmpty', e2: 'resolveEmpty'}, }, ]), ], }) class LoadedModule {} router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]); const recordedEvents: any[] = []; router.events.subscribe((e) => e instanceof RouterEvent && recordedEvents.push(e)); let e: any = null; router.navigateByUrl('lazy/loaded').catch((error) => (e = error)); advance(fixture); expectEvents(recordedEvents, [ [NavigationStart, '/lazy/loaded'], [RoutesRecognized, '/lazy/loaded'], [GuardsCheckStart, '/lazy/loaded'], [GuardsCheckEnd, '/lazy/loaded'], [ResolveStart, '/lazy/loaded'], [NavigationCancel, '/lazy/loaded'], ]); expect(e).toEqual(null); }), ));
{ "end_byte": 88144, "start_byte": 79871, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_88152_98168
should not navigate when at least one resolver for a child route from forChild() returns empty result', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); @Component({ selector: 'lazy-cmp', template: 'lazy-loaded-1', standalone: false, }) class LazyComponent1 {} @NgModule({ declarations: [LazyComponent1], imports: [ RouterModule.forChild([ { path: 'loaded', component: LazyComponent1, resolve: {e1: 'resolveTwo', e2: 'resolveEmpty'}, }, ]), ], }) class LoadedModule {} router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]); const recordedEvents: any[] = []; router.events.subscribe((e) => e instanceof RouterEvent && recordedEvents.push(e)); let e: any = null; router.navigateByUrl('lazy/loaded').catch((error) => (e = error)); advance(fixture); expectEvents(recordedEvents, [ [NavigationStart, '/lazy/loaded'], [RoutesRecognized, '/lazy/loaded'], [GuardsCheckStart, '/lazy/loaded'], [GuardsCheckEnd, '/lazy/loaded'], [ResolveStart, '/lazy/loaded'], [NavigationCancel, '/lazy/loaded'], ]); expect(e).toEqual(null); }), )); it('should include target snapshot in NavigationError when resolver throws', async () => { const router = TestBed.inject(Router); const errorMessage = 'throwing resolver'; @Injectable({providedIn: 'root'}) class ThrowingResolver { resolve() { throw new Error(errorMessage); } } let caughtError: NavigationError | undefined; router.events.subscribe((e) => { if (e instanceof NavigationError) { caughtError = e; } }); router.resetConfig([ {path: 'throwing', resolve: {thrower: ThrowingResolver}, component: BlankCmp}, ]); try { await router.navigateByUrl('/throwing'); fail('navigation should throw'); } catch (e: unknown) { expect((e as Error).message).toEqual(errorMessage); } expect(caughtError).toBeDefined(); expect(caughtError?.target).toBeDefined(); }); it('should preserve resolved data', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'parent', resolve: {two: 'resolveTwo'}, children: [ {path: 'child1', component: CollectParamsCmp}, {path: 'child2', component: CollectParamsCmp}, ], }, ]); router.navigateByUrl('/parent/child1'); advance(fixture); router.navigateByUrl('/parent/child2'); advance(fixture); const cmp: CollectParamsCmp = fixture.debugElement.children[1].componentInstance; expect(cmp.route.snapshot.data).toEqual({two: 2}); }), )); it('should override route static data with resolved data', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: '', component: NestedComponentWithData, resolve: {prop: 'resolveTwo'}, data: {prop: 'static'}, }, ]); router.navigateByUrl('/'); advance(fixture); const cmp = fixture.debugElement.children[1].componentInstance; expect(cmp.data).toEqual([{prop: 2}]); }), )); it('should correctly override inherited route static data with resolved data', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'a', component: WrapperCmp, resolve: {prop2: 'resolveTwo'}, data: {prop: 'wrapper-a'}, children: [ // will inherit data from this child route because it has `path` and its parent has // component { path: 'b', data: {prop: 'nested-b'}, resolve: {prop3: 'resolveFour'}, children: [ { path: 'c', children: [ {path: '', component: NestedComponentWithData, data: {prop3: 'nested'}}, ], }, ], }, ], }, ]); router.navigateByUrl('/a/b/c'); advance(fixture); const pInj = fixture.debugElement.queryAll(By.directive(NestedComponentWithData))[0] .injector!; const cmp = pInj.get(NestedComponentWithData); expect(cmp.data).toEqual([{prop: 'nested-b', prop3: 'nested'}]); }), )); it('should not override inherited resolved data with inherited static data', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'a', component: WrapperCmp, resolve: {prop2: 'resolveTwo'}, data: {prop: 'wrapper-a'}, children: [ // will inherit data from this child route because it has `path` and its parent has // component { path: 'b', data: {prop2: 'parent-b', prop: 'parent-b'}, children: [ { path: 'c', resolve: {prop2: 'resolveFour'}, children: [ { path: '', component: NestedComponentWithData, data: {prop: 'nested-d'}, }, ], }, ], }, ], }, ]); router.navigateByUrl('/a/b/c'); advance(fixture); const pInj = fixture.debugElement.queryAll(By.directive(NestedComponentWithData))[0] .injector!; const cmp = pInj.get(NestedComponentWithData); expect(cmp.data).toEqual([{prop: 'nested-d', prop2: 4}]); }), )); it('should not override nested route static data when both are using resolvers', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'child', component: WrapperCmp, resolve: {prop: 'resolveTwo'}, children: [ { path: '', pathMatch: 'full', component: NestedComponentWithData, resolve: {prop: 'resolveFour'}, }, ], }, ]); router.navigateByUrl('/child'); advance(fixture); const pInj = fixture.debugElement.query(By.directive(NestedComponentWithData)).injector!; const cmp = pInj.get(NestedComponentWithData); expect(cmp.data).toEqual([{prop: 4}]); }), )); it("should not override child route's static data when both are using static data", fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'child', component: WrapperCmp, data: {prop: 'wrapper'}, children: [ { path: '', pathMatch: 'full', component: NestedComponentWithData, data: {prop: 'inner'}, }, ], }, ]); router.navigateByUrl('/child'); advance(fixture); const pInj = fixture.debugElement.query(By.directive(NestedComponentWithData)).injector!; const cmp = pInj.get(NestedComponentWithData); expect(cmp.data).toEqual([{prop: 'inner'}]); }), )); it("should not override child route's static data when wrapper is using resolved data and the child route static data", fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'nested', component: WrapperCmp, resolve: {prop: 'resolveTwo', prop2: 'resolveSix'}, data: {prop3: 'wrapper-static', prop4: 'another-static'}, children: [ { path: '', pathMatch: 'full', component: NestedComponentWithData, data: {prop: 'nested', prop4: 'nested-static'}, }, ], }, ]); router.navigateByUrl('/nested'); advance(fixture); const pInj = fixture.debugElement.query(By.directive(NestedComponentWithData)).injector!; const cmp = pInj.get(NestedComponentWithData); // Issue 34361 - `prop` should contain value defined in `data` object from the nested // route. expect(cmp.data).toEqual([ {prop: 'nested', prop2: 6, prop3: 'wrapper-static', prop4: 'nested-static'}, ]); }), ));
{ "end_byte": 98168, "start_byte": 88152, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_98176_103348
should allow guards alter data resolved by routes', fakeAsync( inject([Router], (router: Router) => { // This is not documented or recommended behavior but is here to prevent unexpected // regressions. This behavior isn't necessary 'by design' but it was discovered during a // refactor that some teams depend on it. const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'route', component: NestedComponentWithData, canActivate: ['overridingGuard'], }, ]); router.navigateByUrl('/route'); advance(fixture); const pInj = fixture.debugElement.query(By.directive(NestedComponentWithData)).injector!; const cmp = pInj.get(NestedComponentWithData); expect(cmp.data).toEqual([{prop: 10}]); }), )); it('should rerun resolvers when the urls segments of a wildcard route change', fakeAsync( inject([Router, Location], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: '**', component: CollectParamsCmp, resolve: {numberOfUrlSegments: 'numberOfUrlSegments'}, }, ]); router.navigateByUrl('/one/two'); advance(fixture); const cmp = fixture.debugElement.children[1].componentInstance; expect(cmp.route.snapshot.data).toEqual({numberOfUrlSegments: 2}); router.navigateByUrl('/one/two/three'); advance(fixture); expect(cmp.route.snapshot.data).toEqual({numberOfUrlSegments: 3}); }), )); describe('should run resolvers for the same route concurrently', () => { let log: string[]; let observer: Observer<unknown>; beforeEach(() => { log = []; TestBed.configureTestingModule({ providers: [ { provide: 'resolver1', useValue: () => { const obs$ = new Observable((obs) => { observer = obs; return () => {}; }); return obs$.pipe(map(() => log.push('resolver1'))); }, }, { provide: 'resolver2', useValue: () => { return of(null).pipe( map(() => { log.push('resolver2'); observer.next(null); observer.complete(); }), ); }, }, ], }); }); it('works', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'a', resolve: { one: 'resolver1', two: 'resolver2', }, component: SimpleCmp, }, ]); router.navigateByUrl('/a'); advance(fixture); expect(log).toEqual(['resolver2', 'resolver1']); }), )); }); it('can resolve symbol keys', fakeAsync(() => { const router = TestBed.inject(Router); const fixture = createRoot(router, RootCmp); const symbolKey = Symbol('key'); router.resetConfig([ {path: 'simple', component: SimpleCmp, resolve: {[symbolKey]: 'resolveFour'}}, ]); router.navigateByUrl('/simple'); advance(fixture); expect(router.routerState.root.snapshot.firstChild!.data[symbolKey]).toEqual(4); })); it('should allow resolvers as pure functions', fakeAsync(() => { const router = TestBed.inject(Router); const fixture = createRoot(router, RootCmp); const user = Symbol('user'); const userResolver: ResolveFn<string> = (route: ActivatedRouteSnapshot) => route.params['user']; router.resetConfig([ {path: ':user', component: SimpleCmp, resolve: {[user]: userResolver}}, ]); router.navigateByUrl('/atscott'); advance(fixture); expect(router.routerState.root.snapshot.firstChild!.data[user]).toEqual('atscott'); })); it('should allow DI in resolvers as pure functions', fakeAsync(() => { const router = TestBed.inject(Router); const fixture = createRoot(router, RootCmp); const user = Symbol('user'); @Injectable({providedIn: 'root'}) class LoginState { user = 'atscott'; } router.resetConfig([ { path: '**', component: SimpleCmp, resolve: { [user]: () => coreInject(LoginState).user, }, }, ]); router.navigateByUrl('/'); advance(fixture); expect(router.routerState.root.snapshot.firstChild!.data[user]).toEqual('atscott'); })); });
{ "end_byte": 103348, "start_byte": 98176, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_103354_112416
ribe('router links', () => { it('should support skipping location update for anchor router links', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = TestBed.createComponent(RootCmp); advance(fixture); router.resetConfig([{path: 'team/:id', component: TeamCmp}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]'); const teamCmp = fixture.debugElement.childNodes[1].componentInstance; teamCmp.routerLink = ['/team/0']; advance(fixture); const anchor = fixture.debugElement.query(By.css('a')).nativeElement; anchor.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('team 0 [ , right: ]'); expect(location.path()).toEqual('/team/22'); teamCmp.routerLink = ['/team/1']; advance(fixture); const button = fixture.debugElement.query(By.css('button')).nativeElement; button.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('team 1 [ , right: ]'); expect(location.path()).toEqual('/team/22'); }), )); it('should support string router links', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: 'link', component: StringLinkCmp}, {path: 'simple', component: SimpleCmp}, ], }, ]); router.navigateByUrl('/team/22/link'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ link, right: ]'); const native = fixture.nativeElement.querySelector('a'); expect(native.getAttribute('href')).toEqual('/team/33/simple'); expect(native.getAttribute('target')).toEqual('_self'); native.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('team 33 [ simple, right: ]'); }), )); it('should not preserve query params and fragment by default', fakeAsync(() => { @Component({ selector: 'someRoot', template: `<router-outlet></router-outlet><a routerLink="/home">Link</a>`, standalone: false, }) class RootCmpWithLink {} TestBed.configureTestingModule({declarations: [RootCmpWithLink]}); const router: Router = TestBed.inject(Router); const fixture = createRoot(router, RootCmpWithLink); router.resetConfig([{path: 'home', component: SimpleCmp}]); const native = fixture.nativeElement.querySelector('a'); router.navigateByUrl('/home?q=123#fragment'); advance(fixture); expect(native.getAttribute('href')).toEqual('/home'); })); it('should not throw when commands is null or undefined', fakeAsync(() => { @Component({ selector: 'someCmp', template: `<router-outlet></router-outlet> <a [routerLink]="null">Link</a> <button [routerLink]="null">Button</button> <a [routerLink]="undefined">Link</a> <button [routerLink]="undefined">Button</button> `, standalone: false, }) class CmpWithLink {} TestBed.configureTestingModule({declarations: [CmpWithLink]}); const router: Router = TestBed.inject(Router); let fixture: ComponentFixture<CmpWithLink> = createRoot(router, CmpWithLink); router.resetConfig([{path: 'home', component: SimpleCmp}]); const anchors = fixture.nativeElement.querySelectorAll('a'); const buttons = fixture.nativeElement.querySelectorAll('button'); expect(() => anchors[0].click()).not.toThrow(); expect(() => anchors[1].click()).not.toThrow(); expect(() => buttons[0].click()).not.toThrow(); expect(() => buttons[1].click()).not.toThrow(); })); it('should not throw when some command is null', fakeAsync(() => { @Component({ selector: 'someCmp', template: `<router-outlet></router-outlet><a [routerLink]="[null]">Link</a><button [routerLink]="[null]">Button</button>`, standalone: false, }) class CmpWithLink {} TestBed.configureTestingModule({declarations: [CmpWithLink]}); const router: Router = TestBed.inject(Router); expect(() => createRoot(router, CmpWithLink)).not.toThrow(); })); it('should not throw when some command is undefined', fakeAsync(() => { @Component({ selector: 'someCmp', template: `<router-outlet></router-outlet><a [routerLink]="[undefined]">Link</a><button [routerLink]="[undefined]">Button</button>`, standalone: false, }) class CmpWithLink {} TestBed.configureTestingModule({declarations: [CmpWithLink]}); const router: Router = TestBed.inject(Router); expect(() => createRoot(router, CmpWithLink)).not.toThrow(); })); it('should update hrefs when query params or fragment change', fakeAsync(() => { @Component({ selector: 'someRoot', template: `<router-outlet></router-outlet><a routerLink="/home" queryParamsHandling="preserve" preserveFragment>Link</a>`, standalone: false, }) class RootCmpWithLink {} TestBed.configureTestingModule({declarations: [RootCmpWithLink]}); const router: Router = TestBed.inject(Router); const fixture = createRoot(router, RootCmpWithLink); router.resetConfig([{path: 'home', component: SimpleCmp}]); const native = fixture.nativeElement.querySelector('a'); router.navigateByUrl('/home?q=123'); advance(fixture); expect(native.getAttribute('href')).toEqual('/home?q=123'); router.navigateByUrl('/home?q=456'); advance(fixture); expect(native.getAttribute('href')).toEqual('/home?q=456'); router.navigateByUrl('/home?q=456#1'); advance(fixture); expect(native.getAttribute('href')).toEqual('/home?q=456#1'); })); it('should correctly use the preserve strategy', fakeAsync(() => { @Component({ selector: 'someRoot', template: `<router-outlet></router-outlet><a routerLink="/home" [queryParams]="{q: 456}" queryParamsHandling="preserve">Link</a>`, standalone: false, }) class RootCmpWithLink {} TestBed.configureTestingModule({declarations: [RootCmpWithLink]}); const router: Router = TestBed.inject(Router); const fixture = createRoot(router, RootCmpWithLink); router.resetConfig([{path: 'home', component: SimpleCmp}]); const native = fixture.nativeElement.querySelector('a'); router.navigateByUrl('/home?a=123'); advance(fixture); expect(native.getAttribute('href')).toEqual('/home?a=123'); })); it('should correctly use the merge strategy', fakeAsync(() => { @Component({ selector: 'someRoot', template: `<router-outlet></router-outlet><a routerLink="/home" [queryParams]="{removeMe: null, q: 456}" queryParamsHandling="merge">Link</a>`, standalone: false, }) class RootCmpWithLink {} TestBed.configureTestingModule({declarations: [RootCmpWithLink]}); const router: Router = TestBed.inject(Router); const fixture = createRoot(router, RootCmpWithLink); router.resetConfig([{path: 'home', component: SimpleCmp}]); const native = fixture.nativeElement.querySelector('a'); router.navigateByUrl('/home?a=123&removeMe=123'); advance(fixture); expect(native.getAttribute('href')).toEqual('/home?a=123&q=456'); })); it('should support using links on non-a tags', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: 'link', component: StringLinkButtonCmp}, {path: 'simple', component: SimpleCmp}, ], }, ]); router.navigateByUrl('/team/22/link'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ link, right: ]'); const button = fixture.nativeElement.querySelector('button'); expect(button.getAttribute('tabindex')).toEqual('0'); button.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('team 33 [ simple, right: ]'); }), ));
{ "end_byte": 112416, "start_byte": 103354, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_112424_121596
should support absolute router links', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: 'link', component: AbsoluteLinkCmp}, {path: 'simple', component: SimpleCmp}, ], }, ]); router.navigateByUrl('/team/22/link'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ link, right: ]'); const native = fixture.nativeElement.querySelector('a'); expect(native.getAttribute('href')).toEqual('/team/33/simple'); native.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('team 33 [ simple, right: ]'); }), )); it('should support relative router links', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: 'link', component: RelativeLinkCmp}, {path: 'simple', component: SimpleCmp}, ], }, ]); router.navigateByUrl('/team/22/link'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ link, right: ]'); const native = fixture.nativeElement.querySelector('a'); expect(native.getAttribute('href')).toEqual('/team/22/simple'); native.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ simple, right: ]'); }), )); it('should support top-level link', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RelativeLinkInIfCmp); advance(fixture); router.resetConfig([ {path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}, ]); router.navigateByUrl('/'); advance(fixture); expect(fixture.nativeElement).toHaveText(''); const cmp = fixture.componentInstance; cmp.show = true; advance(fixture); expect(fixture.nativeElement).toHaveText('link'); const native = fixture.nativeElement.querySelector('a'); expect(native.getAttribute('href')).toEqual('/simple'); native.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('linksimple'); }), )); it('should support query params and fragments', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: 'link', component: LinkWithQueryParamsAndFragment}, {path: 'simple', component: SimpleCmp}, ], }, ]); router.navigateByUrl('/team/22/link'); advance(fixture); const native = fixture.nativeElement.querySelector('a'); expect(native.getAttribute('href')).toEqual('/team/22/simple?q=1#f'); native.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ simple, right: ]'); expect(location.path(true)).toEqual('/team/22/simple?q=1#f'); }), )); describe('should support history and state', () => { let component: typeof LinkWithState | typeof DivLinkWithState; it('for anchor elements', () => { // Test logic in afterEach to reduce duplication component = LinkWithState; }); it('for non-anchor elements', () => { // Test logic in afterEach to reduce duplication component = DivLinkWithState; }); afterEach(fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: 'link', component}, {path: 'simple', component: SimpleCmp}, ], }, ]); router.navigateByUrl('/team/22/link'); advance(fixture); const native = fixture.nativeElement.querySelector('#link'); native.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ simple, right: ]'); // Check the history entry expect(location.getState()).toEqual({foo: 'bar', navigationId: 3}); }), )); }); it('should set href on area elements', fakeAsync(() => { @Component({ selector: 'someRoot', template: `<router-outlet></router-outlet><map><area routerLink="/home" /></map>`, standalone: false, }) class RootCmpWithArea {} TestBed.configureTestingModule({declarations: [RootCmpWithArea]}); const router: Router = TestBed.inject(Router); const fixture = createRoot(router, RootCmpWithArea); router.resetConfig([{path: 'home', component: SimpleCmp}]); const native = fixture.nativeElement.querySelector('area'); expect(native.getAttribute('href')).toEqual('/home'); })); }); describe('redirects', () => { it('should work', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'old/team/:id', redirectTo: 'team/:id'}, {path: 'team/:id', component: TeamCmp}, ]); router.navigateByUrl('old/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); }), )); it('can redirect from componentless named outlets', fakeAsync(() => { const router = TestBed.inject(Router); const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'main', outlet: 'aux', component: BlankCmp}, {path: '', pathMatch: 'full', outlet: 'aux', redirectTo: 'main'}, ]); router.navigateByUrl(''); advance(fixture); expect(TestBed.inject(Location).path()).toEqual('/(aux:main)'); })); it('should update Navigation object after redirects are applied', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); let initialUrl, afterRedirectUrl; router.resetConfig([ {path: 'old/team/:id', redirectTo: 'team/:id'}, {path: 'team/:id', component: TeamCmp}, ]); router.events.subscribe((e) => { if (e instanceof NavigationStart) { const navigation = router.getCurrentNavigation(); initialUrl = navigation && navigation.finalUrl; } if (e instanceof RoutesRecognized) { const navigation = router.getCurrentNavigation(); afterRedirectUrl = navigation && navigation.finalUrl; } }); router.navigateByUrl('old/team/22'); advance(fixture); expect(initialUrl).toBeUndefined(); expect(router.serializeUrl(afterRedirectUrl as any)).toBe('/team/22'); }), )); it('should not break the back button when trigger by location change', fakeAsync(() => { TestBed.configureTestingModule({ providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}], }); const router = TestBed.inject(Router); const location = TestBed.inject(Location); const fixture = TestBed.createComponent(RootCmp); advance(fixture); router.resetConfig([ {path: 'initial', component: BlankCmp}, {path: 'old/team/:id', redirectTo: 'team/:id'}, {path: 'team/:id', component: TeamCmp}, ]); location.go('initial'); location.historyGo(0); location.go('old/team/22'); location.historyGo(0); // initial navigation router.initialNavigation(); advance(fixture); expect(location.path()).toEqual('/team/22'); location.back(); advance(fixture); expect(location.path()).toEqual('/initial'); // location change location.go('/old/team/33'); location.historyGo(0); advance(fixture); expect(location.path()).toEqual('/team/33'); location.back(); advance(fixture); expect(location.path()).toEqual('/initial'); })); });
{ "end_byte": 121596, "start_byte": 112424, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_121601_130314
ribe('guards', () => { describe('CanActivate', () => { 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); const recordedEvents: Event[] = []; router.events.forEach((e) => recordedEvents.push(e)); router.resetConfig([ {path: 'team/:id', component: TeamCmp, canActivate: ['alwaysFalse']}, ]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual(''); expectEvents(recordedEvents, [ [NavigationStart, '/team/22'], [RoutesRecognized, '/team/22'], [GuardsCheckStart, '/team/22'], [ChildActivationStart], [ActivationStart], [GuardsCheckEnd, '/team/22'], [NavigationCancel, '/team/22'], ]); expect((recordedEvents[5] as GuardsCheckEnd).shouldActivate).toBe(false); }), )); }); 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); router.resetConfig([ { path: 'parent', canActivate: ['alwaysFalse'], children: [{path: 'team/:id', component: TeamCmp}], }, ]); router.navigateByUrl('parent/team/22'); advance(fixture); expect(location.path()).toEqual(''); }), )); }); 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.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); }), )); }); describe('should work when given a class', () => { class AlwaysTrue { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { return true; } } beforeEach(() => { TestBed.configureTestingModule({providers: [AlwaysTrue]}); }); 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.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); }), )); }); describe('should work when returns an observable', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ { provide: 'CanActivate', useValue: (a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { return new Observable<boolean>((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']}, ]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual(''); }), )); }); 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']}, ]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/22'); }), )); }); 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}, ], }); }); it('works', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'one', component: SimpleCmp}, {path: 'two', component: SimpleCmp, canActivate: ['alwaysFalse']}, ]); router.navigateByUrl('/one'); advance(fixture); expect(location.path()).toEqual('/one'); location.go('/two'); location.historyGo(0); advance(fixture); expect(location.path()).toEqual('/one'); }), )); }); 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([ { path: '', component: SimpleCmp, }, {path: 'one', component: RouteCmp, canActivate: ['returnFalseAndNavigate']}, ]); const fixture = TestBed.createComponent(RootCmp); router.navigateByUrl('/one'); advance(fixture); expect(location.path()).toEqual(''); expect(fixture.nativeElement).toHaveText('simple'); }), )); });
{ "end_byte": 130314, "start_byte": 121601, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_130324_141224
ribe('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[] = []; let cancelEvent: NavigationCancel = null!; router.events.forEach((e) => { recordedEvents.push(e); if (e instanceof NavigationCancel) cancelEvent = e; }); router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'one', component: RouteCmp, canActivate: ['returnUrlTree']}, {path: 'redirected', component: SimpleCmp}, ]); const fixture = TestBed.createComponent(RootCmp); router.navigateByUrl('/one'); advance(fixture); expect(location.path()).toEqual('/redirected'); expect(fixture.nativeElement).toHaveText('simple'); expect(cancelEvent && cancelEvent.reason).toBe( 'NavigationCancelingError: Redirecting to "/redirected"', ); expectEvents(recordedEvents, [ [NavigationStart, '/one'], [RoutesRecognized, '/one'], [GuardsCheckStart, '/one'], [ChildActivationStart, undefined], [ActivationStart, undefined], [NavigationCancel, '/one'], [NavigationStart, '/redirected'], [RoutesRecognized, '/redirected'], [GuardsCheckStart, '/redirected'], [ChildActivationStart, undefined], [ActivationStart, undefined], [GuardsCheckEnd, '/redirected'], [ResolveStart, '/redirected'], [ResolveEnd, '/redirected'], [ActivationEnd, undefined], [ChildActivationEnd, undefined], [NavigationEnd, '/redirected'], ]); }), )); it('works with root url', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const recordedEvents: Event[] = []; let cancelEvent: NavigationCancel = null!; router.events.forEach((e: any) => { recordedEvents.push(e); if (e instanceof NavigationCancel) cancelEvent = e; }); router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'one', component: RouteCmp, canActivate: ['returnRootUrlTree']}, ]); const fixture = TestBed.createComponent(RootCmp); router.navigateByUrl('/one'); advance(fixture); expect(location.path()).toEqual(''); expect(fixture.nativeElement).toHaveText('simple'); expect(cancelEvent && cancelEvent.reason).toBe( 'NavigationCancelingError: Redirecting to "/"', ); expectEvents(recordedEvents, [ [NavigationStart, '/one'], [RoutesRecognized, '/one'], [GuardsCheckStart, '/one'], [ChildActivationStart, undefined], [ActivationStart, undefined], [NavigationCancel, '/one'], [NavigationStart, '/'], [RoutesRecognized, '/'], [GuardsCheckStart, '/'], [ChildActivationStart, undefined], [ActivationStart, undefined], [GuardsCheckEnd, '/'], [ResolveStart, '/'], [ResolveEnd, '/'], [ActivationEnd, undefined], [ChildActivationEnd, undefined], [NavigationEnd, '/'], ]); }), )); it('replaces URL when URL is updated eagerly so back button can still work', fakeAsync(() => { TestBed.configureTestingModule({ providers: [provideRouter([], withRouterConfig({urlUpdateStrategy: 'eager'}))], }); const router = TestBed.inject(Router); const location = TestBed.inject(Location); router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'one', component: RouteCmp, canActivate: ['returnUrlTree']}, {path: 'redirected', component: SimpleCmp}, ]); createRoot(router, RootCmp); router.navigateByUrl('/one'); const urlChanges: string[] = []; location.onUrlChange((change) => { urlChanges.push(change); }); tick(); expect(location.path()).toEqual('/redirected'); expect(urlChanges).toEqual(['/one', '/redirected']); location.back(); tick(); expect(location.path()).toEqual(''); })); it('should resolve navigateByUrl promise after redirect finishes', fakeAsync(() => { TestBed.configureTestingModule({ providers: [provideRouter([], withRouterConfig({urlUpdateStrategy: 'eager'}))], }); const router = TestBed.inject(Router); const location = TestBed.inject(Location); let resolvedPath = ''; router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'one', component: RouteCmp, canActivate: ['returnUrlTree']}, {path: 'redirected', component: SimpleCmp}, ]); const fixture = createRoot(router, RootCmp); router.navigateByUrl('/one').then((v) => { resolvedPath = location.path(); }); tick(); expect(resolvedPath).toBe('/redirected'); })); it('can redirect to 404 without changing the URL', fakeAsync(() => { TestBed.configureTestingModule({ providers: [provideRouter([], withRouterConfig({urlUpdateStrategy: 'eager'}))], }); const router = TestBed.inject(Router); const location = TestBed.inject(Location); router.resetConfig([ {path: '', component: SimpleCmp}, { path: 'one', component: RouteCmp, canActivate: [ () => new RedirectCommand(router.parseUrl('/404'), {skipLocationChange: true}), ], }, {path: '404', component: SimpleCmp}, ]); const fixture = createRoot(router, RootCmp); router.navigateByUrl('/one'); advance(fixture); expect(location.path()).toEqual('/one'); expect(router.url.toString()).toEqual('/404'); })); it('can redirect while changing state object', fakeAsync(() => { TestBed.configureTestingModule({ providers: [provideRouter([], withRouterConfig({urlUpdateStrategy: 'eager'}))], }); const router = TestBed.inject(Router); const location = TestBed.inject(Location); router.resetConfig([ {path: '', component: SimpleCmp}, { path: 'one', component: RouteCmp, canActivate: [ () => new RedirectCommand(router.parseUrl('/redirected'), {state: {test: 1}}), ], }, {path: 'redirected', component: SimpleCmp}, ]); const fixture = createRoot(router, RootCmp); router.navigateByUrl('/one'); advance(fixture); expect(location.path()).toEqual('/redirected'); expect(location.getState()).toEqual(jasmine.objectContaining({test: 1})); })); }); it('can redirect to 404 without changing the URL', async () => { TestBed.configureTestingModule({ providers: [ provideRouter([ { path: 'one', component: RouteCmp, canActivate: [ () => { const router = coreInject(Router); router.navigateByUrl('/404', { browserUrl: router.getCurrentNavigation()?.finalUrl, }); return false; }, ], }, {path: '404', component: SimpleCmp}, ]), ], }); const location = TestBed.inject(Location); await RouterTestingHarness.create('/one'); expect(location.path()).toEqual('/one'); expect(TestBed.inject(Router).url.toString()).toEqual('/404'); }); it('can navigate to same internal route with different browser url', async () => { TestBed.configureTestingModule({ providers: [provideRouter([{path: 'one', component: RouteCmp}])], }); const location = TestBed.inject(Location); const router = TestBed.inject(Router); await RouterTestingHarness.create('/one'); await router.navigateByUrl('/one', {browserUrl: '/two'}); expect(location.path()).toEqual('/two'); expect(router.url.toString()).toEqual('/one'); }); it('retains browserUrl through UrlTree redirects', async () => { TestBed.configureTestingModule({ providers: [ provideRouter([ { path: 'one', component: RouteCmp, canActivate: [() => coreInject(Router).parseUrl('/404')], }, {path: '404', component: SimpleCmp}, ]), ], }); const router = TestBed.inject(Router); const location = TestBed.inject(Location); await RouterTestingHarness.create(); await router.navigateByUrl('/one', {browserUrl: router.parseUrl('abc123')}); expect(location.path()).toEqual('/abc123'); expect(TestBed.inject(Router).url.toString()).toEqual('/404'); });
{ "end_byte": 141224, "start_byte": 130324, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_141234_149909
ribe('runGuardsAndResolvers', () => { let guardRunCount = 0; let resolverRunCount = 0; beforeEach(() => { guardRunCount = 0; resolverRunCount = 0; TestBed.configureTestingModule({ providers: [ { provide: 'guard', useValue: () => { guardRunCount++; return true; }, }, {provide: 'resolver', useValue: () => resolverRunCount++}, ], }); }); function configureRouter( router: Router, runGuardsAndResolvers: RunGuardsAndResolvers, ): ComponentFixture<RootCmpWithTwoOutlets> { const fixture = createRoot(router, RootCmpWithTwoOutlets); router.resetConfig([ { path: 'a', runGuardsAndResolvers, component: RouteCmp, canActivate: ['guard'], resolve: {data: 'resolver'}, }, {path: 'b', component: SimpleCmp, outlet: 'right'}, { path: 'c/:param', runGuardsAndResolvers, component: RouteCmp, canActivate: ['guard'], resolve: {data: 'resolver'}, }, { path: 'd/:param', component: WrapperCmp, runGuardsAndResolvers, children: [ { path: 'e/:param', component: SimpleCmp, canActivate: ['guard'], resolve: {data: 'resolver'}, }, ], }, { path: 'throwing', runGuardsAndResolvers, component: ThrowingCmp, canActivate: ['guard'], resolve: {data: 'resolver'}, }, ]); router.navigateByUrl('/a'); advance(fixture); return fixture; } it('should rerun guards and resolvers when params change', fakeAsync( inject([Router], (router: Router) => { const fixture = configureRouter(router, 'paramsChange'); const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance; const recordedData: Data[] = []; cmp.route.data.subscribe((data) => recordedData.push(data)); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); router.navigateByUrl('/a;p=1'); advance(fixture); expect(guardRunCount).toEqual(2); expect(recordedData).toEqual([{data: 0}, {data: 1}]); router.navigateByUrl('/a;p=2'); advance(fixture); expect(guardRunCount).toEqual(3); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}]); router.navigateByUrl('/a;p=2?q=1'); advance(fixture); expect(guardRunCount).toEqual(3); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}]); }), )); it('should rerun guards and resolvers when query params change', fakeAsync( inject([Router], (router: Router) => { const fixture = configureRouter(router, 'paramsOrQueryParamsChange'); const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance; const recordedData: Data[] = []; cmp.route.data.subscribe((data) => recordedData.push(data)); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); router.navigateByUrl('/a;p=1'); advance(fixture); expect(guardRunCount).toEqual(2); expect(recordedData).toEqual([{data: 0}, {data: 1}]); router.navigateByUrl('/a;p=2'); advance(fixture); expect(guardRunCount).toEqual(3); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}]); router.navigateByUrl('/a;p=2?q=1'); advance(fixture); expect(guardRunCount).toEqual(4); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}, {data: 3}]); router.navigateByUrl('/a;p=2(right:b)?q=1'); advance(fixture); expect(guardRunCount).toEqual(4); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}, {data: 3}]); }), )); it('should always rerun guards and resolvers', fakeAsync( inject([Router], (router: Router) => { const fixture = configureRouter(router, 'always'); const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance; const recordedData: Data[] = []; cmp.route.data.subscribe((data) => recordedData.push(data)); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); router.navigateByUrl('/a;p=1'); advance(fixture); expect(guardRunCount).toEqual(2); expect(recordedData).toEqual([{data: 0}, {data: 1}]); router.navigateByUrl('/a;p=2'); advance(fixture); expect(guardRunCount).toEqual(3); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}]); router.navigateByUrl('/a;p=2?q=1'); advance(fixture); expect(guardRunCount).toEqual(4); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}, {data: 3}]); router.navigateByUrl('/a;p=2(right:b)?q=1'); advance(fixture); expect(guardRunCount).toEqual(5); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}, {data: 3}, {data: 4}]); // Issue #39030, always running guards and resolvers should not throw // when navigating away from a component with a throwing constructor. expect(() => { router.navigateByUrl('/throwing').catch(() => {}); advance(fixture); router.navigateByUrl('/a;p=1'); advance(fixture); }).not.toThrow(); }), )); it('should rerun rerun guards and resolvers when path params change', fakeAsync( inject([Router], (router: Router) => { const fixture = configureRouter(router, 'pathParamsChange'); const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance; const recordedData: Data[] = []; cmp.route.data.subscribe((data) => recordedData.push(data)); // First navigation has already run expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); // Changing any optional params will not result in running guards or resolvers router.navigateByUrl('/a;p=1'); advance(fixture); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); router.navigateByUrl('/a;p=2'); advance(fixture); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); router.navigateByUrl('/a;p=2?q=1'); advance(fixture); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); router.navigateByUrl('/a;p=2(right:b)?q=1'); advance(fixture); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); // Change to new route with path param should run guards and resolvers router.navigateByUrl('/c/paramValue'); advance(fixture); expect(guardRunCount).toEqual(2); // Modifying a path param should run guards and resolvers router.navigateByUrl('/c/paramValueChanged'); advance(fixture); expect(guardRunCount).toEqual(3); // Adding optional params should not cause guards/resolvers to run router.navigateByUrl('/c/paramValueChanged;p=1?q=2'); advance(fixture); expect(guardRunCount).toEqual(3); }), ));
{ "end_byte": 149909, "start_byte": 141234, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_149921_155893
should rerun when a parent segment changes', fakeAsync( inject([Router], (router: Router) => { const fixture = configureRouter(router, 'pathParamsChange'); const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance; // Land on an initial page router.navigateByUrl('/d/1;dd=11/e/2;dd=22'); advance(fixture); expect(guardRunCount).toEqual(2); // Changes cause re-run on the config with the guard router.navigateByUrl('/d/1;dd=11/e/3;ee=22'); advance(fixture); expect(guardRunCount).toEqual(3); // Changes to the parent also cause re-run router.navigateByUrl('/d/2;dd=11/e/3;ee=22'); advance(fixture); expect(guardRunCount).toEqual(4); }), )); it('should rerun rerun guards and resolvers when path or query params change', fakeAsync( inject([Router], (router: Router) => { const fixture = configureRouter(router, 'pathParamsOrQueryParamsChange'); const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance; const recordedData: Data[] = []; cmp.route.data.subscribe((data) => recordedData.push(data)); // First navigation has already run expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); // Changing matrix params will not result in running guards or resolvers router.navigateByUrl('/a;p=1'); advance(fixture); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); router.navigateByUrl('/a;p=2'); advance(fixture); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); // Adding query params will re-run guards/resolvers router.navigateByUrl('/a;p=2?q=1'); advance(fixture); expect(guardRunCount).toEqual(2); expect(recordedData).toEqual([{data: 0}, {data: 1}]); // Changing query params will re-run guards/resolvers router.navigateByUrl('/a;p=2?q=2'); advance(fixture); expect(guardRunCount).toEqual(3); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}]); }), )); it('should allow a predicate function to determine when to run guards and resolvers', fakeAsync( inject([Router], (router: Router) => { const fixture = configureRouter(router, (from, to) => to.paramMap.get('p') === '2'); const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance; const recordedData: Data[] = []; cmp.route.data.subscribe((data) => recordedData.push(data)); // First navigation has already run expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); // Adding `p` param shouldn't cause re-run router.navigateByUrl('/a;p=1'); advance(fixture); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); // Re-run should trigger on p=2 router.navigateByUrl('/a;p=2'); advance(fixture); expect(guardRunCount).toEqual(2); expect(recordedData).toEqual([{data: 0}, {data: 1}]); // Any other changes don't pass the predicate router.navigateByUrl('/a;p=3?q=1'); advance(fixture); expect(guardRunCount).toEqual(2); expect(recordedData).toEqual([{data: 0}, {data: 1}]); // Changing query params will re-run guards/resolvers router.navigateByUrl('/a;p=3?q=2'); advance(fixture); expect(guardRunCount).toEqual(2); expect(recordedData).toEqual([{data: 0}, {data: 1}]); }), )); }); describe('should wait for parent to complete', () => { let log: string[]; 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<boolean> { let resolve: (val: boolean) => void; const promise = new Promise<boolean>((res) => (resolve = res)); setTimeout(() => resolve(true), delay); return promise; } it('works', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'parent', canActivate: ['parentGuard'], children: [{path: 'child', component: SimpleCmp, canActivate: ['childGuard']}], }, ]); router.navigateByUrl('/parent/child'); advance(fixture); tick(15); expect(log).toEqual(['parent', 'child']); }), )); }); });
{ "end_byte": 155893, "start_byte": 149921, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_155901_166046
ribe('CanDeactivate', () => { let log: any; 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', () => { it('works', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'team/:id', component: TeamCmp, canDeactivate: ['CanDeactivateTeam']}, ]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); let successStatus: boolean = false; router.navigateByUrl('/team/33')!.then((res) => (successStatus = res)); advance(fixture); expect(location.path()).toEqual('/team/33'); expect(successStatus).toEqual(true); let canceledStatus: boolean = false; router.navigateByUrl('/team/44')!.then((res) => (canceledStatus = res)); advance(fixture); expect(location.path()).toEqual('/team/33'); expect(canceledStatus).toEqual(false); }), )); it('works with componentless routes', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'grandparent', canDeactivate: ['RecordingDeactivate'], children: [ { path: 'parent', canDeactivate: ['RecordingDeactivate'], children: [ { path: 'child', canDeactivate: ['RecordingDeactivate'], children: [ { path: 'simple', component: SimpleCmp, canDeactivate: ['RecordingDeactivate'], }, ], }, ], }, ], }, {path: 'simple', component: SimpleCmp}, ]); router.navigateByUrl('/grandparent/parent/child/simple'); advance(fixture); expect(location.path()).toEqual('/grandparent/parent/child/simple'); router.navigateByUrl('/simple'); advance(fixture); const child = fixture.debugElement.children[1].componentInstance; expect(log.map((a: any) => a.path)).toEqual([ 'simple', 'child', 'parent', 'grandparent', ]); expect(log[0].component instanceof SimpleCmp).toBeTruthy(); [1, 2, 3].forEach((i) => expect(log[i].component).toBeNull()); expect(child instanceof SimpleCmp).toBeTruthy(); expect(child).not.toBe(log[0].component); }), )); it('works with aux routes', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'two-outlets', component: TwoOutletsCmp, children: [ {path: 'a', component: BlankCmp}, { path: 'b', canDeactivate: ['RecordingDeactivate'], component: SimpleCmp, outlet: 'aux', }, ], }, ]); router.navigateByUrl('/two-outlets/(a//aux:b)'); advance(fixture); expect(location.path()).toEqual('/two-outlets/(a//aux:b)'); router.navigate(['two-outlets', {outlets: {aux: null}}]); advance(fixture); expect(log.map((a: any) => a.path)).toEqual(['b']); expect(location.path()).toEqual('/two-outlets/a'); }), )); it('works with a nested route', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: '', pathMatch: 'full', component: SimpleCmp}, {path: 'user/:name', component: UserCmp, canDeactivate: ['CanDeactivateUser']}, ], }, ]); router.navigateByUrl('/team/22/user/victor'); advance(fixture); // this works because we can deactivate victor router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/33'); router.navigateByUrl('/team/33/user/fedor'); advance(fixture); // this doesn't work cause we cannot deactivate fedor router.navigateByUrl('/team/44'); advance(fixture); expect(location.path()).toEqual('/team/33/user/fedor'); }), )); }); it('should use correct component to deactivate forChild route', fakeAsync( inject([Router], (router: Router) => { @Component({ selector: 'admin', template: '', standalone: false, }) class AdminComponent {} @NgModule({ declarations: [AdminComponent], imports: [ RouterModule.forChild([ { path: '', component: AdminComponent, canDeactivate: ['RecordingDeactivate'], }, ]), ], }) class LazyLoadedModule {} const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'a', component: WrapperCmp, children: [{path: '', pathMatch: 'full', loadChildren: () => LazyLoadedModule}], }, {path: 'b', component: SimpleCmp}, ]); router.navigateByUrl('/a'); advance(fixture); router.navigateByUrl('/b'); advance(fixture); expect(log[0].component).toBeInstanceOf(AdminComponent); }), )); it('should not create a route state if navigation is canceled', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'main', component: TeamCmp, children: [ {path: 'component1', component: SimpleCmp, canDeactivate: ['alwaysFalse']}, {path: 'component2', component: SimpleCmp}, ], }, ]); router.navigateByUrl('/main/component1'); advance(fixture); router.navigateByUrl('/main/component2'); advance(fixture); const teamCmp = fixture.debugElement.children[1].componentInstance; expect(teamCmp.route.firstChild.url.value[0].path).toEqual('component1'); expect(location.path()).toEqual('/main/component1'); }), ));
{ "end_byte": 166046, "start_byte": 155901, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_166056_176392
should not run CanActivate when CanDeactivate returns false', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'main', component: TeamCmp, children: [ { path: 'component1', component: SimpleCmp, canDeactivate: ['alwaysFalseWithDelayAndLogging'], }, { path: 'component2', component: SimpleCmp, canActivate: ['canActivate_alwaysTrueAndLogging'], }, ], }, ]); router.navigateByUrl('/main/component1'); advance(fixture); expect(location.path()).toEqual('/main/component1'); router.navigateByUrl('/main/component2'); advance(fixture); expect(location.path()).toEqual('/main/component1'); expect(log).toEqual(['called']); }), )); it('should call guards every time when navigating to the same url over and over again', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'simple', component: SimpleCmp, canDeactivate: ['alwaysFalseAndLogging']}, {path: 'blank', component: BlankCmp}, ]); router.navigateByUrl('/simple'); advance(fixture); router.navigateByUrl('/blank'); advance(fixture); expect(log).toEqual(['called']); expect(location.path()).toEqual('/simple'); router.navigateByUrl('/blank'); advance(fixture); expect(log).toEqual(['called', 'called']); expect(location.path()).toEqual('/simple'); }), )); describe('next state', () => { let log: string[]; class ClassWithNextState { canDeactivate( component: TeamCmp, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState: RouterStateSnapshot, ): boolean { log.push(currentState.url, nextState.url); return true; } } 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; }, }, ], }); }); it('should pass next state as the 4 argument when guard is a class', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, canDeactivate: [ ( component: TeamCmp, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState: RouterStateSnapshot, ) => coreInject(ClassWithNextState).canDeactivate( component, currentRoute, currentState, nextState, ), ], }, ]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/33'); expect(log).toEqual(['/team/22', '/team/33']); }), )); it('should pass next state as the 4 argument when guard is a function', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'team/:id', component: TeamCmp, canDeactivate: ['FunctionWithNextState']}, ]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/33'); expect(log).toEqual(['/team/22', '/team/33']); }), )); }); describe('should work when given a class', () => { class AlwaysTrue { canDeactivate(): boolean { return true; } } beforeEach(() => { TestBed.configureTestingModule({providers: [AlwaysTrue]}); }); it('works', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, canDeactivate: [() => coreInject(AlwaysTrue).canDeactivate()], }, ]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/33'); }), )); }); describe('should work when returns an observable', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ { provide: 'CanDeactivate', useValue: (c: TeamCmp, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { return new Observable<boolean>((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']}, ]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/22'); }), )); }); }); 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); router.resetConfig([ { path: '', canActivateChild: ['alwaysFalse'], children: [{path: 'team/:id', component: TeamCmp}], }, ]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); router.navigateByUrl('/team/33')!.catch(() => {}); advance(fixture); expect(location.path()).toEqual('/team/22'); }), )); }); it('should find the guard provided in lazy loaded module', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { @Component({ selector: 'admin', template: '<router-outlet></router-outlet>', standalone: false, }) class AdminComponent {} @Component({ selector: 'lazy', template: 'lazy-loaded', standalone: false, }) class LazyLoadedComponent {} @NgModule({ declarations: [AdminComponent, LazyLoadedComponent], imports: [ RouterModule.forChild([ { path: '', component: AdminComponent, children: [ { path: '', canActivateChild: ['alwaysTrue'], children: [{path: '', component: LazyLoadedComponent}], }, ], }, ]), ], providers: [{provide: 'alwaysTrue', useValue: () => true}], }) class LazyLoadedModule {} const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'admin', loadChildren: () => LazyLoadedModule}]); router.navigateByUrl('/admin'); advance(fixture); expect(location.path()).toEqual('/admin'); expect(fixture.nativeElement).toHaveText('lazy-loaded'); }), )); });
{ "end_byte": 176392, "start_byte": 166056, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_176400_186060
ribe('CanLoad', () => { let canLoadRunCount = 0; beforeEach(() => { 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', useValue: () => { canLoadRunCount++; return true; }, }, ], }); }); it('should not load children when CanLoad returns false', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { @Component({ selector: 'lazy', template: 'lazy-loaded', standalone: false, }) class LazyLoadedComponent {} @NgModule({ declarations: [LazyLoadedComponent], imports: [RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])], }) class LoadedModule {} const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'lazyFalse', canLoad: ['alwaysFalse'], loadChildren: () => LoadedModule}, {path: 'lazyTrue', canLoad: ['alwaysTrue'], loadChildren: () => LoadedModule}, ]); const recordedEvents: Event[] = []; router.events.forEach((e) => recordedEvents.push(e)); // failed navigation router.navigateByUrl('/lazyFalse/loaded'); advance(fixture); expect(location.path()).toEqual(''); expectEvents(recordedEvents, [ [NavigationStart, '/lazyFalse/loaded'], // [GuardsCheckStart, '/lazyFalse/loaded'], [NavigationCancel, '/lazyFalse/loaded'], ]); expect((recordedEvents[1] as NavigationCancel).code).toBe( NavigationCancellationCode.GuardRejected, ); recordedEvents.splice(0); // successful navigation router.navigateByUrl('/lazyTrue/loaded'); advance(fixture); expect(location.path()).toEqual('/lazyTrue/loaded'); expectEvents(recordedEvents, [ [NavigationStart, '/lazyTrue/loaded'], [RouteConfigLoadStart], [RouteConfigLoadEnd], [RoutesRecognized, '/lazyTrue/loaded'], [GuardsCheckStart, '/lazyTrue/loaded'], [ChildActivationStart], [ActivationStart], [ChildActivationStart], [ActivationStart], [GuardsCheckEnd, '/lazyTrue/loaded'], [ResolveStart, '/lazyTrue/loaded'], [ResolveEnd, '/lazyTrue/loaded'], [ActivationEnd], [ChildActivationEnd], [ActivationEnd], [ChildActivationEnd], [NavigationEnd, '/lazyTrue/loaded'], ]); }), )); it('should support navigating from within the guard', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'lazyFalse', canLoad: ['returnFalseAndNavigate'], loadChildren: jasmine.createSpy('lazyFalse'), }, {path: 'blank', component: BlankCmp}, ]); const recordedEvents: Event[] = []; router.events.forEach((e) => recordedEvents.push(e)); router.navigateByUrl('/lazyFalse/loaded'); advance(fixture); expect(location.path()).toEqual('/blank'); expectEvents(recordedEvents, [ [NavigationStart, '/lazyFalse/loaded'], // No GuardCheck events as `canLoad` is a special guard that's not actually part of // the guard lifecycle. [NavigationCancel, '/lazyFalse/loaded'], [NavigationStart, '/blank'], [RoutesRecognized, '/blank'], [GuardsCheckStart, '/blank'], [ChildActivationStart], [ActivationStart], [GuardsCheckEnd, '/blank'], [ResolveStart, '/blank'], [ResolveEnd, '/blank'], [ActivationEnd], [ChildActivationEnd], [NavigationEnd, '/blank'], ]); expect((recordedEvents[1] as NavigationCancel).code).toBe( NavigationCancellationCode.SupersededByNewNavigation, ); }), )); it('should support returning UrlTree from within the guard', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'lazyFalse', canLoad: ['returnUrlTree'], loadChildren: jasmine.createSpy('lazyFalse'), }, {path: 'blank', component: BlankCmp}, ]); const recordedEvents: Event[] = []; router.events.forEach((e) => recordedEvents.push(e)); router.navigateByUrl('/lazyFalse/loaded'); advance(fixture); expect(location.path()).toEqual('/blank'); expectEvents(recordedEvents, [ [NavigationStart, '/lazyFalse/loaded'], // No GuardCheck events as `canLoad` is a special guard that's not actually part of // the guard lifecycle. [NavigationCancel, '/lazyFalse/loaded'], [NavigationStart, '/blank'], [RoutesRecognized, '/blank'], [GuardsCheckStart, '/blank'], [ChildActivationStart], [ActivationStart], [GuardsCheckEnd, '/blank'], [ResolveStart, '/blank'], [ResolveEnd, '/blank'], [ActivationEnd], [ChildActivationEnd], [NavigationEnd, '/blank'], ]); expect((recordedEvents[1] as NavigationCancel).code).toBe( NavigationCancellationCode.Redirect, ); }), )); // Regression where navigateByUrl with false CanLoad no longer resolved `false` value on // navigateByUrl promise: https://github.com/angular/angular/issues/26284 it('should resolve navigateByUrl promise after CanLoad executes', fakeAsync( inject([Router], (router: Router) => { @Component({ selector: 'lazy', template: 'lazy-loaded', standalone: false, }) class LazyLoadedComponent {} @NgModule({ declarations: [LazyLoadedComponent], imports: [RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])], }) class LazyLoadedModule {} const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'lazy-false', canLoad: ['alwaysFalse'], loadChildren: () => LazyLoadedModule}, {path: 'lazy-true', canLoad: ['alwaysTrue'], loadChildren: () => LazyLoadedModule}, ]); let navFalseResult = true; let navTrueResult = false; router.navigateByUrl('/lazy-false').then((v) => { navFalseResult = v; }); advance(fixture); router.navigateByUrl('/lazy-true').then((v) => { navTrueResult = v; }); advance(fixture); expect(navFalseResult).toBe(false); expect(navTrueResult).toBe(true); }), )); it('should execute CanLoad only once', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { @Component({ selector: 'lazy', template: 'lazy-loaded', standalone: false, }) class LazyLoadedComponent {} @NgModule({ declarations: [LazyLoadedComponent], imports: [RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])], }) class LazyLoadedModule {} const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'lazy', canLoad: ['alwaysTrue'], loadChildren: () => LazyLoadedModule}, ]); router.navigateByUrl('/lazy/loaded'); advance(fixture); expect(location.path()).toEqual('/lazy/loaded'); expect(canLoadRunCount).toEqual(1); router.navigateByUrl('/'); advance(fixture); expect(location.path()).toEqual(''); router.navigateByUrl('/lazy/loaded'); advance(fixture); expect(location.path()).toEqual('/lazy/loaded'); expect(canLoadRunCount).toEqual(1); }), ));
{ "end_byte": 186060, "start_byte": 176400, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_186070_195415
cancels guard execution when a new navigation happens', fakeAsync(() => { @Injectable({providedIn: 'root'}) class DelayedGuard { static delayedExecutions = 0; static canLoadCalls = 0; canLoad() { DelayedGuard.canLoadCalls++; return of(true).pipe( delay(1000), tap(() => { DelayedGuard.delayedExecutions++; }), ); } } const router = TestBed.inject(Router); router.resetConfig([ {path: 'a', canLoad: [DelayedGuard], loadChildren: () => [], component: SimpleCmp}, {path: 'team/:id', component: TeamCmp}, ]); const fixture = createRoot(router, RootCmp); router.navigateByUrl('/a'); tick(10); // The delayed guard should have started expect(DelayedGuard.canLoadCalls).toEqual(1); router.navigateByUrl('/team/1'); advance(fixture, 1000); expect(fixture.nativeElement.innerHTML).toContain('team'); // The delayed guard should not execute the delayed condition because a new navigation // cancels the current one and unsubscribes from intermediate results. expect(DelayedGuard.delayedExecutions).toEqual(0); })); }); describe('should run CanLoad guards concurrently', () => { function delayObservable(delayMs: number): Observable<boolean> { return of(delayMs).pipe(delay(delayMs), mapTo(true)); } let log: string[]; 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(() => { const router = TestBed.inject(Router); router.resetConfig([ { path: 'lazy', canLoad: ['guard1'], loadChildren: () => of(ModuleWithBlankCmpAsRoute), }, {path: 'redirected', component: SimpleCmp}, // canLoad should not run for this route because 'lazy' activates first { path: '', canLoad: ['returnFalseAndNavigate'], loadChildren: () => of(ModuleWithBlankCmpAsRoute), }, ]); router.navigateByUrl('/lazy'); tick(5); expect(log.length).toEqual(1); expect(log).toEqual(['guard1']); })); it('should execute canLoad guards', fakeAsync( inject([Router], (router: Router) => { router.resetConfig([ { path: 'lazy', canLoad: ['guard1', 'guard2'], loadChildren: () => ModuleWithBlankCmpAsRoute, }, ]); router.navigateByUrl('/lazy'); tick(5); expect(log.length).toEqual(2); expect(log).toEqual(['guard2', 'guard1']); }), )); it('should redirect with UrlTree if higher priority guards have resolved', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { router.resetConfig([ { path: 'lazy', canLoad: ['returnUrlTree', 'guard1', 'guard2'], loadChildren: () => ModuleWithBlankCmpAsRoute, }, {path: 'redirected', component: SimpleCmp}, ]); router.navigateByUrl('/lazy'); tick(15); expect(log.length).toEqual(3); expect(log).toEqual(['guard2', 'guard1', 'returnUrlTree']); expect(location.path()).toEqual('/redirected'); }), )); it('should redirect with UrlTree if UrlTree is lower priority', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { router.resetConfig([ { path: 'lazy', canLoad: ['guard1', 'returnUrlTree'], loadChildren: () => ModuleWithBlankCmpAsRoute, }, {path: 'redirected', component: SimpleCmp}, ]); router.navigateByUrl('/lazy'); tick(15); expect(log.length).toEqual(2); expect(log).toEqual(['guard1', 'returnUrlTree']); expect(location.path()).toEqual('/redirected'); }), )); }); describe('order', () => { class Logger { logs: string[] = []; add(thing: string) { 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], }, ], }); }); it('should call guards in the right order', fakeAsync( inject( [Router, Location, Logger], (router: Router, location: Location, logger: Logger) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: '', canActivateChild: ['canActivateChild_parent'], children: [ { path: 'team/:id', canActivate: ['canActivate_team'], canDeactivate: ['canDeactivate_team'], component: TeamCmp, }, ], }, ]); router.navigateByUrl('/team/22'); advance(fixture); router.navigateByUrl('/team/33'); advance(fixture); expect(logger.logs).toEqual([ 'canActivateChild_parent', 'canActivate_team', 'canDeactivate_team', 'canActivateChild_parent', 'canActivate_team', ]); }, ), )); it('should call deactivate guards from bottom to top', fakeAsync( inject( [Router, Location, Logger], (router: Router, location: Location, logger: Logger) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: '', children: [ { path: 'team/:id', canDeactivate: ['canDeactivate_team'], children: [ {path: '', component: SimpleCmp, canDeactivate: ['canDeactivate_simple']}, ], component: TeamCmp, }, ], }, ]); router.navigateByUrl('/team/22'); advance(fixture); router.navigateByUrl('/team/33'); advance(fixture); expect(logger.logs).toEqual(['canDeactivate_simple', 'canDeactivate_team']); }, ), )); });
{ "end_byte": 195415, "start_byte": 186070, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_195423_204312
ribe('canMatch', () => { @Injectable({providedIn: 'root'}) class ConfigurableGuard { result: Promise<boolean | UrlTree> | Observable<boolean | UrlTree> | boolean | UrlTree = false; canMatch() { return this.result; } } it('falls back to second route when canMatch returns false', fakeAsync(() => { const router = TestBed.inject(Router); router.resetConfig([ { path: 'a', canMatch: [() => coreInject(ConfigurableGuard).canMatch()], component: BlankCmp, }, {path: 'a', component: SimpleCmp}, ]); const fixture = createRoot(router, RootCmp); router.navigateByUrl('/a'); advance(fixture); expect(fixture.nativeElement.innerHTML).toContain('simple'); })); it('uses route when canMatch returns true', fakeAsync(() => { const router = TestBed.inject(Router); TestBed.inject(ConfigurableGuard).result = Promise.resolve(true); router.resetConfig([ { path: 'a', canMatch: [() => coreInject(ConfigurableGuard).canMatch()], component: SimpleCmp, }, {path: 'a', component: BlankCmp}, ]); const fixture = createRoot(router, RootCmp); router.navigateByUrl('/a'); advance(fixture); expect(fixture.nativeElement.innerHTML).toContain('simple'); })); it('can return UrlTree from canMatch guard', fakeAsync(() => { const router = TestBed.inject(Router); TestBed.inject(ConfigurableGuard).result = Promise.resolve( router.createUrlTree(['/team/1']), ); router.resetConfig([ { path: 'a', canMatch: [() => coreInject(ConfigurableGuard).canMatch()], component: SimpleCmp, }, {path: 'team/:id', component: TeamCmp}, ]); const fixture = createRoot(router, RootCmp); router.navigateByUrl('/a'); advance(fixture); expect(fixture.nativeElement.innerHTML).toContain('team'); })); it('can return UrlTree from CanMatchFn guard', fakeAsync(() => { const canMatchTeamSection = new InjectionToken('CanMatchTeamSection'); const canMatchFactory: (router: Router) => CanMatchFn = (router: Router) => () => router.createUrlTree(['/team/1']); TestBed.overrideProvider(canMatchTeamSection, { useFactory: canMatchFactory, deps: [Router], }); const router = TestBed.inject(Router); router.resetConfig([ {path: 'a', canMatch: [canMatchTeamSection], component: SimpleCmp}, {path: 'team/:id', component: TeamCmp}, ]); const fixture = createRoot(router, RootCmp); router.navigateByUrl('/a'); advance(fixture); expect(fixture.nativeElement.innerHTML).toContain('team'); })); it('runs canMatch guards provided in lazy module', fakeAsync(() => { const router = TestBed.inject(Router); @Component({ selector: 'lazy', template: 'lazy-loaded-parent [<router-outlet></router-outlet>]', standalone: false, }) class ParentLazyLoadedComponent {} @Component({ selector: 'lazy', template: 'lazy-loaded-child', standalone: false, }) class ChildLazyLoadedComponent {} @Injectable() class LazyCanMatchFalse { canMatch() { return false; } } @Component({ template: 'restricted', standalone: false, }) class Restricted {} @NgModule({ declarations: [ParentLazyLoadedComponent, ChildLazyLoadedComponent, Restricted], providers: [LazyCanMatchFalse], imports: [ RouterModule.forChild([ { path: 'loaded', canMatch: [LazyCanMatchFalse], component: Restricted, children: [{path: 'child', component: Restricted}], }, { path: 'loaded', component: ParentLazyLoadedComponent, children: [{path: 'child', component: ChildLazyLoadedComponent}], }, ]), ], }) class LoadedModule {} const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]); router.navigateByUrl('/lazy/loaded/child'); advance(fixture); expect(TestBed.inject(Location).path()).toEqual('/lazy/loaded/child'); expect(fixture.nativeElement).toHaveText('lazy-loaded-parent [lazy-loaded-child]'); })); it('cancels guard execution when a new navigation happens', fakeAsync(() => { @Injectable({providedIn: 'root'}) class DelayedGuard { static delayedExecutions = 0; canMatch() { return of(true).pipe( delay(1000), tap(() => { DelayedGuard.delayedExecutions++; }), ); } } const router = TestBed.inject(Router); const delayedGuardSpy = spyOn(TestBed.inject(DelayedGuard), 'canMatch'); delayedGuardSpy.and.callThrough(); const configurableMatchSpy = spyOn(TestBed.inject(ConfigurableGuard), 'canMatch'); configurableMatchSpy.and.callFake(() => { router.navigateByUrl('/team/1'); return false; }); router.resetConfig([ {path: 'a', canMatch: [ConfigurableGuard, DelayedGuard], component: SimpleCmp}, {path: 'a', canMatch: [ConfigurableGuard, DelayedGuard], component: SimpleCmp}, {path: 'a', canMatch: [ConfigurableGuard, DelayedGuard], component: SimpleCmp}, {path: 'team/:id', component: TeamCmp}, ]); const fixture = createRoot(router, RootCmp); router.navigateByUrl('/a'); advance(fixture); expect(fixture.nativeElement.innerHTML).toContain('team'); expect(configurableMatchSpy.calls.count()).toEqual(1); // The delayed guard should not execute the delayed condition because the other guard // initiates a new navigation, which cancels the current one and unsubscribes from // intermediate results. expect(DelayedGuard.delayedExecutions).toEqual(0); // The delayed guard should still have executed once because guards are executed at the // same time expect(delayedGuardSpy.calls.count()).toEqual(1); })); }); it('should allow guards as functions', fakeAsync(() => { @Component({ template: '', standalone: true, }) class BlankCmp {} const router = TestBed.inject(Router); const fixture = createRoot(router, RootCmp); const guards = { canActivate() { return true; }, canDeactivate() { return true; }, canActivateChild() { return true; }, canMatch() { return true; }, canLoad() { return true; }, }; spyOn(guards, 'canActivate').and.callThrough(); spyOn(guards, 'canActivateChild').and.callThrough(); spyOn(guards, 'canDeactivate').and.callThrough(); spyOn(guards, 'canLoad').and.callThrough(); spyOn(guards, 'canMatch').and.callThrough(); router.resetConfig([ { path: '', component: BlankCmp, loadChildren: () => [{path: '', component: BlankCmp}], canActivate: [guards.canActivate], canActivateChild: [guards.canActivateChild], canLoad: [guards.canLoad], canDeactivate: [guards.canDeactivate], canMatch: [guards.canMatch], }, { path: 'other', component: BlankCmp, }, ]); router.navigateByUrl('/'); advance(fixture); expect(guards.canMatch).toHaveBeenCalled(); expect(guards.canLoad).toHaveBeenCalled(); expect(guards.canActivate).toHaveBeenCalled(); expect(guards.canActivateChild).toHaveBeenCalled(); router.navigateByUrl('/other'); advance(fixture); expect(guards.canDeactivate).toHaveBeenCalled(); }));
{ "end_byte": 204312, "start_byte": 195423, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_204320_212812
should allow DI in plain function guards', fakeAsync(() => { @Component({ template: '', standalone: true, }) class BlankCmp {} @Injectable({providedIn: 'root'}) class State { value = true; } const router = TestBed.inject(Router); const fixture = createRoot(router, RootCmp); const guards = { canActivate() { return coreInject(State).value; }, canDeactivate() { return coreInject(State).value; }, canActivateChild() { return coreInject(State).value; }, canMatch() { return coreInject(State).value; }, canLoad() { return coreInject(State).value; }, }; spyOn(guards, 'canActivate').and.callThrough(); spyOn(guards, 'canActivateChild').and.callThrough(); spyOn(guards, 'canDeactivate').and.callThrough(); spyOn(guards, 'canLoad').and.callThrough(); spyOn(guards, 'canMatch').and.callThrough(); router.resetConfig([ { path: '', component: BlankCmp, loadChildren: () => [{path: '', component: BlankCmp}], canActivate: [guards.canActivate], canActivateChild: [guards.canActivateChild], canLoad: [guards.canLoad], canDeactivate: [guards.canDeactivate], canMatch: [guards.canMatch], }, { path: 'other', component: BlankCmp, }, ]); router.navigateByUrl('/'); advance(fixture); expect(guards.canMatch).toHaveBeenCalled(); expect(guards.canLoad).toHaveBeenCalled(); expect(guards.canActivate).toHaveBeenCalled(); expect(guards.canActivateChild).toHaveBeenCalled(); router.navigateByUrl('/other'); advance(fixture); expect(guards.canDeactivate).toHaveBeenCalled(); })); it('can run functional guards serially', fakeAsync(() => { function runSerially( guards: CanActivateFn[] | CanActivateChildFn[], ): CanActivateFn | CanActivateChildFn { return (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => { const injector = coreInject(EnvironmentInjector); const observables = guards.map((guard) => { const guardResult = injector.runInContext(() => guard(route, state)); return wrapIntoObservable(guardResult).pipe(first()); }); return concat(...observables).pipe( takeWhile((v) => v === true), last(), ); }; } const guardDone: string[] = []; const guard1: CanActivateFn = () => of(true).pipe( delay(100), tap(() => guardDone.push('guard1')), ); const guard2: CanActivateFn = () => of(true).pipe(tap(() => guardDone.push('guard2'))); const guard3: CanActivateFn = () => of(true).pipe( delay(50), tap(() => guardDone.push('guard3')), ); const guard4: CanActivateFn = () => of(true).pipe( delay(200), tap(() => guardDone.push('guard4')), ); const router = TestBed.inject(Router); router.resetConfig([ { path: '**', component: BlankCmp, canActivate: [runSerially([guard1, guard2, guard3, guard4])], }, ]); router.navigateByUrl(''); tick(100); expect(guardDone).toEqual(['guard1', 'guard2']); tick(50); expect(guardDone).toEqual(['guard1', 'guard2', 'guard3']); tick(200); expect(guardDone).toEqual(['guard1', 'guard2', 'guard3', 'guard4']); })); }); describe('route events', () => { it('should fire matching (Child)ActivationStart/End events', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'user/:name', component: UserCmp}]); const recordedEvents: Event[] = []; router.events.forEach((e) => recordedEvents.push(e)); router.navigateByUrl('/user/fedor'); advance(fixture); const event3 = recordedEvents[3] as ChildActivationStart; const event9 = recordedEvents[9] as ChildActivationEnd; expect(fixture.nativeElement).toHaveText('user fedor'); expect(event3 instanceof ChildActivationStart).toBe(true); expect(event3.snapshot).toBe(event9.snapshot.root); expect(event9 instanceof ChildActivationEnd).toBe(true); expect(event9.snapshot).toBe(event9.snapshot.root); const event4 = recordedEvents[4] as ActivationStart; const event8 = recordedEvents[8] as ActivationEnd; expect(event4 instanceof ActivationStart).toBe(true); expect(event4.snapshot.routeConfig?.path).toBe('user/:name'); expect(event8 instanceof ActivationEnd).toBe(true); expect(event8.snapshot.routeConfig?.path).toBe('user/:name'); expectEvents(recordedEvents, [ [NavigationStart, '/user/fedor'], [RoutesRecognized, '/user/fedor'], [GuardsCheckStart, '/user/fedor'], [ChildActivationStart], [ActivationStart], [GuardsCheckEnd, '/user/fedor'], [ResolveStart, '/user/fedor'], [ResolveEnd, '/user/fedor'], [ActivationEnd], [ChildActivationEnd], [NavigationEnd, '/user/fedor'], ]); }), )); it('should allow redirection in NavigationStart', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'blank', component: UserCmp}, {path: 'user/:name', component: BlankCmp}, ]); const navigateSpy = spyOn(router, 'navigate').and.callThrough(); const recordedEvents: Event[] = []; const navStart$ = router.events.pipe( tap((e) => recordedEvents.push(e)), filter((e): e is NavigationStart => e instanceof NavigationStart), first(), ); navStart$.subscribe((e: NavigationStart | NavigationError) => { router.navigate(['/blank'], { queryParams: {state: 'redirected'}, queryParamsHandling: 'merge', }); advance(fixture); }); router.navigate(['/user/:fedor']); advance(fixture); expect(navigateSpy.calls.mostRecent().args[1]!.queryParams); }), )); it('should stop emitting events after the router is destroyed', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'user/:name', component: UserCmp}]); let events = 0; const subscription = router.events.subscribe(() => events++); router.navigateByUrl('/user/frodo'); advance(fixture); expect(events).toBeGreaterThan(0); const previousCount = events; router.dispose(); router.navigateByUrl('/user/bilbo'); advance(fixture); expect(events).toBe(previousCount); subscription.unsubscribe(); }), )); it('should resolve navigation promise with false after the router is destroyed', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); let result = null as boolean | null; const callback = (r: boolean) => (result = r); router.resetConfig([{path: 'user/:name', component: UserCmp}]); router.navigateByUrl('/user/frodo').then(callback); advance(fixture); expect(result).toBe(true); result = null as boolean | null; router.dispose(); router.navigateByUrl('/user/bilbo').then(callback); advance(fixture); expect(result).toBe(false); result = null as boolean | null; router.navigate(['/user/bilbo']).then(callback); advance(fixture); expect(result).toBe(false); }), )); });
{ "end_byte": 212812, "start_byte": 204320, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_212818_222904
ribe('routerLinkActive', () => { it('should set the class when the link is active (a tag)', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ { path: 'link', component: DummyLinkCmp, children: [ {path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}, ], }, ], }, ]); router.navigateByUrl('/team/22/link;exact=true'); advance(fixture); advance(fixture); expect(location.path()).toEqual('/team/22/link;exact=true'); const nativeLink = fixture.nativeElement.querySelector('a'); const nativeButton = fixture.nativeElement.querySelector('button'); expect(nativeLink.className).toEqual('active'); expect(nativeButton.className).toEqual('active'); router.navigateByUrl('/team/22/link/simple'); advance(fixture); expect(location.path()).toEqual('/team/22/link/simple'); expect(nativeLink.className).toEqual(''); expect(nativeButton.className).toEqual(''); }), )); it('should not set the class until the first navigation succeeds', fakeAsync(() => { @Component({ template: '<router-outlet></router-outlet><a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}" ></a>', standalone: false, }) class RootCmpWithLink {} TestBed.configureTestingModule({declarations: [RootCmpWithLink]}); const router: Router = TestBed.inject(Router); const f = TestBed.createComponent(RootCmpWithLink); advance(f); const link = f.nativeElement.querySelector('a'); expect(link.className).toEqual(''); router.initialNavigation(); advance(f); expect(link.className).toEqual('active'); })); it('should set the class on a parent element when the link is active', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ { path: 'link', component: DummyLinkWithParentCmp, children: [ {path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}, ], }, ], }, ]); router.navigateByUrl('/team/22/link;exact=true'); advance(fixture); advance(fixture); expect(location.path()).toEqual('/team/22/link;exact=true'); const native = fixture.nativeElement.querySelector('#link-parent'); expect(native.className).toEqual('active'); router.navigateByUrl('/team/22/link/simple'); advance(fixture); expect(location.path()).toEqual('/team/22/link/simple'); expect(native.className).toEqual(''); }), )); it('should set the class when the link is active', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ { path: 'link', component: DummyLinkCmp, children: [ {path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}, ], }, ], }, ]); router.navigateByUrl('/team/22/link'); advance(fixture); advance(fixture); expect(location.path()).toEqual('/team/22/link'); const native = fixture.nativeElement.querySelector('a'); expect(native.className).toEqual('active'); router.navigateByUrl('/team/22/link/simple'); advance(fixture); expect(location.path()).toEqual('/team/22/link/simple'); expect(native.className).toEqual('active'); }), )); it('should expose an isActive property', fakeAsync(() => { @Component({ template: `<a routerLink="/team" routerLinkActive #rla="routerLinkActive"></a> <p>{{rla.isActive}}</p> <span *ngIf="rla.isActive"></span> <span [ngClass]="{'highlight': rla.isActive}"></span> <router-outlet></router-outlet>`, standalone: false, }) class ComponentWithRouterLink {} TestBed.configureTestingModule({declarations: [ComponentWithRouterLink]}); const router: Router = TestBed.inject(Router); router.resetConfig([ { path: 'team', component: TeamCmp, }, { path: 'otherteam', component: TeamCmp, }, ]); const fixture = TestBed.createComponent(ComponentWithRouterLink); router.navigateByUrl('/team'); expect(() => advance(fixture)).not.toThrow(); advance(fixture); const paragraph = fixture.nativeElement.querySelector('p'); expect(paragraph.textContent).toEqual('true'); router.navigateByUrl('/otherteam'); advance(fixture); advance(fixture); expect(paragraph.textContent).toEqual('false'); })); it('should not trigger change detection when active state has not changed', fakeAsync(() => { @Component({ template: `<div id="link" routerLinkActive="active" [routerLink]="link"></div>`, standalone: false, }) class LinkComponent { link = 'notactive'; } @Component({ template: '', standalone: false, }) class SimpleComponent {} TestBed.configureTestingModule({ imports: [...ROUTER_DIRECTIVES], providers: [provideRouter([{path: '', component: SimpleComponent}])], declarations: [LinkComponent, SimpleComponent], }); const fixture = createRoot(TestBed.inject(Router), LinkComponent); fixture.componentInstance.link = 'stillnotactive'; fixture.detectChanges(false /** checkNoChanges */); expect(TestBed.inject(NgZone).hasPendingMicrotasks).toBe(false); })); it('should emit on isActiveChange output when link is activated or inactivated', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ { path: 'link', component: DummyLinkCmp, children: [ {path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}, ], }, ], }, ]); router.navigateByUrl('/team/22/link;exact=true'); advance(fixture); advance(fixture); expect(location.path()).toEqual('/team/22/link;exact=true'); const linkComponent = fixture.debugElement.query(By.directive(DummyLinkCmp)) .componentInstance as DummyLinkCmp; expect(linkComponent.isLinkActivated).toEqual(true); const nativeLink = fixture.nativeElement.querySelector('a'); const nativeButton = fixture.nativeElement.querySelector('button'); expect(nativeLink.className).toEqual('active'); expect(nativeButton.className).toEqual('active'); router.navigateByUrl('/team/22/link/simple'); advance(fixture); expect(location.path()).toEqual('/team/22/link/simple'); expect(linkComponent.isLinkActivated).toEqual(false); expect(nativeLink.className).toEqual(''); expect(nativeButton.className).toEqual(''); }), )); it('should set a provided aria-current attribute when the link is active (a tag)', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ { path: 'link', component: DummyLinkCmp, children: [ {path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}, ], }, ], }, ]); router.navigateByUrl('/team/22/link;exact=true'); advance(fixture); advance(fixture); expect(location.path()).toEqual('/team/22/link;exact=true'); const nativeLink = fixture.nativeElement.querySelector('a'); const nativeButton = fixture.nativeElement.querySelector('button'); expect(nativeLink.getAttribute('aria-current')).toEqual('page'); expect(nativeButton.hasAttribute('aria-current')).toEqual(false); router.navigateByUrl('/team/22/link/simple'); advance(fixture); expect(location.path()).toEqual('/team/22/link/simple'); expect(nativeLink.hasAttribute('aria-current')).toEqual(false); expect(nativeButton.hasAttribute('aria-current')).toEqual(false); }), )); });
{ "end_byte": 222904, "start_byte": 212818, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_222910_232773
ribe('lazy loading', () => { it('works', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { @Component({ selector: 'lazy', template: 'lazy-loaded-parent [<router-outlet></router-outlet>]', standalone: false, }) class ParentLazyLoadedComponent {} @Component({ selector: 'lazy', template: 'lazy-loaded-child', standalone: false, }) class ChildLazyLoadedComponent {} @NgModule({ declarations: [ParentLazyLoadedComponent, ChildLazyLoadedComponent], imports: [ RouterModule.forChild([ { path: 'loaded', component: ParentLazyLoadedComponent, children: [{path: 'child', component: ChildLazyLoadedComponent}], }, ]), ], }) class LoadedModule {} const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]); router.navigateByUrl('/lazy/loaded/child'); advance(fixture); expect(location.path()).toEqual('/lazy/loaded/child'); expect(fixture.nativeElement).toHaveText('lazy-loaded-parent [lazy-loaded-child]'); }), )); it('should have 2 injector trees: module and element', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { @Component({ selector: 'lazy', template: 'parent[<router-outlet></router-outlet>]', viewProviders: [{provide: 'shadow', useValue: 'from parent component'}], standalone: false, }) class Parent {} @Component({ selector: 'lazy', template: 'child', standalone: false, }) class Child {} @NgModule({ declarations: [Parent], imports: [ RouterModule.forChild([ { path: 'parent', component: Parent, children: [{path: 'child', loadChildren: () => ChildModule}], }, ]), ], providers: [ {provide: 'moduleName', useValue: 'parent'}, {provide: 'fromParent', useValue: 'from parent'}, ], }) class ParentModule {} @NgModule({ declarations: [Child], imports: [RouterModule.forChild([{path: '', component: Child}])], providers: [ {provide: 'moduleName', useValue: 'child'}, {provide: 'fromChild', useValue: 'from child'}, {provide: 'shadow', useValue: 'from child module'}, ], }) class ChildModule {} const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: () => ParentModule}]); router.navigateByUrl('/lazy/parent/child'); advance(fixture); expect(location.path()).toEqual('/lazy/parent/child'); expect(fixture.nativeElement).toHaveText('parent[child]'); const pInj = fixture.debugElement.query(By.directive(Parent)).injector!; const cInj = fixture.debugElement.query(By.directive(Child)).injector!; expect(pInj.get('moduleName')).toEqual('parent'); expect(pInj.get('fromParent')).toEqual('from parent'); expect(pInj.get(Parent)).toBeInstanceOf(Parent); expect(pInj.get('fromChild', null)).toEqual(null); expect(pInj.get(Child, null)).toEqual(null); expect(cInj.get('moduleName')).toEqual('child'); expect(cInj.get('fromParent')).toEqual('from parent'); expect(cInj.get('fromChild')).toEqual('from child'); expect(cInj.get(Parent)).toBeInstanceOf(Parent); expect(cInj.get(Child)).toBeInstanceOf(Child); // The child module can not shadow the parent component expect(cInj.get('shadow')).toEqual('from parent component'); const pmInj = pInj.get(NgModuleRef).injector; const cmInj = cInj.get(NgModuleRef).injector; expect(pmInj.get('moduleName')).toEqual('parent'); expect(cmInj.get('moduleName')).toEqual('child'); expect(pmInj.get(Parent, '-')).toEqual('-'); expect(cmInj.get(Parent, '-')).toEqual('-'); expect(pmInj.get(Child, '-')).toEqual('-'); expect(cmInj.get(Child, '-')).toEqual('-'); }), )); // https://github.com/angular/angular/issues/12889 it('should create a single instance of lazy-loaded modules', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { @Component({ selector: 'lazy', template: 'lazy-loaded-parent [<router-outlet></router-outlet>]', standalone: false, }) class ParentLazyLoadedComponent {} @Component({ selector: 'lazy', template: 'lazy-loaded-child', standalone: false, }) class ChildLazyLoadedComponent {} @NgModule({ declarations: [ParentLazyLoadedComponent, ChildLazyLoadedComponent], imports: [ RouterModule.forChild([ { path: 'loaded', component: ParentLazyLoadedComponent, children: [{path: 'child', component: ChildLazyLoadedComponent}], }, ]), ], }) class LoadedModule { static instances = 0; constructor() { LoadedModule.instances++; } } const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]); router.navigateByUrl('/lazy/loaded/child'); advance(fixture); expect(fixture.nativeElement).toHaveText('lazy-loaded-parent [lazy-loaded-child]'); expect(LoadedModule.instances).toEqual(1); }), )); // https://github.com/angular/angular/issues/13870 it('should create a single instance of guards for lazy-loaded modules', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { @Injectable() class Service {} @Injectable() class Resolver { constructor(public service: Service) {} resolve() { return this.service; } } @Component({ selector: 'lazy', template: 'lazy', standalone: false, }) class LazyLoadedComponent { resolvedService: Service; constructor( public injectedService: Service, route: ActivatedRoute, ) { this.resolvedService = route.snapshot.data['service']; } } @NgModule({ declarations: [LazyLoadedComponent], providers: [Service, Resolver], imports: [ RouterModule.forChild([ { path: 'loaded', component: LazyLoadedComponent, resolve: {'service': () => coreInject(Resolver).resolve()}, }, ]), ], }) class LoadedModule {} const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]); router.navigateByUrl('/lazy/loaded'); advance(fixture); expect(fixture.nativeElement).toHaveText('lazy'); const lzc = fixture.debugElement.query( By.directive(LazyLoadedComponent), ).componentInstance; expect(lzc.injectedService).toBe(lzc.resolvedService); }), )); it('should emit RouteConfigLoadStart and RouteConfigLoadEnd event when route is lazy loaded', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { @Component({ selector: 'lazy', template: 'lazy-loaded-parent [<router-outlet></router-outlet>]', standalone: false, }) class ParentLazyLoadedComponent {} @Component({ selector: 'lazy', template: 'lazy-loaded-child', standalone: false, }) class ChildLazyLoadedComponent {} @NgModule({ declarations: [ParentLazyLoadedComponent, ChildLazyLoadedComponent], imports: [ RouterModule.forChild([ { path: 'loaded', component: ParentLazyLoadedComponent, children: [{path: 'child', component: ChildLazyLoadedComponent}], }, ]), ], }) class LoadedModule {} const events: Array<RouteConfigLoadStart | RouteConfigLoadEnd> = []; router.events.subscribe((e) => { if (e instanceof RouteConfigLoadStart || e instanceof RouteConfigLoadEnd) { events.push(e); } }); const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]); router.navigateByUrl('/lazy/loaded/child'); advance(fixture); expect(events.length).toEqual(2); expect(events[0].toString()).toEqual('RouteConfigLoadStart(path: lazy)'); expect(events[1].toString()).toEqual('RouteConfigLoadEnd(path: lazy)'); }), ));
{ "end_byte": 232773, "start_byte": 222910, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_232781_242079
throws an error when forRoot() is used in a lazy context', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { @Component({ selector: 'lazy', template: 'should not show', standalone: false, }) class LazyLoadedComponent {} @NgModule({ declarations: [LazyLoadedComponent], imports: [RouterModule.forRoot([{path: 'loaded', component: LazyLoadedComponent}])], }) class LoadedModule {} const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]); let recordedError: any = null; router.navigateByUrl('/lazy/loaded')!.catch((err) => (recordedError = err)); advance(fixture); expect(recordedError.message).toContain(`NG04007`); }), )); it('should combine routes from multiple modules into a single configuration', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { @Component({ selector: 'lazy', template: 'lazy-loaded-2', standalone: false, }) class LazyComponent2 {} @NgModule({ declarations: [LazyComponent2], imports: [RouterModule.forChild([{path: 'loaded', component: LazyComponent2}])], }) class SiblingOfLoadedModule {} @Component({ selector: 'lazy', template: 'lazy-loaded-1', standalone: false, }) class LazyComponent1 {} @NgModule({ declarations: [LazyComponent1], imports: [ RouterModule.forChild([{path: 'loaded', component: LazyComponent1}]), SiblingOfLoadedModule, ], }) class LoadedModule {} const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'lazy1', loadChildren: () => LoadedModule}, {path: 'lazy2', loadChildren: () => SiblingOfLoadedModule}, ]); router.navigateByUrl('/lazy1/loaded'); advance(fixture); expect(location.path()).toEqual('/lazy1/loaded'); router.navigateByUrl('/lazy2/loaded'); advance(fixture); expect(location.path()).toEqual('/lazy2/loaded'); }), )); it('should allow lazy loaded module in named outlet', fakeAsync( inject([Router], (router: Router) => { @Component({ selector: 'lazy', template: 'lazy-loaded', standalone: false, }) class LazyComponent {} @NgModule({ declarations: [LazyComponent], imports: [RouterModule.forChild([{path: '', component: LazyComponent}])], }) class LazyLoadedModule {} const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'lazy', loadChildren: () => LazyLoadedModule, outlet: 'right'}, ], }, ]); router.navigateByUrl('/team/22/user/john'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ user john, right: ]'); router.navigateByUrl('/team/22/(user/john//right:lazy)'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ user john, right: lazy-loaded ]'); }), )); it('should allow componentless named outlet to render children', fakeAsync( inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'simple', outlet: 'right', children: [{path: '', component: SimpleCmp}]}, ], }, ]); router.navigateByUrl('/team/22/user/john'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ user john, right: ]'); router.navigateByUrl('/team/22/(user/john//right:simple)'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ user john, right: simple ]'); }), )); it('should render loadComponent named outlet with children', fakeAsync(() => { const router = TestBed.inject(Router); const fixture = createRoot(router, RootCmp); @Component({ standalone: true, imports: [RouterModule], template: '[right outlet component: <router-outlet></router-outlet>]', }) class RightComponent { constructor(readonly route: ActivatedRoute) {} } const loadSpy = jasmine.createSpy(); loadSpy.and.returnValue(RightComponent); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, { path: 'simple', loadComponent: loadSpy, outlet: 'right', children: [{path: '', component: SimpleCmp}], }, ], }, {path: '', component: SimpleCmp}, ]); router.navigateByUrl('/team/22/(user/john//right:simple)'); advance(fixture); expect(fixture.nativeElement).toHaveText( 'team 22 [ user john, right: [right outlet component: simple] ]', ); const rightCmp: RightComponent = fixture.debugElement.query( By.directive(RightComponent), ).componentInstance; // Ensure we don't accidentally add `EmptyOutletComponent` via `standardizeConfig` expect(rightCmp.route.routeConfig?.component).not.toBeDefined(); // Ensure we can navigate away and come back router.navigateByUrl('/'); advance(fixture); router.navigateByUrl('/team/22/(user/john//right:simple)'); advance(fixture); expect(fixture.nativeElement).toHaveText( 'team 22 [ user john, right: [right outlet component: simple] ]', ); expect(loadSpy.calls.count()).toEqual(1); })); describe('should use the injector of the lazily-loaded configuration', () => { class LazyLoadedServiceDefinedInModule {} @Component({ selector: 'eager-parent', template: 'eager-parent <router-outlet></router-outlet>', standalone: false, }) class EagerParentComponent {} @Component({ selector: 'lazy-parent', template: 'lazy-parent <router-outlet></router-outlet>', standalone: false, }) class LazyParentComponent {} @Component({ selector: 'lazy-child', template: 'lazy-child', standalone: false, }) class LazyChildComponent { constructor( lazy: LazyParentComponent, // should be able to inject lazy/direct parent lazyService: LazyLoadedServiceDefinedInModule, // should be able to inject lazy service eager: EagerParentComponent, // should use the injector of the location to create a // parent ) {} } @NgModule({ declarations: [LazyParentComponent, LazyChildComponent], imports: [ RouterModule.forChild([ { path: '', children: [ { path: 'lazy-parent', component: LazyParentComponent, children: [{path: 'lazy-child', component: LazyChildComponent}], }, ], }, ]), ], providers: [LazyLoadedServiceDefinedInModule], }) class LoadedModule {} @NgModule({declarations: [EagerParentComponent], imports: [RouterModule.forRoot([])]}) class TestModule {} beforeEach(() => { TestBed.configureTestingModule({ imports: [TestModule], }); }); it('should use the injector of the lazily-loaded configuration', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'eager-parent', component: EagerParentComponent, children: [{path: 'lazy', loadChildren: () => LoadedModule}], }, ]); router.navigateByUrl('/eager-parent/lazy/lazy-parent/lazy-child'); advance(fixture); expect(location.path()).toEqual('/eager-parent/lazy/lazy-parent/lazy-child'); expect(fixture.nativeElement).toHaveText('eager-parent lazy-parent lazy-child'); }), )); });
{ "end_byte": 242079, "start_byte": 232781, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_242087_249441
works when given a callback', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { @Component({ selector: 'lazy', template: 'lazy-loaded', standalone: false, }) class LazyLoadedComponent {} @NgModule({ declarations: [LazyLoadedComponent], imports: [RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])], }) class LoadedModule {} const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]); router.navigateByUrl('/lazy/loaded'); advance(fixture); expect(location.path()).toEqual('/lazy/loaded'); expect(fixture.nativeElement).toHaveText('lazy-loaded'); }), )); it('error emit an error when cannot load a config', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'lazy', loadChildren: () => { throw new Error('invalid'); }, }, ]); const recordedEvents: Event[] = []; router.events.forEach((e) => recordedEvents.push(e)); router.navigateByUrl('/lazy/loaded')!.catch((s) => {}); advance(fixture); expect(location.path()).toEqual(''); expectEvents(recordedEvents, [ [NavigationStart, '/lazy/loaded'], [RouteConfigLoadStart], [NavigationError, '/lazy/loaded'], ]); }), )); it('should emit an error when the lazily-loaded config is not valid', fakeAsync(() => { const router = TestBed.inject(Router); @NgModule({imports: [RouterModule.forChild([{path: 'loaded'}])]}) class LoadedModule {} const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]); let recordedError: any = null; router.navigateByUrl('/lazy/loaded').catch((err) => (recordedError = err)); advance(fixture); expect(recordedError.message).toContain( `Invalid configuration of route 'lazy/loaded'. One of the following must be provided: component, loadComponent, redirectTo, children or loadChildren`, ); })); it('should work with complex redirect rules', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { @Component({ selector: 'lazy', template: 'lazy-loaded', standalone: false, }) class LazyLoadedComponent {} @NgModule({ declarations: [LazyLoadedComponent], imports: [RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])], }) class LoadedModule {} const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'lazy', loadChildren: () => LoadedModule}, {path: '**', redirectTo: 'lazy'}, ]); router.navigateByUrl('/lazy/loaded'); advance(fixture); expect(location.path()).toEqual('/lazy/loaded'); }), )); it('should work with wildcard route', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { @Component({ selector: 'lazy', template: 'lazy-loaded', standalone: false, }) class LazyLoadedComponent {} @NgModule({ declarations: [LazyLoadedComponent], imports: [RouterModule.forChild([{path: '', component: LazyLoadedComponent}])], }) class LazyLoadedModule {} const fixture = createRoot(router, RootCmp); router.resetConfig([{path: '**', loadChildren: () => LazyLoadedModule}]); router.navigateByUrl('/lazy'); advance(fixture); expect(location.path()).toEqual('/lazy'); expect(fixture.nativeElement).toHaveText('lazy-loaded'); }), )); describe('preloading', () => { let log: string[] = []; @Component({ selector: 'lazy', template: 'should not show', standalone: false, }) class LazyLoadedComponent {} @NgModule({ declarations: [LazyLoadedComponent], imports: [ RouterModule.forChild([{path: 'LoadedModule2', component: LazyLoadedComponent}]), ], }) class LoadedModule2 {} @NgModule({ imports: [ RouterModule.forChild([{path: 'LoadedModule1', loadChildren: () => LoadedModule2}]), ], }) class LoadedModule1 {} @NgModule({}) class EmptyModule {} beforeEach(() => { log.length = 0; TestBed.configureTestingModule({ providers: [ {provide: PreloadingStrategy, useExisting: PreloadAllModules}, { provide: 'loggingReturnsTrue', useValue: () => { log.push('loggingReturnsTrue'); return true; }, }, ], }); const preloader = TestBed.inject(RouterPreloader); preloader.setUpPreloading(); }); it('should work', fakeAsync(() => { const router = TestBed.inject(Router); const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'blank', component: BlankCmp}, {path: 'lazy', loadChildren: () => LoadedModule1}, ]); router.navigateByUrl('/blank'); advance(fixture); const config = router.config; const firstRoutes = getLoadedRoutes(config[1])!; expect(firstRoutes).toBeDefined(); expect(firstRoutes[0].path).toEqual('LoadedModule1'); const secondRoutes = getLoadedRoutes(firstRoutes[0])!; expect(secondRoutes).toBeDefined(); expect(secondRoutes[0].path).toEqual('LoadedModule2'); })); it('should not preload when canLoad is present and does not execute guard', fakeAsync(() => { const router = TestBed.inject(Router); const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'blank', component: BlankCmp}, {path: 'lazy', loadChildren: () => LoadedModule1, canLoad: ['loggingReturnsTrue']}, ]); router.navigateByUrl('/blank'); advance(fixture); const config = router.config; const firstRoutes = getLoadedRoutes(config[1])!; expect(firstRoutes).toBeUndefined(); expect(log.length).toBe(0); })); it('should allow navigation to modules with no routes', fakeAsync(() => { const router = TestBed.inject(Router); const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: () => EmptyModule}]); router.navigateByUrl('/lazy'); advance(fixture); })); });
{ "end_byte": 249441, "start_byte": 242087, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_249449_259036
ribe('custom url handling strategies', () => { class CustomUrlHandlingStrategy implements UrlHandlingStrategy { shouldProcessUrl(url: UrlTree): boolean { return url.toString().startsWith('/include') || url.toString() === '/'; } extract(url: UrlTree): UrlTree { const oldRoot = url.root; const children: Record<string, UrlSegmentGroup> = {}; if (oldRoot.children[PRIMARY_OUTLET]) { children[PRIMARY_OUTLET] = oldRoot.children[PRIMARY_OUTLET]; } const root = new UrlSegmentGroup(oldRoot.segments, children); return new UrlTree(root, url.queryParams, url.fragment); } merge(newUrlPart: UrlTree, wholeUrl: UrlTree): UrlTree { const oldRoot = newUrlPart.root; const children: Record<string, UrlSegmentGroup> = {}; if (oldRoot.children[PRIMARY_OUTLET]) { children[PRIMARY_OUTLET] = oldRoot.children[PRIMARY_OUTLET]; } Object.entries(wholeUrl.root.children).forEach(([k, v]: [string, any]) => { if (k !== PRIMARY_OUTLET) { children[k] = v; } v.parent = this; }); const root = new UrlSegmentGroup(oldRoot.segments, children); return new UrlTree(root, newUrlPart.queryParams, newUrlPart.fragment); } } beforeEach(() => { TestBed.configureTestingModule({ providers: [ {provide: UrlHandlingStrategy, useClass: CustomUrlHandlingStrategy}, {provide: LocationStrategy, useClass: HashLocationStrategy}, ], }); }); it('should work', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'include', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'simple', component: SimpleCmp}, ], }, ]); const events: Event[] = []; router.events.subscribe((e) => e instanceof RouterEvent && events.push(e)); // supported URL router.navigateByUrl('/include/user/kate'); advance(fixture); expect(location.path()).toEqual('/include/user/kate'); expectEvents(events, [ [NavigationStart, '/include/user/kate'], [RoutesRecognized, '/include/user/kate'], [GuardsCheckStart, '/include/user/kate'], [GuardsCheckEnd, '/include/user/kate'], [ResolveStart, '/include/user/kate'], [ResolveEnd, '/include/user/kate'], [NavigationEnd, '/include/user/kate'], ]); expect(fixture.nativeElement).toHaveText('team [ user kate, right: ]'); events.splice(0); // unsupported URL router.navigateByUrl('/exclude/one'); advance(fixture); expect(location.path()).toEqual('/exclude/one'); expect(Object.keys(router.routerState.root.children).length).toEqual(0); expect(fixture.nativeElement).toHaveText(''); expectEvents(events, [ [NavigationStart, '/exclude/one'], [GuardsCheckStart, '/exclude/one'], [GuardsCheckEnd, '/exclude/one'], [NavigationEnd, '/exclude/one'], ]); events.splice(0); // another unsupported URL location.go('/exclude/two'); location.historyGo(0); advance(fixture); expect(location.path()).toEqual('/exclude/two'); expectEvents(events, [[NavigationSkipped, '/exclude/two']]); events.splice(0); // back to a supported URL location.go('/include/simple'); location.historyGo(0); advance(fixture); expect(location.path()).toEqual('/include/simple'); expect(fixture.nativeElement).toHaveText('team [ simple, right: ]'); expectEvents(events, [ [NavigationStart, '/include/simple'], [RoutesRecognized, '/include/simple'], [GuardsCheckStart, '/include/simple'], [GuardsCheckEnd, '/include/simple'], [ResolveStart, '/include/simple'], [ResolveEnd, '/include/simple'], [NavigationEnd, '/include/simple'], ]); }), )); it('should handle the case when the router takes only the primary url', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'include', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'simple', component: SimpleCmp}, ], }, ]); const events: Event[] = []; router.events.subscribe((e) => e instanceof RouterEvent && events.push(e)); location.go('/include/user/kate(aux:excluded)'); location.historyGo(0); advance(fixture); expect(location.path()).toEqual('/include/user/kate(aux:excluded)'); expectEvents(events, [ [NavigationStart, '/include/user/kate'], [RoutesRecognized, '/include/user/kate'], [GuardsCheckStart, '/include/user/kate'], [GuardsCheckEnd, '/include/user/kate'], [ResolveStart, '/include/user/kate'], [ResolveEnd, '/include/user/kate'], [NavigationEnd, '/include/user/kate'], ]); events.splice(0); location.go('/include/user/kate(aux:excluded2)'); location.historyGo(0); advance(fixture); expectEvents(events, [[NavigationSkipped, '/include/user/kate(aux:excluded2)']]); events.splice(0); router.navigateByUrl('/include/simple'); advance(fixture); expect(location.path()).toEqual('/include/simple(aux:excluded2)'); expectEvents(events, [ [NavigationStart, '/include/simple'], [RoutesRecognized, '/include/simple'], [GuardsCheckStart, '/include/simple'], [GuardsCheckEnd, '/include/simple'], [ResolveStart, '/include/simple'], [ResolveEnd, '/include/simple'], [NavigationEnd, '/include/simple'], ]); }), )); it('should not remove parts of the URL that are not handled by the router when "eager"', fakeAsync(() => { TestBed.configureTestingModule({ providers: [provideRouter([], withRouterConfig({urlUpdateStrategy: 'eager'}))], }); const router = TestBed.inject(Router); const location = TestBed.inject(Location); const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'include', component: TeamCmp, children: [{path: 'user/:name', component: UserCmp}], }, ]); location.go('/include/user/kate(aux:excluded)'); location.historyGo(0); advance(fixture); expect(location.path()).toEqual('/include/user/kate(aux:excluded)'); })); }); it('can use `relativeTo` `route.parent` in `routerLink` to close secondary outlet', fakeAsync(() => { // Given @Component({ template: '<router-outlet name="secondary"></router-outlet>', standalone: false, }) class ChildRootCmp {} @Component({ selector: 'link-cmp', template: `<a [relativeTo]="route.parent" [routerLink]="[{outlets: {'secondary': null}}]">link</a> <button [relativeTo]="route.parent" [routerLink]="[{outlets: {'secondary': null}}]">link</button> `, standalone: false, }) class RelativeLinkCmp { @ViewChildren(RouterLink) links!: QueryList<RouterLink>; constructor(readonly route: ActivatedRoute) {} } @NgModule({ declarations: [RelativeLinkCmp, ChildRootCmp], imports: [ RouterModule.forChild([ { path: 'childRoot', component: ChildRootCmp, children: [{path: 'popup', outlet: 'secondary', component: RelativeLinkCmp}], }, ]), ], }) class LazyLoadedModule {} const router = TestBed.inject(Router); router.resetConfig([{path: 'root', loadChildren: () => LazyLoadedModule}]); // When router.navigateByUrl('/root/childRoot/(secondary:popup)'); const fixture = createRoot(router, RootCmp); advance(fixture); // Then const relativeLinkCmp = fixture.debugElement.query( By.directive(RelativeLinkCmp), ).componentInstance; expect(relativeLinkCmp.links.first.urlTree.toString()).toEqual('/root/childRoot'); expect(relativeLinkCmp.links.last.urlTree.toString()).toEqual('/root/childRoot'); }));
{ "end_byte": 259036, "start_byte": 249449, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_259044_267635
should ignore empty path for relative links', fakeAsync( inject([Router], (router: Router) => { @Component({ selector: 'link-cmp', template: `<a [routerLink]="['../simple']">link</a>`, standalone: false, }) class RelativeLinkCmp {} @NgModule({ declarations: [RelativeLinkCmp], imports: [ RouterModule.forChild([ {path: 'foo/bar', children: [{path: '', component: RelativeLinkCmp}]}, ]), ], }) class LazyLoadedModule {} const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: () => LazyLoadedModule}]); router.navigateByUrl('/lazy/foo/bar'); advance(fixture); const link = fixture.nativeElement.querySelector('a'); expect(link.getAttribute('href')).toEqual('/lazy/foo/simple'); }), )); }); describe('Custom Route Reuse Strategy', () => { class AttachDetachReuseStrategy implements RouteReuseStrategy { stored: {[k: string]: DetachedRouteHandle} = {}; pathsToDetach = ['a']; shouldDetach(route: ActivatedRouteSnapshot): boolean { return ( typeof route.routeConfig!.path !== 'undefined' && this.pathsToDetach.includes(route.routeConfig!.path) ); } store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void { this.stored[route.routeConfig!.path!] = detachedTree; } shouldAttach(route: ActivatedRouteSnapshot): boolean { return !!this.stored[route.routeConfig!.path!]; } retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { return this.stored[route.routeConfig!.path!]; } shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { return future.routeConfig === curr.routeConfig; } } class ShortLifecycle implements RouteReuseStrategy { shouldDetach(route: ActivatedRouteSnapshot): boolean { return false; } store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {} shouldAttach(route: ActivatedRouteSnapshot): boolean { return false; } retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null { return null; } shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { if (future.routeConfig !== curr.routeConfig) { return false; } if (Object.keys(future.params).length !== Object.keys(curr.params).length) { return false; } return Object.keys(future.params).every((k) => future.params[k] === curr.params[k]); } } it('should be injectable', () => { TestBed.configureTestingModule({ providers: [ {provide: RouteReuseStrategy, useClass: AttachDetachReuseStrategy}, provideRouter([]), ], }); const router = TestBed.inject(Router); expect(router.routeReuseStrategy).toBeInstanceOf(AttachDetachReuseStrategy); }); it('should emit an event when an outlet gets attached/detached', fakeAsync(() => { @Component({ selector: 'container', template: `<router-outlet (attach)="recordAttached($event)" (detach)="recordDetached($event)"></router-outlet>`, standalone: false, }) class Container { attachedComponents: unknown[] = []; detachedComponents: unknown[] = []; recordAttached(component: unknown): void { this.attachedComponents.push(component); } recordDetached(component: unknown): void { this.detachedComponents.push(component); } } TestBed.configureTestingModule({ declarations: [Container], providers: [{provide: RouteReuseStrategy, useClass: AttachDetachReuseStrategy}], }); const router = TestBed.inject(Router); const fixture = createRoot(router, Container); const cmp = fixture.componentInstance; router.resetConfig([ {path: 'a', component: BlankCmp}, {path: 'b', component: SimpleCmp}, ]); cmp.attachedComponents = []; cmp.detachedComponents = []; router.navigateByUrl('/a'); advance(fixture); expect(cmp.attachedComponents.length).toEqual(0); expect(cmp.detachedComponents.length).toEqual(0); router.navigateByUrl('/b'); advance(fixture); expect(cmp.attachedComponents.length).toEqual(0); expect(cmp.detachedComponents.length).toEqual(1); expect(cmp.detachedComponents[0] instanceof BlankCmp).toBe(true); // the route will be reused by the `RouteReuseStrategy` router.navigateByUrl('/a'); advance(fixture); expect(cmp.attachedComponents.length).toEqual(1); expect(cmp.attachedComponents[0] instanceof BlankCmp).toBe(true); expect(cmp.detachedComponents.length).toEqual(1); expect(cmp.detachedComponents[0] instanceof BlankCmp).toBe(true); })); it('should support attaching & detaching fragments', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.routeReuseStrategy = new AttachDetachReuseStrategy(); (router.routeReuseStrategy as AttachDetachReuseStrategy).pathsToDetach = ['a', 'b']; spyOn(router.routeReuseStrategy, 'retrieve').and.callThrough(); router.resetConfig([ { path: 'a', component: TeamCmp, children: [{path: 'b', component: SimpleCmp}], }, {path: 'c', component: UserCmp}, ]); router.navigateByUrl('/a/b'); advance(fixture); const teamCmp = fixture.debugElement.children[1].componentInstance; const simpleCmp = fixture.debugElement.children[1].children[1].componentInstance; expect(location.path()).toEqual('/a/b'); expect(teamCmp).toBeDefined(); expect(simpleCmp).toBeDefined(); expect(router.routeReuseStrategy.retrieve).not.toHaveBeenCalled(); router.navigateByUrl('/c'); advance(fixture); expect(location.path()).toEqual('/c'); expect(fixture.debugElement.children[1].componentInstance).toBeInstanceOf(UserCmp); // We have still not encountered a route that should be reattached expect(router.routeReuseStrategy.retrieve).not.toHaveBeenCalled(); router.navigateByUrl('/a;p=1/b;p=2'); advance(fixture); // We retrieve both the stored route snapshots expect(router.routeReuseStrategy.retrieve).toHaveBeenCalledTimes(4); const teamCmp2 = fixture.debugElement.children[1].componentInstance; const simpleCmp2 = fixture.debugElement.children[1].children[1].componentInstance; expect(location.path()).toEqual('/a;p=1/b;p=2'); expect(teamCmp2).toBe(teamCmp); expect(simpleCmp2).toBe(simpleCmp); expect(teamCmp.route).toBe(router.routerState.root.firstChild); expect(teamCmp.route.snapshot).toBe(router.routerState.snapshot.root.firstChild); expect(teamCmp.route.snapshot.params).toEqual({p: '1'}); expect(teamCmp.route.firstChild.snapshot.params).toEqual({p: '2'}); expect(teamCmp.recordedParams).toEqual([{}, {p: '1'}]); }), )); it('should support shorter lifecycles', fakeAsync( inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.routeReuseStrategy = new ShortLifecycle(); router.resetConfig([{path: 'a', component: SimpleCmp}]); router.navigateByUrl('/a'); advance(fixture); const simpleCmp1 = fixture.debugElement.children[1].componentInstance; expect(location.path()).toEqual('/a'); router.navigateByUrl('/a;p=1'); advance(fixture); expect(location.path()).toEqual('/a;p=1'); const simpleCmp2 = fixture.debugElement.children[1].componentInstance; expect(simpleCmp1).not.toBe(simpleCmp2); }), ));
{ "end_byte": 267635, "start_byte": 259044, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_267643_277018
should not mount the component of the previously reused route when the outlet was not instantiated at the time of route activation', fakeAsync(() => { @Component({ selector: 'root-cmp', template: '<div *ngIf="isToolpanelShowing"><router-outlet name="toolpanel"></router-outlet></div>', standalone: false, }) class RootCmpWithCondOutlet implements OnDestroy { private subscription: Subscription; public isToolpanelShowing: boolean = false; constructor(router: Router) { this.subscription = router.events .pipe(filter((event) => event instanceof NavigationEnd)) .subscribe( () => (this.isToolpanelShowing = !!router.parseUrl(router.url).root.children[ 'toolpanel' ]), ); } public ngOnDestroy(): void { this.subscription.unsubscribe(); } } @Component({ selector: 'tool-1-cmp', template: 'Tool 1 showing', standalone: false, }) class Tool1Component {} @Component({ selector: 'tool-2-cmp', template: 'Tool 2 showing', standalone: false, }) class Tool2Component {} @NgModule({ declarations: [RootCmpWithCondOutlet, Tool1Component, Tool2Component], imports: [CommonModule, ...ROUTER_DIRECTIVES], providers: [ provideRouter([ {path: 'a', outlet: 'toolpanel', component: Tool1Component}, {path: 'b', outlet: 'toolpanel', component: Tool2Component}, ]), ], }) class TestModule {} TestBed.configureTestingModule({imports: [TestModule]}); const router: Router = TestBed.inject(Router); router.routeReuseStrategy = new AttachDetachReuseStrategy(); const fixture = createRoot(router, RootCmpWithCondOutlet); // Activate 'tool-1' router.navigate([{outlets: {toolpanel: 'a'}}]); advance(fixture); expect(fixture).toContainComponent(Tool1Component, '(a)'); // Deactivate 'tool-1' router.navigate([{outlets: {toolpanel: null}}]); advance(fixture); expect(fixture).not.toContainComponent(Tool1Component, '(b)'); // Activate 'tool-1' router.navigate([{outlets: {toolpanel: 'a'}}]); advance(fixture); expect(fixture).toContainComponent(Tool1Component, '(c)'); // Deactivate 'tool-1' router.navigate([{outlets: {toolpanel: null}}]); advance(fixture); expect(fixture).not.toContainComponent(Tool1Component, '(d)'); // Activate 'tool-2' router.navigate([{outlets: {toolpanel: 'b'}}]); advance(fixture); expect(fixture).toContainComponent(Tool2Component, '(e)'); })); it('should not remount a destroyed component', fakeAsync(() => { @Component({ selector: 'root-cmp', template: '<div *ngIf="showRouterOutlet"><router-outlet></router-outlet></div>', standalone: false, }) class RootCmpWithCondOutlet { public showRouterOutlet: boolean = true; } @NgModule({ declarations: [RootCmpWithCondOutlet], imports: [CommonModule, ...ROUTER_DIRECTIVES], providers: [ {provide: RouteReuseStrategy, useClass: AttachDetachReuseStrategy}, provideRouter([ {path: 'a', component: SimpleCmp}, {path: 'b', component: BlankCmp}, ]), ], }) class TestModule {} TestBed.configureTestingModule({imports: [TestModule]}); const router: Router = TestBed.inject(Router); const fixture = createRoot(router, RootCmpWithCondOutlet); // Activate 'a' router.navigate(['a']); advance(fixture); expect(fixture.debugElement.query(By.directive(SimpleCmp))).toBeTruthy(); // Deactivate 'a' and detach the route router.navigate(['b']); advance(fixture); expect(fixture.debugElement.query(By.directive(SimpleCmp))).toBeNull(); // Activate 'a' again, the route should be re-attached router.navigate(['a']); advance(fixture); expect(fixture.debugElement.query(By.directive(SimpleCmp))).toBeTruthy(); // Hide the router-outlet, SimpleCmp should be destroyed fixture.componentInstance.showRouterOutlet = false; advance(fixture); expect(fixture.debugElement.query(By.directive(SimpleCmp))).toBeNull(); // Show the router-outlet, SimpleCmp should be re-created fixture.componentInstance.showRouterOutlet = true; advance(fixture); expect(fixture.debugElement.query(By.directive(SimpleCmp))).toBeTruthy(); })); it('should allow to attach parent route with fresh child route', fakeAsync(() => { const CREATED_COMPS = new InjectionToken<string[]>('CREATED_COMPS'); @Component({ selector: 'root', template: `<router-outlet></router-outlet>`, standalone: false, }) class Root {} @Component({ selector: 'parent', template: `<router-outlet></router-outlet>`, standalone: false, }) class Parent { constructor(@Inject(CREATED_COMPS) createdComps: string[]) { createdComps.push('parent'); } } @Component({ selector: 'child', template: `child`, standalone: false, }) class Child { constructor(@Inject(CREATED_COMPS) createdComps: string[]) { createdComps.push('child'); } } @NgModule({ declarations: [Root, Parent, Child], imports: [CommonModule, ...ROUTER_DIRECTIVES], providers: [ {provide: RouteReuseStrategy, useClass: AttachDetachReuseStrategy}, {provide: CREATED_COMPS, useValue: []}, provideRouter([ {path: 'a', component: Parent, children: [{path: 'b', component: Child}]}, {path: 'c', component: SimpleCmp}, ]), ], }) class TestModule {} TestBed.configureTestingModule({imports: [TestModule]}); const router = TestBed.inject(Router); const fixture = createRoot(router, Root); const createdComps = TestBed.inject(CREATED_COMPS); expect(createdComps).toEqual([]); router.navigateByUrl('/a/b'); advance(fixture); expect(createdComps).toEqual(['parent', 'child']); router.navigateByUrl('/c'); advance(fixture); expect(createdComps).toEqual(['parent', 'child']); // 'a' parent route will be reused by the `RouteReuseStrategy`, child 'b' should be // recreated router.navigateByUrl('/a/b'); advance(fixture); expect(createdComps).toEqual(['parent', 'child', 'child']); })); it('should not try to detach the outlet of a route that does not get to attach a component', fakeAsync(() => { @Component({ selector: 'root', template: `<router-outlet></router-outlet>`, standalone: false, }) class Root {} @Component({ selector: 'component-a', template: 'Component A', standalone: false, }) class ComponentA {} @Component({ selector: 'component-b', template: 'Component B', standalone: false, }) class ComponentB {} @NgModule({ declarations: [ComponentA], imports: [RouterModule.forChild([{path: '', component: ComponentA}])], }) class LoadedModule {} @NgModule({ declarations: [Root, ComponentB], imports: [ROUTER_DIRECTIVES], providers: [ {provide: RouteReuseStrategy, useClass: AttachDetachReuseStrategy}, provideRouter([ {path: 'a', loadChildren: () => LoadedModule}, {path: 'b', component: ComponentB}, ]), ], }) class TestModule {} TestBed.configureTestingModule({imports: [TestModule]}); const router = TestBed.inject(Router); const strategy = TestBed.inject(RouteReuseStrategy); const fixture = createRoot(router, Root); spyOn(strategy, 'shouldDetach').and.callThrough(); router.navigateByUrl('/a'); advance(fixture); // Deactivate 'a' // 'shouldDetach' should not be called for the componentless route router.navigateByUrl('/b'); advance(fixture); expect(strategy.shouldDetach).toHaveBeenCalledTimes(1); })); }); }); } function expectEvents(events: Event[], pairs: any[]) { expect(events.length).toEqual(pairs.length); for (let i = 0; i < events.length; ++i) { expect(events[i].constructor.name).toBe(pairs[i][0].name); expect((<any>events[i]).url).toBe(pairs[i][1]); } } function onlyNavigationStartAndEnd(e: Event): e is NavigationStart | NavigationEnd { return e instanceof NavigationStart || e instanceof NavigationEnd; } @C
{ "end_byte": 277018, "start_byte": 267643, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_277020_284481
ponent({ selector: 'link-cmp', template: `<a routerLink="/team/33/simple" [target]="'_self'">link</a>`, standalone: false, }) class StringLinkCmp {} @Component({ selector: 'link-cmp', template: `<button routerLink="/team/33/simple">link</button>`, standalone: false, }) class StringLinkButtonCmp {} @Component({ selector: 'link-cmp', template: `<router-outlet></router-outlet><a [routerLink]="['/team/33/simple']">link</a>`, standalone: false, }) class AbsoluteLinkCmp {} @Component({ selector: 'link-cmp', template: `<router-outlet></router-outlet><a routerLinkActive="active" (isActiveChange)="this.onRouterLinkActivated($event)" [routerLinkActiveOptions]="{exact: exact}" ariaCurrentWhenActive="page" [routerLink]="['./']">link</a> <button routerLinkActive="active" [routerLinkActiveOptions]="{exact: exact}" [routerLink]="['./']">button</button> `, standalone: false, }) class DummyLinkCmp { private exact: boolean; public isLinkActivated?: boolean; constructor(route: ActivatedRoute) { this.exact = route.snapshot.paramMap.get('exact') === 'true'; } public onRouterLinkActivated(isActive: boolean): void { this.isLinkActivated = isActive; } } @Component({ selector: 'link-cmp', template: `<a [routerLink]="['/simple']">link</a>`, standalone: false, }) class AbsoluteSimpleLinkCmp {} @Component({ selector: 'link-cmp', template: `<a [routerLink]="['../simple']">link</a>`, standalone: false, }) class RelativeLinkCmp {} @Component({ selector: 'link-cmp', template: `<a [routerLink]="['../simple']" [queryParams]="{q: '1'}" fragment="f">link</a>`, standalone: false, }) class LinkWithQueryParamsAndFragment {} @Component({ selector: 'link-cmp', template: `<a id="link" [routerLink]="['../simple']" [state]="{foo: 'bar'}">link</a>`, standalone: false, }) class LinkWithState {} @Component({ selector: 'div-link-cmp', template: `<div id="link" [routerLink]="['../simple']" [state]="{foo: 'bar'}">link</div>`, standalone: false, }) class DivLinkWithState {} @Component({ selector: 'simple-cmp', template: `simple`, standalone: false, }) class SimpleCmp {} @Component({ selector: 'collect-params-cmp', template: `collect-params`, standalone: false, }) class CollectParamsCmp { private params: Params[] = []; private urls: UrlSegment[][] = []; constructor(public route: ActivatedRoute) { route.params.forEach((p) => this.params.push(p)); route.url.forEach((u) => this.urls.push(u)); } recordedUrls(): string[] { return this.urls.map((a: UrlSegment[]) => a.map((p: UrlSegment) => p.path).join('/')); } } @Component({ selector: 'blank-cmp', template: ``, standalone: false, }) class BlankCmp {} @NgModule({imports: [RouterModule.forChild([{path: '', component: BlankCmp}])]}) class ModuleWithBlankCmpAsRoute {} @Component({ selector: 'team-cmp', template: `team {{id | async}} ` + `[ <router-outlet></router-outlet>, right: <router-outlet name="right"></router-outlet> ]` + `<a [routerLink]="routerLink" skipLocationChange></a>` + `<button [routerLink]="routerLink" skipLocationChange></button>`, standalone: false, }) class TeamCmp { id: Observable<string>; recordedParams: Params[] = []; snapshotParams: Params[] = []; routerLink = ['.']; constructor(public route: ActivatedRoute) { this.id = route.params.pipe(map((p: Params) => p['id'])); route.params.forEach((p) => { this.recordedParams.push(p); this.snapshotParams.push(route.snapshot.params); }); } } @Component({ selector: 'two-outlets-cmp', template: `[ <router-outlet></router-outlet>, aux: <router-outlet name="aux"></router-outlet> ]`, standalone: false, }) class TwoOutletsCmp {} @Component({ selector: 'user-cmp', template: `user {{name | async}}`, standalone: false, }) class UserCmp { name: Observable<string>; recordedParams: Params[] = []; snapshotParams: Params[] = []; constructor(route: ActivatedRoute) { this.name = route.params.pipe(map((p: Params) => p['name'])); route.params.forEach((p) => { this.recordedParams.push(p); this.snapshotParams.push(route.snapshot.params); }); } } @Component({ selector: 'wrapper', template: `<router-outlet></router-outlet>`, standalone: false, }) class WrapperCmp {} @Component({ selector: 'query-cmp', template: `query: {{name | async}} fragment: {{fragment | async}}`, standalone: false, }) class QueryParamsAndFragmentCmp { name: Observable<string | null>; fragment: Observable<string>; constructor(route: ActivatedRoute) { this.name = route.queryParamMap.pipe(map((p: ParamMap) => p.get('name'))); this.fragment = route.fragment.pipe( map((p: string | null | undefined) => { if (p === undefined) { return 'undefined'; } else if (p === null) { return 'null'; } else { return p; } }), ); } } @Component({ selector: 'empty-query-cmp', template: ``, standalone: false, }) class EmptyQueryParamsCmp { recordedParams: Params[] = []; constructor(route: ActivatedRoute) { route.queryParams.forEach((_) => this.recordedParams.push(_)); } } @Component({ selector: 'route-cmp', template: `route`, standalone: false, }) class RouteCmp { constructor(public route: ActivatedRoute) {} } @Component({ selector: 'link-cmp', template: `<div *ngIf="show"><a [routerLink]="['./simple']">link</a></div> <router-outlet></router-outlet>`, standalone: false, }) class RelativeLinkInIfCmp { show: boolean = false; } @Component({ selector: 'child', template: '<div *ngIf="alwaysTrue"><router-outlet></router-outlet></div>', standalone: false, }) class OutletInNgIf { alwaysTrue = true; } @Component({ selector: 'link-cmp', template: `<router-outlet></router-outlet> <div id="link-parent" routerLinkActive="active" [routerLinkActiveOptions]="{exact: exact}"> <div ngClass="{one: 'true'}"><a [routerLink]="['./']">link</a></div> </div>`, standalone: false, }) class DummyLinkWithParentCmp { protected exact: boolean; constructor(route: ActivatedRoute) { this.exact = route.snapshot.params['exact'] === 'true'; } } @Component({ selector: 'cmp', template: '', standalone: false, }) class ComponentRecordingRoutePathAndUrl { public path: ActivatedRoute[]; public url: string; constructor(router: Router, route: ActivatedRoute) { this.path = route.pathFromRoot; this.url = router.url.toString(); } } @Component({ selector: 'root-cmp', template: `<router-outlet></router-outlet>`, standalone: false, }) class RootCmp {} @Component({ selector: 'root-cmp-on-init', template: `<router-outlet></router-outlet>`, standalone: false, }) class RootCmpWithOnInit { constructor(private router: Router) {} ngOnInit(): void { this.router.navigate(['one']); } } @Component({ selector: 'root-cmp', template: `primary [<router-outlet></router-outlet>] right [<router-outlet name="right"></router-outlet>]`, standalone: false, }) class RootCmpWithTwoOutlets {} @Component({ selector: 'root-cmp', template: `main [<router-outlet name="main"></router-outlet>]`, standalone: false, }) class RootCmpWithNamedOutlet {} @Component({ selector: 'throwing-cmp', template: '', standalone: false, }) class ThrowingCmp { constructor() { throw new Error('Throwing Cmp'); } } @Co
{ "end_byte": 284481, "start_byte": 277020, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/integration.spec.ts_284482_286595
ponent({ selector: 'conditional-throwing-cmp', template: 'conditional throwing', standalone: false, }) class ConditionalThrowingCmp { static throwError = true; constructor() { if (ConditionalThrowingCmp.throwError) { throw new Error('Throwing Cmp'); } } } function advance(fixture: ComponentFixture<unknown>, millis?: number): void { tick(millis); fixture.detectChanges(); } function createRoot<T>(router: Router, type: Type<T>): ComponentFixture<T> { const f = TestBed.createComponent<T>(type); advance(f); router.initialNavigation(); advance(f); return f; } @Component({ selector: 'lazy', template: 'lazy-loaded', standalone: false, }) class LazyComponent {} @NgModule({ imports: [CommonModule, ...ROUTER_DIRECTIVES], exports: [ BlankCmp, SimpleCmp, TwoOutletsCmp, TeamCmp, UserCmp, StringLinkCmp, DummyLinkCmp, AbsoluteLinkCmp, AbsoluteSimpleLinkCmp, RelativeLinkCmp, DummyLinkWithParentCmp, LinkWithQueryParamsAndFragment, DivLinkWithState, LinkWithState, CollectParamsCmp, QueryParamsAndFragmentCmp, StringLinkButtonCmp, WrapperCmp, OutletInNgIf, ComponentRecordingRoutePathAndUrl, RouteCmp, RootCmp, RootCmpWithOnInit, RelativeLinkInIfCmp, RootCmpWithTwoOutlets, RootCmpWithNamedOutlet, EmptyQueryParamsCmp, ThrowingCmp, ConditionalThrowingCmp, ], declarations: [ BlankCmp, SimpleCmp, TeamCmp, TwoOutletsCmp, UserCmp, StringLinkCmp, DummyLinkCmp, AbsoluteLinkCmp, AbsoluteSimpleLinkCmp, RelativeLinkCmp, DummyLinkWithParentCmp, LinkWithQueryParamsAndFragment, DivLinkWithState, LinkWithState, CollectParamsCmp, QueryParamsAndFragmentCmp, StringLinkButtonCmp, WrapperCmp, OutletInNgIf, ComponentRecordingRoutePathAndUrl, RouteCmp, RootCmp, RootCmpWithOnInit, RelativeLinkInIfCmp, RootCmpWithTwoOutlets, RootCmpWithNamedOutlet, EmptyQueryParamsCmp, ThrowingCmp, ConditionalThrowingCmp, ], }) class TestModule {}
{ "end_byte": 286595, "start_byte": 284482, "url": "https://github.com/angular/angular/blob/main/packages/router/test/integration.spec.ts" }
angular/packages/router/test/bootstrap.spec.ts_0_1585
/** * @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.dev/license */ import {DOCUMENT, PlatformLocation, ɵgetDOM as getDOM} from '@angular/common'; import {BrowserPlatformLocation} from '@angular/common/src/location/platform_location'; import {NullViewportScroller, ViewportScroller} from '@angular/common/src/viewport_scroller'; import {MockPlatformLocation} from '@angular/common/testing'; import { ApplicationRef, Component, CUSTOM_ELEMENTS_SCHEMA, destroyPlatform, ENVIRONMENT_INITIALIZER, inject, Injectable, NgModule, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import { Event, NavigationEnd, provideRouter, 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;
{ "end_byte": 1585, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/bootstrap.spec.ts" }
angular/packages/router/test/bootstrap.spec.ts_1587_10543
escribe('bootstrap', () => { let log: any[] = []; let testProviders: any[] = null!; @Component({ template: 'simple', standalone: false, }) class SimpleCmp {} @Component({ selector: 'test-app', template: 'root <router-outlet></router-outlet>', standalone: false, }) class RootCmp { constructor() { log.push('RootCmp'); } } @Component({ selector: 'test-app2', template: 'root <router-outlet></router-outlet>', standalone: false, }) class SecondRootCmp {} @Injectable({providedIn: 'root'}) class TestResolver { resolve() { let resolve: (value: unknown) => void; const res = new Promise((r) => (resolve = r)); setTimeout(() => resolve('test-data'), 0); return res; } } let navigationEndPromise: Promise<void>; beforeEach(() => { destroyPlatform(); const doc = TestBed.inject(DOCUMENT); const oldRoots = doc.querySelectorAll('test-app,test-app2'); for (let i = 0; i < oldRoots.length; i++) { getDOM().remove(oldRoots[i]); } const el1 = getDOM().createElement('test-app', doc); const el2 = getDOM().createElement('test-app2', doc); doc.body.appendChild(el1); doc.body.appendChild(el2); const {promise, resolveFn} = createPromise(); navigationEndPromise = promise; log = []; testProviders = [ {provide: DOCUMENT, useValue: doc}, {provide: ViewportScroller, useClass: isNode ? NullViewportScroller : ViewportScroller}, {provide: PlatformLocation, useClass: MockPlatformLocation}, provideNavigationEndAction(resolveFn), ]; }); afterEach(destroyPlatform); it('should complete when initial navigation fails and initialNavigation = enabledBlocking', async () => { @NgModule({ imports: [BrowserModule], declarations: [RootCmp], bootstrap: [RootCmp], providers: [ ...testProviders, 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 {} @NgModule({ imports: [BrowserModule, RouterOutlet], declarations: [RootCmp], bootstrap: [RootCmp], providers: [ ...testProviders, provideRouter( [ {path: '', component: Renavigate}, {path: 'other', component: BlankCmp}, ], withEnabledBlockingInitialNavigation(), ), ], }) class TestModule {} await expectAsync( Promise.all([platformBrowserDynamic([]).bootstrapModule(TestModule), navigationEndPromise]), ).toBeResolved(); }); 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: []}, ], {initialNavigation: 'enabledBlocking'}, ), ], declarations: [RootCmp], bootstrap: [RootCmp], providers: [...testProviders], schemas: [CUSTOM_ELEMENTS_SCHEMA], }) class TestModule { constructor() { log.push('TestModule'); } } const bootstrapPromise = platformBrowserDynamic([]) .bootstrapModule(TestModule) .then((ref) => { const router = ref.injector.get(Router); expect(router.navigated).toEqual(true); expect(router.url).toContain('redirectToMe'); expect(log).toContain('TestModule'); }); await Promise.all([bootstrapPromise, navigationEndPromise]); }); it('should wait for redirect with UrlTree when initialNavigation = enabledBlocking', async () => { @NgModule({ imports: [ BrowserModule, RouterModule.forRoot( [ {path: 'redirectToMe', children: []}, { path: '**', canActivate: [() => inject(Router).createUrlTree(['redirectToMe'])], children: [], }, ], {initialNavigation: 'enabledBlocking'}, ), ], declarations: [RootCmp], bootstrap: [RootCmp], providers: [...testProviders], schemas: [CUSTOM_ELEMENTS_SCHEMA], }) class TestModule { constructor() { log.push('TestModule'); } } const bootstrapPromise = platformBrowserDynamic([]) .bootstrapModule(TestModule) .then((ref) => { const router = ref.injector.get(Router); expect(router.navigated).toEqual(true); expect(router.url).toContain('redirectToMe'); expect(log).toContain('TestModule'); }); await Promise.all([bootstrapPromise, navigationEndPromise]); }); it('should wait for resolvers to complete when initialNavigation = enabledBlocking', async () => { @Component({ selector: 'test', template: 'test', standalone: false, }) class TestCmpEnabled {} @NgModule({ imports: [ BrowserModule, RouterModule.forRoot( [{path: '**', component: TestCmpEnabled, resolve: {test: TestResolver}}], {initialNavigation: 'enabledBlocking'}, ), ], declarations: [RootCmp, TestCmpEnabled], bootstrap: [RootCmp], providers: [...testProviders, TestResolver], schemas: [CUSTOM_ELEMENTS_SCHEMA], }) class TestModule { constructor(router: Router) {} } const bootstrapPromise = platformBrowserDynamic([]) .bootstrapModule(TestModule) .then((ref) => { const router = ref.injector.get(Router); const data = router.routerState.snapshot.root.firstChild!.data; expect(data['test']).toEqual('test-data'); // Also ensure that the navigation completed. The navigation transition clears the // current navigation in its `finalize` operator. expect(router.getCurrentNavigation()).toBeNull(); }); await Promise.all([bootstrapPromise, navigationEndPromise]); }); it('should NOT wait for resolvers to complete when initialNavigation = enabledNonBlocking', async () => { @Component({ selector: 'test', template: 'test', standalone: false, }) class TestCmpLegacyEnabled {} @NgModule({ imports: [ BrowserModule, RouterModule.forRoot( [{path: '**', component: TestCmpLegacyEnabled, resolve: {test: TestResolver}}], {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)); } } const bootstrapPromise = platformBrowserDynamic([]) .bootstrapModule(TestModule) .then((ref) => { const router: Router = ref.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', ]); }); await Promise.all([bootstrapPromise, navigationEndPromise]); });
{ "end_byte": 10543, "start_byte": 1587, "url": "https://github.com/angular/angular/blob/main/packages/router/test/bootstrap.spec.ts" }
angular/packages/router/test/bootstrap.spec.ts_10547_19720
t('should NOT wait for resolvers to complete when initialNavigation is not set', async () => { @Component({ selector: 'test', template: 'test', standalone: false, }) class TestCmpLegacyEnabled {} @NgModule({ imports: [ BrowserModule, RouterModule.forRoot([ {path: '**', component: TestCmpLegacyEnabled, resolve: {test: TestResolver}}, ]), ], 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)); } } const bootstrapPromise = platformBrowserDynamic([]) .bootstrapModule(TestModule) .then((ref) => { const router: Router = ref.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', ]); }); await Promise.all([bootstrapPromise, navigationEndPromise]); }); it('should not run navigation when initialNavigation = disabled', (done) => { @Component({ selector: 'test', template: 'test', standalone: false, }) class TestCmpDiabled {} @NgModule({ imports: [ BrowserModule, RouterModule.forRoot( [{path: '**', component: TestCmpDiabled, resolve: {test: TestResolver}}], {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', async () => { @NgModule({ imports: [BrowserModule, RouterModule.forRoot([])], declarations: [SecondRootCmp, RootCmp], bootstrap: [RootCmp], providers: testProviders, schemas: [CUSTOM_ELEMENTS_SCHEMA], }) class TestModule {} await 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(); }); }); it('should reinit router navigation listeners if a previously bootstrapped root component is destroyed', async () => { @NgModule({ imports: [BrowserModule, RouterModule.forRoot([])], declarations: [SecondRootCmp, RootCmp], bootstrap: [RootCmp], providers: testProviders, schemas: [CUSTOM_ELEMENTS_SCHEMA], }) class TestModule {} await 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); const {promise, resolveFn} = createPromise(); appRef.components[0].onDestroy(() => { appRef.bootstrap(SecondRootCmp); expect((router as any).resetRootComponentType).toHaveBeenCalled(); resolveFn(); }); appRef.components[0].destroy(); return promise; }); }); if (!isNode) { 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> `, standalone: false, }) 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: [() => false]}, ], { scrollPositionRestoration: 'enabled', anchorScrolling: 'enabled', scrollOffset: [0, 100], onSameUrlNavigation: 'ignore', }, ), ], declarations: [TallComponent, RootCmp], bootstrap: [RootCmp], providers: [...testProviders], schemas: [CUSTOM_ELEMENTS_SCHEMA], }) class TestModule {} function resolveAfter(milliseconds: number) { return new Promise<void>((resolve) => { setTimeout(() => { resolve(); }, milliseconds); }); } 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'); await resolveAfter(100); expect(window.pageYOffset).toEqual(0); await router.navigateByUrl('/aa#marker2'); await resolveAfter(100); expect(window.scrollY).toBeGreaterThanOrEqual(5900); expect(window.scrollY).toBeLessThan(6000); // offset // Scroll somewhere else, then navigate to the hash again. Even though the same url navigation // is ignored by the Router, we should still scroll. window.scrollTo(0, 3000); await router.navigateByUrl('/aa#marker2'); await resolveAfter(100); expect(window.scrollY).toBeGreaterThanOrEqual(5900); expect(window.scrollY).toBeLessThan(6000); // offset }); it('should cleanup "popstate" and "hashchange" listeners', async () => { @NgModule({ imports: [BrowserModule, RouterModule.forRoot([])], declarations: [RootCmp], bootstrap: [RootCmp], providers: [ ...testProviders, {provide: PlatformLocation, useClass: BrowserPlatformLocation}, ], }) 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(async (e) => { if (e instanceof NavigationEnd && e.url === '/b') { await router.navigate(['a']); done(); } }); await router.navigateByUrl('/b'); })(); }); }); function onNavigationEnd(router: Router, fn: Function) { router.events.subscribe((e) => { if (e instanceof NavigationEnd) { fn(); } }); }
{ "end_byte": 19720, "start_byte": 10547, "url": "https://github.com/angular/angular/blob/main/packages/router/test/bootstrap.spec.ts" }
angular/packages/router/test/bootstrap.spec.ts_19722_20097
unction provideNavigationEndAction(fn: Function) { return { provide: ENVIRONMENT_INITIALIZER, multi: true, useValue: () => { onNavigationEnd(inject(Router), fn); }, }; } function createPromise() { let resolveFn: () => void; const promise = new Promise<void>((r) => { resolveFn = r; }); return {resolveFn: () => resolveFn(), promise}; }
{ "end_byte": 20097, "start_byte": 19722, "url": "https://github.com/angular/angular/blob/main/packages/router/test/bootstrap.spec.ts" }
angular/packages/router/test/view_transitions.spec.ts_0_3246
/** * @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.dev/license */ import {DOCUMENT} from '@angular/common'; import {Component, destroyPlatform, inject} from '@angular/core'; import {bootstrapApplication} from '@angular/platform-browser'; import {withBody} from '@angular/private/testing'; import { Event, NavigationEnd, provideRouter, Router, withDisabledInitialNavigation, withViewTransitions, } from '@angular/router'; describe('view transitions', () => { if (isNode) { it('are not available in node environment', () => {}); return; } beforeEach(destroyPlatform); afterEach(destroyPlatform); @Component({ selector: 'test-app', standalone: true, template: ``, }) class App {} beforeEach(withBody('<test-app></test-app>', () => {})); it('should skip initial transition', async () => { const appRef = await bootstrapApplication(App, { providers: [ provideRouter( [{path: '**', component: App}], withDisabledInitialNavigation(), withViewTransitions({skipInitialTransition: true}), ), ], }); const doc = appRef.injector.get(DOCUMENT); if (!doc.startViewTransition) { return; } const viewTransitionSpy = spyOn(doc, 'startViewTransition').and.callThrough(); await appRef.injector.get(Router).navigateByUrl('/a'); expect(viewTransitionSpy).not.toHaveBeenCalled(); await appRef.injector.get(Router).navigateByUrl('/b'); expect(viewTransitionSpy).toHaveBeenCalled(); }); it('should have the correct event order when using view transitions', async () => { @Component({ selector: 'component-b', template: `b`, standalone: true, }) class ComponentB {} const res = await bootstrapApplication(App, { providers: [provideRouter([{path: 'b', component: ComponentB}], withViewTransitions())], }); const router = res.injector.get(Router); const eventLog = [] as Event[]; router.events.subscribe((e) => { eventLog.push(e); }); await router.navigateByUrl('/b'); expect(eventLog[eventLog.length - 1]).toBeInstanceOf(NavigationEnd); }); describe('onViewTransitionCreated option', () => { it('should not create a view transition if only the fragment changes', async () => { @Component({ selector: 'test-app', standalone: true, template: `{{checks}}`, }) class App { checks = 0; ngDoCheck() { this.checks++; } } const transitionSpy = jasmine.createSpy(); const appRef = await bootstrapApplication(App, { providers: [ provideRouter( [{path: '**', component: App}], withDisabledInitialNavigation(), withViewTransitions({onViewTransitionCreated: transitionSpy}), ), ], }); const doc = appRef.injector.get(DOCUMENT); if (!doc.startViewTransition) { return; } await appRef.injector.get(Router).navigateByUrl('/a'); expect(transitionSpy).toHaveBeenCalled(); }); }); });
{ "end_byte": 3246, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/view_transitions.spec.ts" }