|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google LLC All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.io/license |
| 7 | + */ |
| 8 | + |
| 9 | +import {Component, DebugElement, Injectable, Type, ViewChild} from '@angular/core'; |
| 10 | +import {ComponentFixture, TestBed} from '@angular/core/testing'; |
| 11 | +import {Router, RouterOutlet, ɵafterNextNavigation as afterNextNavigation} from '@angular/router'; |
| 12 | + |
| 13 | +@Injectable({providedIn: 'root'}) |
| 14 | +export class RootFixtureService { |
| 15 | + private fixture?: ComponentFixture<RootCmp>; |
| 16 | + private harness?: RouterTestingHarness; |
| 17 | + |
| 18 | + createHarness(): RouterTestingHarness { |
| 19 | + if (this.harness) { |
| 20 | + throw new Error('Only one harness should be created per test.'); |
| 21 | + } |
| 22 | + this.harness = new RouterTestingHarness(this.getRootFixture()); |
| 23 | + return this.harness; |
| 24 | + } |
| 25 | + |
| 26 | + private getRootFixture(): ComponentFixture<RootCmp> { |
| 27 | + if (this.fixture !== undefined) { |
| 28 | + return this.fixture; |
| 29 | + } |
| 30 | + this.fixture = TestBed.createComponent(RootCmp); |
| 31 | + this.fixture.detectChanges(); |
| 32 | + return this.fixture; |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +@Component({ |
| 37 | + standalone: true, |
| 38 | + template: '<router-outlet></router-outlet>', |
| 39 | + imports: [RouterOutlet], |
| 40 | +}) |
| 41 | +export class RootCmp { |
| 42 | + @ViewChild(RouterOutlet) outlet?: RouterOutlet; |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * A testing harness for the `Router` to reduce the boilerplate needed to test routes and routed |
| 47 | + * components. |
| 48 | + * |
| 49 | + * @publicApi |
| 50 | + */ |
| 51 | +export class RouterTestingHarness { |
| 52 | + /** |
| 53 | + * Creates a `RouterTestingHarness` instance. |
| 54 | + * |
| 55 | + * The `RouterTestingHarness` also creates its own root component with a `RouterOutlet` for the |
| 56 | + * purposes of rendering route components. |
| 57 | + * |
| 58 | + * Throws an error if an instance has already been created. |
| 59 | + * Use of this harness also requires `destroyAfterEach: true` in the `ModuleTeardownOptions` |
| 60 | + * |
| 61 | + * @param initialUrl The target of navigation to trigger before returning the harness. |
| 62 | + */ |
| 63 | + static async create(initialUrl?: string): Promise<RouterTestingHarness> { |
| 64 | + const harness = TestBed.inject(RootFixtureService).createHarness(); |
| 65 | + if (initialUrl !== undefined) { |
| 66 | + await harness.navigateByUrl(initialUrl); |
| 67 | + } |
| 68 | + return harness; |
| 69 | + } |
| 70 | + |
| 71 | + /** @internal */ |
| 72 | + constructor(private readonly fixture: ComponentFixture<RootCmp>) {} |
| 73 | + |
| 74 | + /** Instructs the root fixture to run change detection. */ |
| 75 | + detectChanges(): void { |
| 76 | + this.fixture.detectChanges(); |
| 77 | + } |
| 78 | + /** The `DebugElement` of the `RouterOutlet` component. `null` if the outlet is not activated. */ |
| 79 | + get routeDebugElement(): DebugElement|null { |
| 80 | + const outlet = this.fixture.componentInstance.outlet; |
| 81 | + if (!outlet || !outlet.isActivated) { |
| 82 | + return null; |
| 83 | + } |
| 84 | + return this.fixture.debugElement.query(v => v.componentInstance === outlet.component); |
| 85 | + } |
| 86 | + /** The native element of the `RouterOutlet` component. `null` if the outlet is not activated. */ |
| 87 | + get routeNativeElement(): HTMLElement|null { |
| 88 | + return this.routeDebugElement?.nativeElement ?? null; |
| 89 | + } |
| 90 | + |
| 91 | + /** |
| 92 | + * Triggers a `Router` navigation and waits for it to complete. |
| 93 | + * |
| 94 | + * The root component with a `RouterOutlet` created for the harness is used to render `Route` |
| 95 | + * components. The root component is reused within the same test in subsequent calls to |
| 96 | + * `navigateForTest`. |
| 97 | + * |
| 98 | + * When testing `Routes` with a guards that reject the navigation, the `RouterOutlet` might not be |
| 99 | + * activated and the `activatedComponent` may be `null`. |
| 100 | + * |
| 101 | + * {@example router/testing/test/router_testing_harness_examples.spec.ts region='Guard'} |
| 102 | + * |
| 103 | + * @param url The target of the navigation. Passed to `Router.navigateByUrl`. |
| 104 | + * @returns The activated component instance of the `RouterOutlet` after navigation completes |
| 105 | + * (`null` if the outlet does not get activated). |
| 106 | + */ |
| 107 | + async navigateByUrl(url: string): Promise<null|{}>; |
| 108 | + /** |
| 109 | + * Triggers a router navigation and waits for it to complete. |
| 110 | + * |
| 111 | + * The root component with a `RouterOutlet` created for the harness is used to render `Route` |
| 112 | + * components. |
| 113 | + * |
| 114 | + * {@example router/testing/test/router_testing_harness_examples.spec.ts region='RoutedComponent'} |
| 115 | + * |
| 116 | + * The root component is reused within the same test in subsequent calls to `navigateByUrl`. |
| 117 | + * |
| 118 | + * This function also makes it easier to test components that depend on `ActivatedRoute` data. |
| 119 | + * |
| 120 | + * {@example router/testing/test/router_testing_harness_examples.spec.ts region='ActivatedRoute'} |
| 121 | + * |
| 122 | + * @param url The target of the navigation. Passed to `Router.navigateByUrl`. |
| 123 | + * @param requiredRoutedComponentType After navigation completes, the required type for the |
| 124 | + * activated component of the `RouterOutlet`. If the outlet is not activated or a different |
| 125 | + * component is activated, this function will throw an error. |
| 126 | + * @returns The activated component instance of the `RouterOutlet` after navigation completes. |
| 127 | + */ |
| 128 | + async navigateByUrl<T>(url: string, requiredRoutedComponentType: Type<T>): Promise<T>; |
| 129 | + async navigateByUrl<T>(url: string, requiredRoutedComponentType?: Type<T>): Promise<T|null> { |
| 130 | + const router = TestBed.inject(Router); |
| 131 | + let resolveFn!: () => void; |
| 132 | + const redirectTrackingPromise = new Promise<void>(resolve => { |
| 133 | + resolveFn = resolve; |
| 134 | + }); |
| 135 | + afterNextNavigation(TestBed.inject(Router), resolveFn); |
| 136 | + await router.navigateByUrl(url); |
| 137 | + await redirectTrackingPromise; |
| 138 | + this.fixture.detectChanges(); |
| 139 | + const outlet = this.fixture.componentInstance.outlet; |
| 140 | + // The outlet might not be activated if the user is testing a navigation for a guard that |
| 141 | + // rejects |
| 142 | + if (outlet && outlet.isActivated && outlet.activatedRoute.component) { |
| 143 | + const activatedComponent = outlet.component; |
| 144 | + if (requiredRoutedComponentType !== undefined && |
| 145 | + !(activatedComponent instanceof requiredRoutedComponentType)) { |
| 146 | + throw new Error(`Unexpected routed component type. Expected ${ |
| 147 | + requiredRoutedComponentType.name} but got ${activatedComponent.constructor.name}`); |
| 148 | + } |
| 149 | + return activatedComponent as T; |
| 150 | + } else { |
| 151 | + return null; |
| 152 | + } |
| 153 | + } |
| 154 | +} |
0 commit comments