_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/core/test/acceptance/injector_profiler_spec.ts_0_1678
/** * @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 {NgForOf, PercentPipe} from '@angular/common'; import { afterRender, ClassProvider, Component, Directive, ElementRef, inject, Injectable, InjectFlags, InjectionToken, Injector, NgModule, NgModuleRef, QueryList, ViewChild, ViewChildren, } from '@angular/core'; import {NullInjector} from '@angular/core/src/di/null_injector'; import { isClassProvider, isExistingProvider, isFactoryProvider, isTypeProvider, isValueProvider, } from '@angular/core/src/di/provider_collection'; import {EnvironmentInjector, R3Injector} from '@angular/core/src/di/r3_injector'; import {setupFrameworkInjectorProfiler} from '@angular/core/src/render3/debug/framework_injector_profiler'; import { getInjectorProfilerContext, InjectedServiceEvent, InjectorCreatedInstanceEvent, InjectorProfilerEvent, InjectorProfilerEventType, ProviderConfiguredEvent, setInjectorProfiler, } from '@angular/core/src/render3/debug/injector_profiler'; import {getNodeInjectorLView, NodeInjector} from '@angular/core/src/render3/di'; import { getDependenciesFromInjectable, getInjectorMetadata, getInjectorProviders, getInjectorResolutionPath, } from '@angular/core/src/render3/util/injector_discovery_utils'; import {fakeAsync, tick} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing/src/test_bed'; import {BrowserModule} from '@angular/platform-browser'; import {Router, RouterModule, RouterOutlet} from '@angular/router';
{ "end_byte": 1678, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/injector_profiler_spec.ts" }
angular/packages/core/test/acceptance/injector_profiler_spec.ts_1680_9468
describe('setProfiler', () => { let injectEvents: InjectedServiceEvent[] = []; let createEvents: InjectorCreatedInstanceEvent[] = []; let providerConfiguredEvents: ProviderConfiguredEvent[] = []; function searchForProfilerEvent<T extends InjectorProfilerEvent>( events: T[], condition: (event: T) => boolean, ): T | undefined { return events.find((event) => condition(event)) as T; } beforeEach(() => { injectEvents = []; createEvents = []; providerConfiguredEvents = []; setInjectorProfiler((injectorProfilerEvent: InjectorProfilerEvent) => { const {type} = injectorProfilerEvent; if (type === InjectorProfilerEventType.Inject) { injectEvents.push({ service: injectorProfilerEvent.service, context: getInjectorProfilerContext(), type, }); } if (type === InjectorProfilerEventType.InstanceCreatedByInjector) { createEvents.push({ instance: injectorProfilerEvent.instance, context: getInjectorProfilerContext(), type, }); } if (type === InjectorProfilerEventType.ProviderConfigured) { providerConfiguredEvents.push({ providerRecord: injectorProfilerEvent.providerRecord, context: getInjectorProfilerContext(), type, }); } }); }); afterAll(() => setInjectorProfiler(null)); it('should emit DI events when a component contains a provider and injects it', () => { class MyService {} @Component({ selector: 'my-comp', template: 'hello world', providers: [MyService], standalone: false, }) class MyComponent { myService = inject(MyService); } TestBed.configureTestingModule({declarations: [MyComponent]}); const fixture = TestBed.createComponent(MyComponent); const myComp = fixture.componentInstance; // MyService should have been configured const myServiceProviderConfiguredEvent = searchForProfilerEvent<ProviderConfiguredEvent>( providerConfiguredEvents, (event) => event.providerRecord.token === MyService, ); expect(myServiceProviderConfiguredEvent).toBeTruthy(); // inject(MyService) was called const myServiceInjectEvent = searchForProfilerEvent<InjectedServiceEvent>( injectEvents, (event) => event.service.token === MyService, ); expect(myServiceInjectEvent).toBeTruthy(); expect(myServiceInjectEvent!.service.value).toBe(myComp.myService); expect(myServiceInjectEvent!.service.flags).toBe(InjectFlags.Default); // myComp is an angular instance that is able to call `inject` in it's constructor, so a // create event should have been emitted for it const componentCreateEvent = searchForProfilerEvent<InjectorCreatedInstanceEvent>( createEvents, (event) => event.instance.value === myComp, ); expect(componentCreateEvent).toBeTruthy(); }); it('should emit the correct DI events when a service is injected with injection flags', () => { class MyService {} class MyServiceB {} class MyServiceC {} @Component({ selector: 'my-comp', template: 'hello world', providers: [MyService, {provide: MyServiceB, useValue: 0}], standalone: false, }) class MyComponent { myService = inject(MyService, {self: true}); myServiceD = inject(MyServiceB, {skipSelf: true}); myServiceC = inject(MyServiceC, {optional: true}); } TestBed.configureTestingModule({ providers: [MyServiceB, MyServiceC, {provide: MyServiceB, useValue: 1}], declarations: [MyComponent], }); TestBed.createComponent(MyComponent); const myServiceInjectEvent = searchForProfilerEvent<InjectedServiceEvent>( injectEvents, (event) => event.service.token === MyService, ); const myServiceBInjectEvent = searchForProfilerEvent( injectEvents, (event) => event.service.token === MyServiceB, ); const myServiceCInjectEvent = searchForProfilerEvent( injectEvents, (event) => event.service.token === MyServiceC, ); expect(myServiceInjectEvent!.service.flags).toBe(InjectFlags.Self); expect(myServiceBInjectEvent!.service.flags).toBe(InjectFlags.SkipSelf); expect(myServiceBInjectEvent!.service.value).toBe(1); expect(myServiceCInjectEvent!.service.flags).toBe(InjectFlags.Optional); }); it('should emit correct DI events when providers are configured with useFactory, useExisting, useClass, useValue', () => { class MyService {} class MyServiceB {} class MyServiceC {} class MyServiceD {} class MyServiceE {} @Component({ selector: 'my-comp', template: 'hello world', providers: [ MyService, {provide: MyServiceB, useFactory: () => new MyServiceB()}, {provide: MyServiceC, useExisting: MyService}, {provide: MyServiceD, useValue: 'hello world'}, {provide: MyServiceE, useClass: class MyExampleClass {}}, ], standalone: false, }) class MyComponent { myService = inject(MyService); } TestBed.configureTestingModule({declarations: [MyComponent]}); TestBed.createComponent(MyComponent); // MyService should have been configured const myServiceProviderConfiguredEvent = searchForProfilerEvent<ProviderConfiguredEvent>( providerConfiguredEvents, (event) => event.providerRecord.token === MyService, ); const myServiceBProviderConfiguredEvent = searchForProfilerEvent<ProviderConfiguredEvent>( providerConfiguredEvents, (event) => event.providerRecord.token === MyServiceB, ); const myServiceCProviderConfiguredEvent = searchForProfilerEvent<ProviderConfiguredEvent>( providerConfiguredEvents, (event) => event.providerRecord.token === MyServiceC, ); const myServiceDProviderConfiguredEvent = searchForProfilerEvent<ProviderConfiguredEvent>( providerConfiguredEvents, (event) => event.providerRecord.token === MyServiceD, ); const myServiceEProviderConfiguredEvent = searchForProfilerEvent<ProviderConfiguredEvent>( providerConfiguredEvents, (event) => event.providerRecord.token === MyServiceE, ); expect(isTypeProvider(myServiceProviderConfiguredEvent!.providerRecord.provider!)).toBeTrue(); expect( isFactoryProvider(myServiceBProviderConfiguredEvent!.providerRecord.provider!), ).toBeTrue(); expect( isExistingProvider(myServiceCProviderConfiguredEvent!.providerRecord.provider!), ).toBeTrue(); expect(isValueProvider(myServiceDProviderConfiguredEvent!.providerRecord.provider!)).toBeTrue(); expect(isClassProvider(myServiceEProviderConfiguredEvent!.providerRecord.provider!)).toBeTrue(); }); it('should emit correct DI events when providers are configured with multi', () => { class MyService {} @Component({ selector: 'my-comp', template: 'hello world', providers: [ {provide: MyService, useClass: MyService, multi: true}, {provide: MyService, useFactory: () => new MyService(), multi: true}, {provide: MyService, useValue: 'hello world', multi: true}, ], standalone: false, }) class MyComponent { myService = inject(MyService); } TestBed.configureTestingModule({declarations: [MyComponent]}); TestBed.createComponent(MyComponent); // MyService should have been configured const myServiceProviderConfiguredEvent = searchForProfilerEvent<ProviderConfiguredEvent>( providerConfiguredEvents, (event) => event.providerRecord.token === MyService, ); expect( (myServiceProviderConfiguredEvent!.providerRecord?.provider as ClassProvider).multi, ).toBeTrue(); });
{ "end_byte": 9468, "start_byte": 1680, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/injector_profiler_spec.ts" }
angular/packages/core/test/acceptance/injector_profiler_spec.ts_9472_17114
it('should emit correct DI events when service providers are configured with providedIn', () => { @Injectable({providedIn: 'root'}) class RootService {} @Injectable({providedIn: 'platform'}) class PlatformService {} const providedInRootInjectionToken = new InjectionToken('providedInRootInjectionToken', { providedIn: 'root', factory: () => 'hello world', }); const providedInPlatformToken = new InjectionToken('providedInPlatformToken', { providedIn: 'platform', factory: () => 'hello world', }); @Component({ selector: 'my-comp', template: 'hello world', standalone: false, }) class MyComponent { rootService = inject(RootService); platformService = inject(PlatformService); fromRoot = inject(providedInRootInjectionToken); fromPlatform = inject(providedInPlatformToken); } TestBed.configureTestingModule({declarations: [MyComponent]}); TestBed.createComponent(MyComponent); // MyService should have been configured const rootServiceProviderConfiguredEvent = searchForProfilerEvent<ProviderConfiguredEvent>( providerConfiguredEvents, (event) => event.providerRecord.token === RootService, ); expect(rootServiceProviderConfiguredEvent).toBeTruthy(); expect(rootServiceProviderConfiguredEvent!.context).toBeTruthy(); expect(rootServiceProviderConfiguredEvent!.context!.injector).toBeInstanceOf(R3Injector); expect( (rootServiceProviderConfiguredEvent!.context!.injector as R3Injector).scopes.has('root'), ).toBeTrue(); const platformServiceProviderConfiguredEvent = searchForProfilerEvent<ProviderConfiguredEvent>( providerConfiguredEvents, (event) => event.providerRecord.token === PlatformService, ); expect(platformServiceProviderConfiguredEvent).toBeTruthy(); expect(platformServiceProviderConfiguredEvent!.context).toBeTruthy(); expect(platformServiceProviderConfiguredEvent!.context!.injector).toBeInstanceOf(R3Injector); expect( (platformServiceProviderConfiguredEvent!.context!.injector as R3Injector).scopes.has( 'platform', ), ).toBeTrue(); const providedInRootInjectionTokenProviderConfiguredEvent = searchForProfilerEvent<ProviderConfiguredEvent>( providerConfiguredEvents, (event) => event.providerRecord.token === providedInRootInjectionToken, ); expect(providedInRootInjectionTokenProviderConfiguredEvent).toBeTruthy(); expect(providedInRootInjectionTokenProviderConfiguredEvent!.context).toBeTruthy(); expect(providedInRootInjectionTokenProviderConfiguredEvent!.context!.injector).toBeInstanceOf( R3Injector, ); expect( ( providedInRootInjectionTokenProviderConfiguredEvent!.context!.injector as R3Injector ).scopes.has('root'), ).toBeTrue(); expect(providedInRootInjectionTokenProviderConfiguredEvent!.providerRecord.token).toBe( providedInRootInjectionToken, ); const providedInPlatformTokenProviderConfiguredEvent = searchForProfilerEvent<ProviderConfiguredEvent>( providerConfiguredEvents, (event) => event.providerRecord.token === providedInPlatformToken, ); expect(providedInPlatformTokenProviderConfiguredEvent).toBeTruthy(); expect(providedInPlatformTokenProviderConfiguredEvent!.context).toBeTruthy(); expect(providedInPlatformTokenProviderConfiguredEvent!.context!.injector).toBeInstanceOf( R3Injector, ); expect( (providedInPlatformTokenProviderConfiguredEvent!.context!.injector as R3Injector).scopes.has( 'platform', ), ).toBeTrue(); expect(providedInPlatformTokenProviderConfiguredEvent!.providerRecord.token).toBe( providedInPlatformToken, ); }); }); describe('getInjectorMetadata', () => { it('should be able to determine injector type and name', fakeAsync(() => { class MyServiceA {} @NgModule({providers: [MyServiceA]}) class ModuleA {} class MyServiceB {} @NgModule({providers: [MyServiceB]}) class ModuleB {} @Component({ selector: 'lazy-comp', template: `lazy component`, standalone: true, imports: [ModuleB], }) class LazyComponent { lazyComponentNodeInjector = inject(Injector); elementRef = inject(ElementRef); constructor() { afterRender(() => afterLazyComponentRendered(this)); } } @Component({ standalone: true, imports: [RouterOutlet, ModuleA], template: `<router-outlet/>`, }) class MyStandaloneComponent { @ViewChild(RouterOutlet, {read: ElementRef}) routerOutlet: ElementRef | undefined; elementRef = inject(ElementRef); } TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ { path: 'lazy', loadComponent: () => LazyComponent, }, ]), ], }); const root = TestBed.createComponent(MyStandaloneComponent); TestBed.inject(Router).navigateByUrl('/lazy'); tick(); root.detectChanges(); function afterLazyComponentRendered(lazyComponent: LazyComponent) { const {lazyComponentNodeInjector} = lazyComponent; const myStandaloneComponent = lazyComponentNodeInjector.get(MyStandaloneComponent, null, { skipSelf: true, })!; expect(myStandaloneComponent).toBeInstanceOf(MyStandaloneComponent); expect(myStandaloneComponent.routerOutlet).toBeInstanceOf(ElementRef); const injectorPath = getInjectorResolutionPath(lazyComponentNodeInjector); const injectorMetadata = injectorPath.map((injector) => getInjectorMetadata(injector)); expect(injectorMetadata[0]).toBeDefined(); expect(injectorMetadata[1]).toBeDefined(); expect(injectorMetadata[2]).toBeDefined(); expect(injectorMetadata[3]).toBeDefined(); expect(injectorMetadata[4]).toBeDefined(); expect(injectorMetadata[5]).toBeDefined(); expect(injectorMetadata[6]).toBeDefined(); expect(injectorMetadata[0]!.source).toBe(lazyComponent.elementRef.nativeElement); expect(injectorMetadata[1]!.source).toBe(myStandaloneComponent.routerOutlet!.nativeElement); expect(injectorMetadata[2]!.source).toBe(myStandaloneComponent.elementRef.nativeElement); expect(injectorMetadata[3]!.source).toBe('Standalone[LazyComponent]'); expect(injectorMetadata[4]!.source).toBe('DynamicTestModule'); expect(injectorMetadata[5]!.source).toBe('Platform: core'); expect(injectorMetadata[0]!.type).toBe('element'); expect(injectorMetadata[1]!.type).toBe('element'); expect(injectorMetadata[2]!.type).toBe('element'); expect(injectorMetadata[3]!.type).toBe('environment'); expect(injectorMetadata[4]!.type).toBe('environment'); expect(injectorMetadata[5]!.type).toBe('environment'); } })); it('should return null for injectors it does not recognize', () => { class MockInjector extends Injector { override get(): void { throw new Error('Method not implemented.'); } } const mockInjector = new MockInjector(); expect(getInjectorMetadata(mockInjector)).toBeNull(); }); it('should return null as the source for an R3Injector with no source.', () => { const emptyR3Injector = new R3Injector([], new NullInjector(), null, new Set()); const r3InjectorMetadata = getInjectorMetadata(emptyR3Injector); expect(r3InjectorMetadata).toBeDefined(); expect(r3InjectorMetadata!.source).toBeNull(); expect(r3InjectorMetadata!.type).toBe('environment'); }); });
{ "end_byte": 17114, "start_byte": 9472, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/injector_profiler_spec.ts" }
angular/packages/core/test/acceptance/injector_profiler_spec.ts_17116_21839
describe('getInjectorProviders', () => { beforeEach(() => setupFrameworkInjectorProfiler()); afterAll(() => setInjectorProfiler(null)); it('should be able to get the providers from a components injector', () => { class MyService {} @Component({ selector: 'my-comp', template: ` {{b | percent:'4.3-5' }} `, providers: [MyService], standalone: false, }) class MyComponent { b = 1.3495; } TestBed.configureTestingModule({declarations: [MyComponent], imports: [PercentPipe]}); const fixture = TestBed.createComponent(MyComponent); const providers = getInjectorProviders(fixture.debugElement.injector); expect(providers.length).toBe(1); expect(providers[0].token).toBe(MyService); expect(providers[0].provider).toBe(MyService); expect(providers[0].isViewProvider).toBe(false); }); it('should be able to get determine if a provider is a view provider', () => { class MyService {} @Component({ selector: 'my-comp', template: ` {{b | percent:'4.3-5' }} `, viewProviders: [MyService], standalone: false, }) class MyComponent { b = 1.3495; } TestBed.configureTestingModule({declarations: [MyComponent], imports: [PercentPipe]}); const fixture = TestBed.createComponent(MyComponent); const providers = getInjectorProviders(fixture.debugElement.injector); expect(providers.length).toBe(1); expect(providers[0].token).toBe(MyService); expect(providers[0].provider).toBe(MyService); expect(providers[0].isViewProvider).toBe(true); }); it('should be able to determine import paths after module provider flattening in the NgModule bootstrap case', () => { // ┌─────────┐ // │AppModule│ // └────┬────┘ // │ // imports // │ // ┌────▼────┐ // ┌─imports─┤ ModuleD ├──imports─┐ // │ └─────────┘ │ // │ ┌─────▼─────┐ // ┌───▼───┐ │ ModuleC │ // │ModuleB│ │-MyServiceB│ // └───┬───┘ └───────────┘ // │ // imports // │ // ┌────▼─────┐ // │ ModuleA │ // │-MyService│ // └──────────┘ class MyService {} class MyServiceB {} @NgModule({providers: [MyService]}) class ModuleA {} @NgModule({ imports: [ModuleA], }) class ModuleB {} @NgModule({providers: [MyServiceB]}) class ModuleC {} @NgModule({ imports: [ModuleB, ModuleC], }) class ModuleD {} @Component({ selector: 'my-comp', template: 'hello world', standalone: false, }) class MyComponent {} @NgModule({ imports: [ModuleD, BrowserModule], declarations: [MyComponent], }) class AppModule {} TestBed.configureTestingModule({imports: [AppModule]}); const root = TestBed.createComponent(MyComponent); root.detectChanges(); const appModuleInjector = root.componentRef.injector.get(EnvironmentInjector); const providers = getInjectorProviders(appModuleInjector); const myServiceProvider = providers.find((provider) => provider.token === MyService); const myServiceBProvider = providers.find((provider) => provider.token === MyServiceB); const testModuleType = root.componentRef.injector.get(NgModuleRef).instance.constructor; expect(myServiceProvider).toBeTruthy(); expect(myServiceBProvider).toBeTruthy(); expect(myServiceProvider!.importPath).toBeInstanceOf(Array); expect(myServiceProvider!.importPath!.length).toBe(5); expect(myServiceProvider!.importPath![0]).toBe(testModuleType); expect(myServiceProvider!.importPath![1]).toBe(AppModule); expect(myServiceProvider!.importPath![2]).toBe(ModuleD); expect(myServiceProvider!.importPath![3]).toBe(ModuleB); expect(myServiceProvider!.importPath![4]).toBe(ModuleA); expect(myServiceBProvider!.importPath).toBeInstanceOf(Array); expect(myServiceBProvider!.importPath!.length).toBe(4); expect(myServiceBProvider!.importPath![0]).toBe(testModuleType); expect(myServiceBProvider!.importPath![1]).toBe(AppModule); expect(myServiceBProvider!.importPath![2]).toBe(ModuleD); expect(myServiceBProvider!.importPath![3]).toBe(ModuleC); }); it('should be able to determine import paths after module provider flattening in the standalone component case', () => { // ┌────────────────────imports───────────────────────┐ // │ │ //
{ "end_byte": 21839, "start_byte": 17116, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/injector_profiler_spec.ts" }
angular/packages/core/test/acceptance/injector_profiler_spec.ts_21843_27801
│ ┌───────imports────────┐ │ // │ │ │ │ // │ │ │ │ // ┌─────────┴─┴─────────┐ ┌─────────▼────────────┐ ┌──────────▼───────────┐ // │MyStandaloneComponent│ │MyStandaloneComponentB│ │MyStandaloneComponentC│ // └──────────┬──────────┘ └──────────┬────┬──────┘ └────┬────────┬────────┘ // │ │ │ │ │ // └──imports─┐ ┌imports┘ └────┐ │ │ // │ │ │ │ imports // ┌▼─────▼┐ imports │ │ // ┌────┤ModuleD├─────┐ │ imports │ // imports └───────┘ │ │ │ ┌───▼────────┐ // │ imports ┌──▼─────┐ │ │ ModuleE │ // ┌──▼────┐ │ │ModuleF │ │ │-MyServiceC │ // │ModuleB│ │ └────────┘ │ └────────────┘ // └──┬────┘ ┌─────▼─────┐ │ // imports │ ModuleC │ │ // ┌────▼─────┐ │-MyServiceB│◄────────────┘ // │ ModuleA │ └───────────┘ // │-MyService│ // └──────────┘ class MyService {} class MyServiceB {} class MyServiceC {} @NgModule({providers: [MyService]}) class ModuleA {} @NgModule({ imports: [ModuleA], }) class ModuleB {} @NgModule({providers: [MyServiceB]}) class ModuleC {} @NgModule({ imports: [ModuleB, ModuleC], }) class ModuleD {} @NgModule({ providers: [MyServiceC], }) class ModuleE {} @NgModule({}) class ModuleF {} @Component({ selector: 'my-comp-c', template: 'hello world', imports: [ModuleE, ModuleC], standalone: true, }) class MyStandaloneComponentC {} @Component({ selector: 'my-comp-b', template: 'hello world', imports: [ModuleD, ModuleF], standalone: true, }) class MyStandaloneComponentB {} @Component({ selector: 'my-comp', template: ` <my-comp-b/> <my-comp-c/> `, imports: [ModuleD, MyStandaloneComponentB, MyStandaloneComponentC], standalone: true, }) class MyStandaloneComponent {} const root = TestBed.createComponent(MyStandaloneComponent); root.detectChanges(); const appComponentEnvironmentInjector = root.componentRef.injector.get(EnvironmentInjector); const providers = getInjectorProviders(appComponentEnvironmentInjector); // There are 2 paths from MyStandaloneComponent to MyService // // path 1: MyStandaloneComponent -> ModuleD => ModuleB -> ModuleA // path 2: MyStandaloneComponent -> MyStandaloneComponentB -> ModuleD => ModuleB -> ModuleA // // Angular discovers this provider through the first path it visits // during it's postorder traversal (in this case path 1). Therefore // we expect myServiceProvider.importPath to have 4 DI containers // const myServiceProvider = providers.find((provider) => provider.token === MyService); expect(myServiceProvider).toBeTruthy(); expect(myServiceProvider!.importPath).toBeInstanceOf(Array); expect(myServiceProvider!.importPath!.length).toBe(4); expect(myServiceProvider!.importPath![0]).toBe(MyStandaloneComponent); expect(myServiceProvider!.importPath![1]).toBe(ModuleD); expect(myServiceProvider!.importPath![2]).toBe(ModuleB); expect(myServiceProvider!.importPath![3]).toBe(ModuleA); // Similarly to above there are multiple paths from MyStandaloneComponent MyServiceB // // path 1: MyStandaloneComponent -> ModuleD => ModuleC // path 2: MyStandaloneComponent -> MyStandaloneComponentB -> ModuleD => ModuleC // path 3: MyStandaloneComponent -> MyStandaloneComponentC -> ModuleC // // Angular discovers this provider through the first path it visits // during it's postorder traversal (in this case path 1). Therefore // we expect myServiceProvider.importPath to have 4 DI containers // const myServiceBProvider = providers.find((provider) => provider.token === MyServiceB); expect(myServiceBProvider).toBeTruthy(); expect(myServiceBProvider!.importPath).toBeInstanceOf(Array); expect(myServiceBProvider!.importPath!.length).toBe(3); expect(myServiceBProvider!.importPath![0]).toBe(MyStandaloneComponent); expect(myServiceBProvider!.importPath![1]).toBe(ModuleD); expect(myServiceBProvider!.importPath![2]).toBe(ModuleC); }); it('should be able to determine import paths after module provider flattening in the standalone component case with lazy components', fakeAsync(() => { class MyService {} @NgModule({providers: [MyService]}) class ModuleA {} @Component({ selector: 'my-comp-b', template: 'hello world', imports: [ModuleA], standalone: true, }) class MyStandaloneComponentB { injector = inject(Injector); } @Component({ selector: 'my-comp', template: `<router-outlet/>`, imports: [MyStandaloneComponentB, RouterOutlet], standalone: true, }) class MyStandaloneComponent { injector = inject(Injector); @ViewChild(RouterOutlet) routerOutlet: RouterOutlet | undefined; } TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ { path: 'lazy', loadComponent: () => MyStandaloneComponentB, }, ]), ], }); const root = TestBed.createComponent(MyStandaloneComponent); TestBed.inject(Router).navigateByUrl('/lazy'); tick(); root.detectChanges(); const myS
{ "end_byte": 27801, "start_byte": 21843, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/injector_profiler_spec.ts" }
angular/packages/core/test/acceptance/injector_profiler_spec.ts_27805_35514
aloneComponentNodeInjector = root.componentRef.injector; const myStandaloneComponentEnvironmentInjector = myStandaloneComponentNodeInjector.get(EnvironmentInjector); const myStandalonecomponentB = root.componentRef.instance!.routerOutlet! .component as MyStandaloneComponentB; const myComponentBNodeInjector = myStandalonecomponentB.injector; const myComponentBEnvironmentInjector = myComponentBNodeInjector.get(EnvironmentInjector); const myStandaloneComponentEnvironmentInjectorProviders = getInjectorProviders( myStandaloneComponentEnvironmentInjector, ); const myComponentBEnvironmentInjectorProviders = getInjectorProviders( myComponentBEnvironmentInjector, ); // Lazy component should have its own environment injector and therefore different // providers expect(myStandaloneComponentEnvironmentInjectorProviders).not.toEqual( myComponentBEnvironmentInjectorProviders, ); const myServiceProviderRecord = myComponentBEnvironmentInjectorProviders.find( (provider) => provider.token === MyService, ); expect(myServiceProviderRecord).toBeTruthy(); expect(myServiceProviderRecord!.importPath).toBeInstanceOf(Array); expect(myServiceProviderRecord!.importPath!.length).toBe(2); expect(myServiceProviderRecord!.importPath![0]).toBe(MyStandaloneComponentB); expect(myServiceProviderRecord!.importPath![1]).toBe(ModuleA); })); it('should be able to determine providers in a lazy route that has providers', fakeAsync(() => { class MyService {} @Component({selector: 'my-comp-b', template: 'hello world', standalone: true}) class MyStandaloneComponentB { injector = inject(Injector); } @Component({ selector: 'my-comp', template: `<router-outlet/>`, imports: [MyStandaloneComponentB, RouterOutlet], standalone: true, }) class MyStandaloneComponent { injector = inject(Injector); @ViewChild(RouterOutlet) routerOutlet: RouterOutlet | undefined; } TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ { path: 'lazy', loadComponent: () => MyStandaloneComponentB, providers: [MyService], }, ]), ], }); const root = TestBed.createComponent(MyStandaloneComponent); TestBed.inject(Router).navigateByUrl('/lazy'); tick(); root.detectChanges(); const myStandalonecomponentB = root.componentRef.instance!.routerOutlet! .component as MyStandaloneComponentB; const routeEnvironmentInjector = myStandalonecomponentB.injector.get( EnvironmentInjector, ) as R3Injector; expect(routeEnvironmentInjector).toBeTruthy(); expect(routeEnvironmentInjector.source).toBeTruthy(); expect(routeEnvironmentInjector.source!.startsWith('Route:')).toBeTrue(); const myComponentBEnvironmentInjectorProviders = getInjectorProviders(routeEnvironmentInjector); const myServiceProviderRecord = myComponentBEnvironmentInjectorProviders.find( (provider) => provider.token === MyService, ); expect(myServiceProviderRecord).toBeTruthy(); expect(myServiceProviderRecord!.provider).toBe(MyService); expect(myServiceProviderRecord!.token).toBe(MyService); })); it('should be able to determine providers in an injector that was created manually', fakeAsync(() => { class MyService {} const injector = Injector.create({providers: [MyService]}) as EnvironmentInjector; const providers = getInjectorProviders(injector); expect(providers.length).toBe(1); expect(providers[0].token).toBe(MyService); expect(providers[0].provider).toBe(MyService); })); it('should be able to get injector providers for element injectors created by components rendering in an ngFor', () => { class MyService {} @Component({selector: 'item-cmp', template: 'item', standalone: true, providers: [MyService]}) class ItemComponent { injector = inject(Injector); } @Component({ selector: 'my-comp', template: ` <item-cmp *ngFor="let item of items"></item-cmp> `, imports: [ItemComponent, NgForOf], standalone: true, }) class MyStandaloneComponent { injector = inject(Injector); items = [1, 2, 3]; @ViewChildren(ItemComponent) itemComponents: QueryList<ItemComponent> | undefined; } const root = TestBed.createComponent(MyStandaloneComponent); root.detectChanges(); const myStandaloneComponent = root.componentRef.instance; const itemComponents = myStandaloneComponent.itemComponents; expect(itemComponents).toBeInstanceOf(QueryList); expect(itemComponents?.length).toBe(3); itemComponents!.forEach((item) => { const itemProviders = getInjectorProviders(item.injector); expect(itemProviders).toBeInstanceOf(Array); expect(itemProviders.length).toBe(1); expect(itemProviders[0].token).toBe(MyService); expect(itemProviders[0].provider).toBe(MyService); expect(itemProviders[0].isViewProvider).toBe(false); }); }); it('should be able to get injector providers for element injectors created by components rendering in a @for', () => { class MyService {} @Component({selector: 'item-cmp', template: 'item', standalone: true, providers: [MyService]}) class ItemComponent { injector = inject(Injector); } @Component({ selector: 'my-comp', template: ` @for (item of items; track item) { <item-cmp></item-cmp> } `, imports: [ItemComponent], standalone: true, }) class MyStandaloneComponent { injector = inject(Injector); items = [1, 2, 3]; @ViewChildren(ItemComponent) itemComponents: QueryList<ItemComponent> | undefined; } const root = TestBed.createComponent(MyStandaloneComponent); root.detectChanges(); const myStandaloneComponent = root.componentRef.instance; const itemComponents = myStandaloneComponent.itemComponents; expect(itemComponents).toBeInstanceOf(QueryList); expect(itemComponents?.length).toBe(3); itemComponents!.forEach((item) => { const itemProviders = getInjectorProviders(item.injector); expect(itemProviders).toBeInstanceOf(Array); expect(itemProviders.length).toBe(1); expect(itemProviders[0].token).toBe(MyService); expect(itemProviders[0].provider).toBe(MyService); expect(itemProviders[0].isViewProvider).toBe(false); }); }); }); describe('getDependenciesFromInjectable', () => { beforeEach(() => setupFrameworkInjectorProfiler()); afterAll(() => setInjectorProfiler(null)); it('should be able to determine which injector dependencies come from', fakeAsync(() => { class MyService {} class MyServiceB {} class MyServiceC {} class MyServiceD {} class MyServiceG {} class MyServiceH {} const myInjectionToken = new InjectionToken('myInjectionToken'); const myServiceCInstance = new MyServiceC(); @NgModule({ providers: [ MyService, {provide: MyServiceB, useValue: 'hello world'}, {provide: MyServiceC, useFactory: () => 123}, {provide: myInjectionToken, useValue: myServiceCInstance}, ], }) class ModuleA {} @Directive({ selector: '[my-directive]', standalone: true, }) class MyStandaloneDirective { serviceFromHost = inject(MyServiceH, {host: true, optional: true}); injector = inject(Injector); ngOnInit() { onMyStandaloneDirectiveCreated(this); } } @Component({ selector: 'my-comp-c', template: 'hello world
{ "end_byte": 35514, "start_byte": 27805, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/injector_profiler_spec.ts" }
angular/packages/core/test/acceptance/injector_profiler_spec.ts_35516_42732
imports: [], standalone: true, }) class MyStandaloneComponentC {} @Component({ selector: 'my-comp-b', template: '<my-comp-c my-directive/>', imports: [MyStandaloneComponentC, MyStandaloneDirective], standalone: true, }) class MyStandaloneComponentB { myService = inject(MyService, {optional: true}); myServiceB = inject(MyServiceB, {optional: true}); myServiceC = inject(MyServiceC, {skipSelf: true, optional: true}); myInjectionTokenValue = inject(myInjectionToken, {optional: true}); injector = inject(Injector, {self: true, host: true}); myServiceD = inject(MyServiceD); myServiceG = inject(MyServiceG); parentComponent = inject(MyStandaloneComponent); } @Component({ selector: 'my-comp', template: `<router-outlet/>`, imports: [RouterOutlet, ModuleA], providers: [MyServiceG, {provide: MyServiceH, useValue: 'MyStandaloneComponent'}], standalone: true, }) class MyStandaloneComponent { injector = inject(Injector); @ViewChild(RouterOutlet) routerOutlet: RouterOutlet | undefined; } TestBed.configureTestingModule({ providers: [{provide: MyServiceD, useValue: '123'}], imports: [ RouterModule.forRoot([{path: 'lazy', loadComponent: () => MyStandaloneComponentB}]), ], }); const root = TestBed.createComponent(MyStandaloneComponent); TestBed.inject(Router).navigateByUrl('/lazy'); tick(); root.detectChanges(); const myStandalonecomponentB = root.componentRef.instance!.routerOutlet! .component as MyStandaloneComponentB; const {dependencies: dependenciesOfMyStandaloneComponentB} = getDependenciesFromInjectable( myStandalonecomponentB.injector, MyStandaloneComponentB, )!; const standaloneInjector = root.componentInstance.injector.get( EnvironmentInjector, ) as EnvironmentInjector; expect(dependenciesOfMyStandaloneComponentB).toBeInstanceOf(Array); expect(dependenciesOfMyStandaloneComponentB.length).toBe(8); const myServiceDep = dependenciesOfMyStandaloneComponentB[0]; const myServiceBDep = dependenciesOfMyStandaloneComponentB[1]; const myServiceCDep = dependenciesOfMyStandaloneComponentB[2]; const myInjectionTokenValueDep = dependenciesOfMyStandaloneComponentB[3]; const injectorDep = dependenciesOfMyStandaloneComponentB[4]; const myServiceDDep = dependenciesOfMyStandaloneComponentB[5]; const myServiceGDep = dependenciesOfMyStandaloneComponentB[6]; const parentComponentDep = dependenciesOfMyStandaloneComponentB[7]; expect(myServiceDep.token).toBe(MyService); expect(myServiceBDep.token).toBe(MyServiceB); expect(myServiceCDep.token).toBe(MyServiceC); expect(myInjectionTokenValueDep.token).toBe(myInjectionToken); expect(injectorDep.token).toBe(Injector); expect(myServiceDDep.token).toBe(MyServiceD); expect(myServiceGDep.token).toBe(MyServiceG); expect(parentComponentDep.token).toBe(MyStandaloneComponent); expect(dependenciesOfMyStandaloneComponentB[0].flags).toEqual({ optional: true, skipSelf: false, self: false, host: false, }); expect(myServiceBDep.flags).toEqual({ optional: true, skipSelf: false, self: false, host: false, }); expect(myServiceCDep.flags).toEqual({ optional: true, skipSelf: true, self: false, host: false, }); expect(myInjectionTokenValueDep.flags).toEqual({ optional: true, skipSelf: false, self: false, host: false, }); expect(injectorDep.flags).toEqual({ optional: false, skipSelf: false, self: true, host: true, }); expect(myServiceDDep.flags).toEqual({ optional: false, skipSelf: false, self: false, host: false, }); expect(myServiceGDep.flags).toEqual({ optional: false, skipSelf: false, self: false, host: false, }); expect(parentComponentDep.flags).toEqual({ optional: false, skipSelf: false, self: false, host: false, }); expect(dependenciesOfMyStandaloneComponentB[0].value).toBe(myStandalonecomponentB.myService); expect(myServiceBDep.value).toBe(null); expect(myServiceCDep.value).toBe(null); expect(myInjectionTokenValueDep.value).toBe(null); expect(injectorDep.value).toBe(myStandalonecomponentB.injector); expect(myServiceDDep.value).toBe('123'); expect(myServiceGDep.value).toBe(myStandalonecomponentB.myServiceG); expect(parentComponentDep.value).toBe(myStandalonecomponentB.parentComponent); expect(dependenciesOfMyStandaloneComponentB[0].providedIn).toBe(undefined); expect(myServiceBDep.providedIn).toBe(undefined); expect(myServiceCDep.providedIn).toBe(undefined); expect(myInjectionTokenValueDep.providedIn).toBe(undefined); expect(injectorDep.providedIn).toBe(myStandalonecomponentB.injector); expect(myServiceDDep.providedIn).toBe( standaloneInjector.get(Injector, null, { skipSelf: true, }) as Injector, ); expect(getNodeInjectorLView(myServiceGDep.providedIn as NodeInjector)).toBe( getNodeInjectorLView(myStandalonecomponentB.parentComponent.injector as NodeInjector), ); function onMyStandaloneDirectiveCreated(myStandaloneDirective: MyStandaloneDirective) { const injector = myStandaloneDirective.injector; const deps = getDependenciesFromInjectable(injector, MyStandaloneDirective); expect(deps).not.toBeNull(); expect(deps!.dependencies.length).toBe(2); // MyServiceH, Injector expect(deps!.dependencies[0].token).toBe(MyServiceH); expect(deps!.dependencies[0].flags).toEqual({ optional: true, host: true, self: false, skipSelf: false, }); // The NodeInjector that provides MyService is not in the host path of this injector. expect(deps!.dependencies[0].providedIn).toBeUndefined(); } })); it('should be able to recursively determine dependencies of dependencies by using the providedIn field', fakeAsync(() => { @Injectable() class MyService { myServiceB = inject(MyServiceB); } @Injectable() class MyServiceB { router = inject(Router); } @NgModule({providers: [MyService]}) class ModuleA {} @NgModule({imports: [ModuleA]}) class ModuleB {} @NgModule({providers: [MyServiceB]}) class ModuleC {} @NgModule({imports: [ModuleB, ModuleC]}) class ModuleD {} @Component({selector: 'my-comp', template: 'hello world', imports: [ModuleD], standalone: true}) class MyStandaloneComponent { myService = inject(MyService); } TestBed.configureTestingModule({imports: [RouterModule]}); const root = TestBed.createComponent(MyStandaloneComponent); const {instance, dependencies} = getDependenciesFromInjectable( root.componentRef.injector, root.componentRef.componentType, )!; const standaloneInjector = root.componentRef.injector.get(EnvironmentInjector); expect(instance).toBeInstanceOf(MyStandaloneComponent); expect(d
{ "end_byte": 42732, "start_byte": 35516, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/injector_profiler_spec.ts" }
angular/packages/core/test/acceptance/injector_profiler_spec.ts_42736_52332
dencies).toBeInstanceOf(Array); expect(dependencies.length).toBe(1); const myServiceDependency = dependencies[0]; expect(myServiceDependency.token).toBe(MyService); expect(myServiceDependency.value).toBe((instance as MyStandaloneComponent).myService); expect(myServiceDependency.flags).toEqual({ optional: false, skipSelf: false, self: false, host: false, }); expect(myServiceDependency.providedIn).toBe(standaloneInjector); const {instance: myServiceInstance, dependencies: myServiceDependencies} = getDependenciesFromInjectable(myServiceDependency.providedIn!, myServiceDependency.token!)!; expect(myServiceDependencies).toBeInstanceOf(Array); expect(myServiceDependencies.length).toBe(1); const myServiceBDependency = myServiceDependencies[0]; expect(myServiceBDependency.token).toBe(MyServiceB); expect(myServiceBDependency.value).toBe((myServiceInstance as MyService).myServiceB); expect(myServiceBDependency.flags).toEqual({ optional: false, skipSelf: false, self: false, host: false, }); expect(myServiceBDependency.providedIn).toBe(standaloneInjector); const {instance: myServiceBInstance, dependencies: myServiceBDependencies} = getDependenciesFromInjectable(myServiceBDependency.providedIn!, myServiceBDependency.token!)!; expect(myServiceBDependencies).toBeInstanceOf(Array); expect(myServiceBDependencies.length).toBe(1); const routerDependency = myServiceBDependencies[0]; expect(routerDependency.token).toBe(Router); expect(routerDependency.value).toBe((myServiceBInstance as MyServiceB).router); expect(routerDependency.flags).toEqual({ optional: false, skipSelf: false, self: false, host: false, }); expect(routerDependency.providedIn).toBe((standaloneInjector as R3Injector).parent); })); }); describe('getInjectorResolutionPath', () => { beforeEach(() => setupFrameworkInjectorProfiler()); afterAll(() => setInjectorProfiler(null)); it('should be able to inspect injector hierarchy structure', fakeAsync(() => { class MyServiceA {} @NgModule({providers: [MyServiceA]}) class ModuleA {} class MyServiceB {} @NgModule({providers: [MyServiceB]}) class ModuleB {} @Component({ selector: 'lazy-comp', template: `lazy component`, standalone: true, imports: [ModuleB], }) class LazyComponent { constructor() { onLazyComponentCreated(); } } @Component({ standalone: true, imports: [RouterOutlet, ModuleA], template: `<router-outlet/>`, }) class MyStandaloneComponent { nodeInjector = inject(Injector); envInjector = inject(EnvironmentInjector); } TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ { path: 'lazy', loadComponent: () => LazyComponent, }, ]), ], }); const root = TestBed.createComponent(MyStandaloneComponent); TestBed.inject(Router).navigateByUrl('/lazy'); tick(); root.detectChanges(); function onLazyComponentCreated() { const lazyComponentNodeInjector = inject(Injector); const lazyComponentEnvironmentInjector = inject(EnvironmentInjector); const routerOutletNodeInjector = inject(Injector, {skipSelf: true}) as NodeInjector; const myStandaloneComponent = inject(MyStandaloneComponent); const myStandaloneComponentNodeInjector = myStandaloneComponent.nodeInjector as NodeInjector; const path = getInjectorResolutionPath(lazyComponentNodeInjector); /** * * Here is a diagram of the injectors in our application: * * * * ┌────────────┐ * │NullInjector│ * └─────▲──────┘ * │ * ┌────────────┴────────────────┐ * │EnvironmentInjector(Platform)│ * └────────────▲────────────────┘ * │ * ┌────────────┴────────────┐ * │EnvironmentInjector(Root)│ * └───────────────▲─────────┘ * │ * │ * │ *┌────────────────────────────────────┐ ┌─┴────────────────────────────────────────┐ *│ NodeInjector(MyStandaloneComponent)├─►| EnvironmentInjector(MyStandaloneComponent│ *└────────────────▲───────────────────┘ └────────────▲─────────────────────────────┘ * │ │ * │ │ * │ │ * ┌────────────┴─────────────┐ │ * │NodeInjector(RouterOutlet)├──────────┐ │ * └────────────▲─────────────┘ │ │ * │ │ │ * │ │ │ * │ │ │ * │ │ │ * ┌─────────────┴──────────────┐ ┌──────▼──────────┴────────────────┐ * │ NodeInjector(LazyComponent)├──►EnvironmentInjector(LazyComponent)│ * └────────────────────────────┘ └──────────────────────────────────┘ * * * * * * The Resolution path if we start at NodeInjector(LazyComponent) should be * [ * NodeInjector[LazyComponent], * NodeInjector[RouterOutlet], * NodeInjector[MyStandaloneComponent], * R3Injector[LazyComponent], * R3Injector[Root], * R3Injector[Platform], * NullInjector * ] */ expect(path.length).toBe(7); expect(path[0]).toBe(lazyComponentNodeInjector); expect(path[1]).toBeInstanceOf(NodeInjector); expect(getNodeInjectorLView(path[1] as NodeInjector)).toBe( getNodeInjectorLView(routerOutletNodeInjector), ); expect(path[2]).toBeInstanceOf(NodeInjector); expect(getNodeInjectorLView(path[2] as NodeInjector)).toBe( getNodeInjectorLView(myStandaloneComponentNodeInjector), ); expect(path[3]).toBeInstanceOf(R3Injector); expect(path[3]).toBe(lazyComponentEnvironmentInjector); expect((path[3] as R3Injector).scopes.has('environment')).toBeTrue(); expect((path[3] as R3Injector).source).toBe('Standalone[LazyComponent]'); expect(path[4]).toBeInstanceOf(R3Injector); expect((path[4] as R3Injector).scopes.has('environment')).toBeTrue(); expect((path[4] as R3Injector).source).toBe('DynamicTestModule'); expect((path[4] as R3Injector).scopes.has('root')).toBeTrue(); expect(path[5]).toBeInstanceOf(R3Injector); expect((path[5] as R3Injector).scopes.has('platform')).toBeTrue(); expect(path[6]).toBeInstanceOf(NullInjector); } })); });
{ "end_byte": 52332, "start_byte": 42736, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/injector_profiler_spec.ts" }
angular/packages/core/test/acceptance/after_render_effect_spec.ts_0_7674
/** * @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 { afterNextRender, ApplicationRef, computed, PLATFORM_ID, provideExperimentalZonelessChangeDetection, signal, } from '@angular/core'; import {afterRenderEffect} from '@angular/core/src/render3/reactivity/after_render_effect'; import {TestBed} from '@angular/core/testing'; describe('afterRenderEffect', () => { beforeEach(() => { TestBed.configureTestingModule({providers: [{provide: PLATFORM_ID, useValue: 'browser'}]}); }); it('should support a single callback in the mixedReadWrite phase', () => { const log: string[] = []; const appRef = TestBed.inject(ApplicationRef); afterNextRender(() => log.push('before'), {injector: appRef.injector}); afterRenderEffect(() => log.push('mixedReadWrite'), {injector: appRef.injector}); afterNextRender(() => log.push('after'), {injector: appRef.injector}); appRef.tick(); expect(log).toEqual(['before', 'mixedReadWrite', 'after']); }); it('should run once', () => { const log: string[] = []; const appRef = TestBed.inject(ApplicationRef); afterRenderEffect( { earlyRead: () => log.push('earlyRead'), write: () => log.push('write'), mixedReadWrite: () => log.push('mixedReadWrite'), read: () => log.push('read'), }, {injector: appRef.injector}, ); appRef.tick(); expect(log).toEqual(['earlyRead', 'write', 'mixedReadWrite', 'read']); }); it('should not run when not dirty', () => { const log: string[] = []; const appRef = TestBed.inject(ApplicationRef); afterRenderEffect( { earlyRead: () => log.push('earlyRead'), write: () => log.push('write'), mixedReadWrite: () => log.push('mixedReadWrite'), read: () => log.push('read'), }, {injector: appRef.injector}, ); // We expect an initial run, and clear the log. appRef.tick(); log.length = 0; // The second tick() should not re-run the effects as they're not dirty. appRef.tick(); expect(log.length).toBe(0); }); it('should run when made dirty via signal', () => { const log: string[] = []; const appRef = TestBed.inject(ApplicationRef); const counter = signal(0); afterRenderEffect( { // `earlyRead` depends on `counter` earlyRead: () => log.push(`earlyRead: ${counter()}`), // `write` does not write: () => log.push('write'), }, {injector: appRef.injector}, ); appRef.tick(); log.length = 0; counter.set(1); appRef.tick(); expect(log).toEqual(['earlyRead: 1']); }); it('should not run when not actually dirty from signals', () => { const log: string[] = []; const appRef = TestBed.inject(ApplicationRef); const counter = signal(0); const isEven = computed(() => counter() % 2 === 0); afterRenderEffect( { earlyRead: () => log.push(`earlyRead: ${isEven()}`), }, {injector: appRef.injector}, ); appRef.tick(); log.length = 0; counter.set(2); appRef.tick(); // Should not have run since `isEven()` didn't actually change despite becoming dirty. expect(log.length).toBe(0); }); it('should pass data from one phase to the next via signal', () => { const log: string[] = []; const appRef = TestBed.inject(ApplicationRef); const counter = signal(0); afterRenderEffect( { // `earlyRead` calculates `isEven` earlyRead: () => counter() % 2 === 0, write: (isEven) => log.push(`isEven: ${isEven()}`), }, {injector: appRef.injector}, ); appRef.tick(); log.length = 0; // isEven: false counter.set(1); appRef.tick(); // isEven: true counter.set(2); appRef.tick(); // No change (no log). counter.set(4); appRef.tick(); expect(log).toEqual(['isEven: false', 'isEven: true']); }); it('should run cleanup functions before re-running phase effects', () => { const log: string[] = []; const appRef = TestBed.inject(ApplicationRef); const counter = signal(0); afterRenderEffect( { earlyRead: (onCleanup) => { onCleanup(() => log.push('cleanup earlyRead')); log.push(`earlyRead: ${counter()}`); // Calculate isEven: return counter() % 2 === 0; }, write: (isEven, onCleanup) => { onCleanup(() => log.push('cleanup write')); log.push(`write: ${isEven()}`); }, }, {injector: appRef.injector}, ); // Initial run should run both effects with no cleanup appRef.tick(); expect(log).toEqual(['earlyRead: 0', 'write: true']); log.length = 0; // A counter of 1 will clean up and rerun both effects. counter.set(1); appRef.tick(); expect(log).toEqual(['cleanup earlyRead', 'earlyRead: 1', 'cleanup write', 'write: false']); log.length = 0; // A counter of 3 will clean up and rerun the earlyRead phase only. counter.set(3); appRef.tick(); expect(log).toEqual(['cleanup earlyRead', 'earlyRead: 3']); log.length = 0; // A counter of 4 will then clean up and rerun both effects. counter.set(4); appRef.tick(); expect(log).toEqual(['cleanup earlyRead', 'earlyRead: 4', 'cleanup write', 'write: true']); }); it('should run cleanup functions when destroyed', () => { const log: string[] = []; const appRef = TestBed.inject(ApplicationRef); const ref = afterRenderEffect( { earlyRead: (onCleanup) => { onCleanup(() => log.push('cleanup earlyRead')); }, write: (_, onCleanup) => { onCleanup(() => log.push('cleanup write')); }, mixedReadWrite: (_, onCleanup) => { onCleanup(() => log.push('cleanup mixedReadWrite')); }, read: (_, onCleanup) => { onCleanup(() => log.push('cleanup read')); }, }, {injector: appRef.injector}, ); appRef.tick(); expect(log.length).toBe(0); ref.destroy(); expect(log).toEqual([ 'cleanup earlyRead', 'cleanup write', 'cleanup mixedReadWrite', 'cleanup read', ]); }); it('should schedule CD when dirty', async () => { TestBed.configureTestingModule({ providers: [ provideExperimentalZonelessChangeDetection(), {provide: PLATFORM_ID, useValue: 'browser'}, ], }); const log: string[] = []; const appRef = TestBed.inject(ApplicationRef); const counter = signal(0); afterRenderEffect( {earlyRead: () => log.push(`earlyRead: ${counter()}`)}, {injector: appRef.injector}, ); await appRef.whenStable(); expect(log).toEqual(['earlyRead: 0']); counter.set(1); await appRef.whenStable(); expect(log).toEqual(['earlyRead: 0', 'earlyRead: 1']); }); it('should cause a re-run for hooks that re-dirty themselves', () => { const log: string[] = []; const appRef = TestBed.inject(ApplicationRef); const counter = signal(0); afterRenderEffect( { earlyRead: () => { log.push(`counter: ${counter()}`); // Cause a re-execution when counter is 1. if (counter() === 1) { counter.set(0); } }, }, {injector: appRef.injector}, ); appRef.tick(); log.length = 0; counter.set(1); appRef.tick(); expect(log).toEqual(['counter: 1', 'counter: 0']); });
{ "end_byte": 7674, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/after_render_effect_spec.ts" }
angular/packages/core/test/acceptance/after_render_effect_spec.ts_7678_9146
it('should cause a re-run for hooks that re-dirty earlier hooks', () => { const log: string[] = []; const appRef = TestBed.inject(ApplicationRef); const counter = signal(0); afterRenderEffect( { earlyRead: () => { log.push(`earlyRead: ${counter()}`); return counter(); }, write: (value) => { log.push(`write: ${value()}`); // Cause a re-execution when value from earlyRead is 1. if (value() === 1) { counter.set(0); } }, }, {injector: appRef.injector}, ); appRef.tick(); log.length = 0; counter.set(1); appRef.tick(); expect(log).toEqual(['earlyRead: 1', 'write: 1', 'earlyRead: 0', 'write: 0']); }); it('should not run later hooks when an earlier hook is re-dirtied', () => { const log: string[] = []; const appRef = TestBed.inject(ApplicationRef); const counter = signal(0); afterRenderEffect( { earlyRead: () => { const value = counter(); log.push(`earlyRead: ${value}`); if (value === 1) { counter.set(0); } return value; }, write: (value) => log.push(`write: ${value()}`), }, {injector: appRef.injector}, ); appRef.tick(); log.length = 0; counter.set(1); appRef.tick(); expect(log).toEqual(['earlyRead: 1', 'earlyRead: 0', 'write: 0']); }); });
{ "end_byte": 9146, "start_byte": 7678, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/after_render_effect_spec.ts" }
angular/packages/core/test/acceptance/embedded_views_spec.ts_0_2237
/** * @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, Input} from '@angular/core'; import {TestBed} from '@angular/core/testing'; describe('embedded views', () => { it('should correctly resolve the implicit receiver in expressions', () => { const items: string[] = []; @Component({ selector: 'child-cmp', template: 'Child', standalone: false, }) class ChildCmp { @Input() addItemFn: Function | undefined; } @Component({ template: `<child-cmp *ngIf="true" [addItemFn]="addItem.bind(this)"></child-cmp>`, standalone: false, }) class TestCmp { item: string = 'CmpItem'; addItem() { items.push(this.item); } } TestBed.configureTestingModule({declarations: [ChildCmp, TestCmp]}); const fixture = TestBed.createComponent(TestCmp); fixture.detectChanges(); const childCmp: ChildCmp = fixture.debugElement.children[0].componentInstance; childCmp.addItemFn!(); childCmp.addItemFn!(); expect(items).toEqual(['CmpItem', 'CmpItem']); }); it('should resolve template input variables through the implicit receiver', () => { @Component({ template: `<ng-template let-a [ngIf]="true">{{a}}</ng-template>`, standalone: false, }) class TestCmp {} TestBed.configureTestingModule({declarations: [TestCmp]}); const fixture = TestBed.createComponent(TestCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('true'); }); it('should component instance variables through the implicit receiver', () => { @Component({ template: ` <ng-template [ngIf]="true"> <ng-template [ngIf]="true">{{this.myProp}}{{myProp}}</ng-template> </ng-template>`, standalone: false, }) class TestCmp { myProp = 'Hello'; } TestBed.configureTestingModule({declarations: [TestCmp]}); const fixture = TestBed.createComponent(TestCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('HelloHello'); }); });
{ "end_byte": 2237, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/embedded_views_spec.ts" }
angular/packages/core/test/acceptance/change_detection_spec.ts_0_7128
/** * @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} from '@angular/common'; import {PLATFORM_BROWSER_ID} from '@angular/common/src/platform_id'; import { ApplicationRef, NgZone, ChangeDetectionStrategy, ChangeDetectorRef, Component, ComponentRef, Directive, DoCheck, EmbeddedViewRef, ErrorHandler, EventEmitter, inject, Input, NgModule, OnInit, Output, QueryList, TemplateRef, Type, ViewChild, ViewChildren, ViewContainerRef, provideExperimentalCheckNoChangesForDebug, provideExperimentalZonelessChangeDetection, ɵRuntimeError as RuntimeError, ɵRuntimeErrorCode as RuntimeErrorCode, afterRender, PLATFORM_ID, provideZoneChangeDetection, } from '@angular/core'; import {} from '@angular/core/src/errors'; import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/src/matchers'; import {BehaviorSubject} from 'rxjs'; describe('change detection', () => { it('can provide zone and zoneless (last one wins like any other provider) in TestBed', () => { expect(() => { TestBed.configureTestingModule({ providers: [provideExperimentalZonelessChangeDetection(), provideZoneChangeDetection()], }); TestBed.inject(ApplicationRef); }).not.toThrow(); }); describe('embedded views', () => { @Directive({ selector: '[viewManipulation]', exportAs: 'vm', standalone: false, }) class ViewManipulation { constructor( private _tplRef: TemplateRef<{}>, public vcRef: ViewContainerRef, private _appRef: ApplicationRef, ) {} insertIntoVcRef() { return this.vcRef.createEmbeddedView(this._tplRef); } insertIntoAppRef(): EmbeddedViewRef<{}> { const viewRef = this._tplRef.createEmbeddedView({}); this._appRef.attachView(viewRef); return viewRef; } } @Component({ selector: 'test-cmp', template: ` <ng-template #vm="vm" viewManipulation>{{'change-detected'}}</ng-template> `, standalone: false, }) class TestCmpt {} it('should detect changes for embedded views inserted through ViewContainerRef', () => { TestBed.configureTestingModule({declarations: [TestCmpt, ViewManipulation]}); const fixture = TestBed.createComponent(TestCmpt); const vm = fixture.debugElement.childNodes[0].references['vm'] as ViewManipulation; vm.insertIntoVcRef(); fixture.detectChanges(); expect(fixture.nativeElement).toHaveText('change-detected'); }); it('should detect changes for embedded views attached to ApplicationRef', () => { TestBed.configureTestingModule({declarations: [TestCmpt, ViewManipulation]}); const fixture = TestBed.createComponent(TestCmpt); const vm = fixture.debugElement.childNodes[0].references['vm'] as ViewManipulation; const viewRef = vm.insertIntoAppRef(); // A newly created view was attached to the CD tree via ApplicationRef so should be also // change detected when ticking root component fixture.detectChanges(); expect(viewRef.rootNodes[0]).toHaveText('change-detected'); }); it('should not detect changes for OnPush embedded views when they are not dirty', () => { @Component({ selector: 'onpush', template: '', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, }) class OnPushComponent { checks = 0; cdRef = inject(ChangeDetectorRef); ngDoCheck() { this.checks++; } } @Component({template: '<ng-template #template></ng-template>', standalone: true}) class Container { @ViewChild('template', {read: ViewContainerRef, static: true}) vcr!: ViewContainerRef; } const fixture = TestBed.createComponent(Container); const ref = fixture.componentInstance.vcr!.createComponent(OnPushComponent); fixture.detectChanges(false); expect(ref.instance.checks).toBe(1); fixture.detectChanges(false); expect(ref.instance.checks).toBe(1); ref.instance.cdRef.markForCheck(); fixture.detectChanges(false); expect(ref.instance.checks).toBe(2); }); it('should not detect changes in child embedded views while they are detached', () => { const counters = {componentView: 0, embeddedView: 0}; @Component({ template: ` <div>{{increment('componentView')}}</div> <ng-template #vm="vm" viewManipulation>{{increment('embeddedView')}}</ng-template> `, standalone: false, }) class App { increment(counter: 'componentView' | 'embeddedView') { counters[counter]++; } } TestBed.configureTestingModule({declarations: [App, ViewManipulation]}); const fixture = TestBed.createComponent(App); const vm: ViewManipulation = fixture.debugElement.childNodes[1].references['vm']; const viewRef = vm.insertIntoVcRef(); viewRef.detach(); fixture.detectChanges(); expect(counters).toEqual({componentView: 2, embeddedView: 0}); // Re-attach the view to ensure that the process can be reversed. viewRef.reattach(); fixture.detectChanges(); expect(counters).toEqual({componentView: 4, embeddedView: 2}); }); it('should not detect changes in child component views while they are detached', () => { let counter = 0; @Component({ template: `<ng-template #vm="vm" viewManipulation></ng-template>`, changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class App {} @Component({ template: ` <button (click)="noop()">Trigger change detection</button> <div>{{increment()}}</div> `, changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class DynamicComp { increment() { counter++; } noop() {} } TestBed.configureTestingModule({declarations: [App, ViewManipulation, DynamicComp]}); const fixture = TestBed.createComponent(App); const vm: ViewManipulation = fixture.debugElement.childNodes[0].references['vm']; const componentRef = vm.vcRef.createComponent(DynamicComp); const button = fixture.nativeElement.querySelector('button'); fixture.detectChanges(); expect(counter).toBe(1); button.click(); fixture.detectChanges(); expect(counter).toBe(2); componentRef.changeDetectorRef.detach(); button.click(); fixture.detectChanges(); expect(counter).toBe(2); // Re-attach the change detector to ensure that the process can be reversed. componentRef.changeDetectorRef.reattach(); button.click(); fixture.detectChanges(); expect(counter).toBe(3); }); });
{ "end_byte": 7128, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_spec.ts" }
angular/packages/core/test/acceptance/change_detection_spec.ts_7132_10771
scribe('markForCheck', () => { it('should mark OnPush ancestor of dynamically created component views as dirty', () => { @Component({ selector: `test-cmpt`, template: `{{counter}}|<ng-template #vc></ng-template>`, changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, }) class TestCmpt { counter = 0; @ViewChild('vc', {read: ViewContainerRef}) vcRef!: ViewContainerRef; createComponentView<T>(cmptType: Type<T>): ComponentRef<T> { return this.vcRef.createComponent(cmptType); } } @Component({ selector: 'dynamic-cmpt', template: `dynamic|{{binding}}`, standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, }) class DynamicCmpt { @Input() binding = 'binding'; } const fixture = TestBed.createComponent(TestCmpt); // initial CD to have query results // NOTE: we call change detection without checkNoChanges to have clearer picture fixture.detectChanges(false); expect(fixture.nativeElement).toHaveText('0|'); // insert a dynamic component, but do not specifically mark parent dirty // (dynamic components with OnPush flag are created with the `Dirty` flag) const dynamicCmptRef = fixture.componentInstance.createComponentView(DynamicCmpt); fixture.detectChanges(false); expect(fixture.nativeElement).toHaveText('0|dynamic|binding'); // update model in the OnPush component - should not update UI fixture.componentInstance.counter = 1; fixture.detectChanges(false); expect(fixture.nativeElement).toHaveText('0|dynamic|binding'); // now mark the dynamically inserted component as dirty dynamicCmptRef.changeDetectorRef.markForCheck(); fixture.detectChanges(false); expect(fixture.nativeElement).toHaveText('1|dynamic|binding'); // Update, mark for check, and detach before change detection, should not update dynamicCmptRef.setInput('binding', 'updatedBinding'); dynamicCmptRef.changeDetectorRef.markForCheck(); dynamicCmptRef.changeDetectorRef.detach(); fixture.detectChanges(false); expect(fixture.nativeElement).toHaveText('1|dynamic|binding'); // reattaching and run CD from the top should update dynamicCmptRef.changeDetectorRef.reattach(); fixture.detectChanges(false); expect(fixture.nativeElement).toHaveText('1|dynamic|updatedBinding'); }); it('should support re-enterant change detection', () => { @Component({ selector: 'has-host-binding', template: '..', host: { '[class.x]': 'x', }, standalone: false, }) class HasHostBinding { x = true; } @Component({ selector: 'child', template: '<has-host-binding></has-host-binding>', inputs: ['input'], standalone: false, }) class Child { /** * @internal */ private _input!: number; constructor(private cdr: ChangeDetectorRef) {} get input() { return this._input; } set input(value: number) { this._input = value; this.cdr.detectChanges(); } } @Component({ selector: 'root', template: '<child [input]="3"></child>', standalone: false, }) class Root {} TestBed.configureTestingModule({ declarations: [Root, Child, HasHostBinding], }); TestBed.createComponent(Root).detectChanges(); }); });
{ "end_byte": 10771, "start_byte": 7132, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_spec.ts" }
angular/packages/core/test/acceptance/change_detection_spec.ts_10775_18900
scribe('OnPush', () => { @Component({ selector: 'my-comp', changeDetection: ChangeDetectionStrategy.OnPush, template: `{{ doCheckCount }} - {{ name }} <button (click)="onClick()"></button>`, standalone: false, }) class MyComponent implements DoCheck { @Input() name = 'Nancy'; doCheckCount = 0; ngDoCheck(): void { this.doCheckCount++; } onClick() {} } @Component({ selector: 'my-app', template: '<my-comp [name]="name"></my-comp>', standalone: false, }) class MyApp { @ViewChild(MyComponent) comp!: MyComponent; name: string = 'Nancy'; } it('should check OnPush components on initialization', () => { TestBed.configureTestingModule({declarations: [MyComponent, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toEqual('1 - Nancy'); }); it('should call doCheck even when OnPush components are not dirty', () => { TestBed.configureTestingModule({declarations: [MyComponent, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); fixture.detectChanges(); expect(fixture.componentInstance.comp.doCheckCount).toEqual(2); fixture.detectChanges(); expect(fixture.componentInstance.comp.doCheckCount).toEqual(3); }); it('should skip OnPush components in update mode when they are not dirty', () => { TestBed.configureTestingModule({declarations: [MyComponent, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); // doCheckCount is 2, but 1 should be rendered since it has not been marked dirty. expect(fixture.nativeElement.textContent.trim()).toEqual('1 - Nancy'); fixture.detectChanges(); // doCheckCount is 3, but 1 should be rendered since it has not been marked dirty. expect(fixture.nativeElement.textContent.trim()).toEqual('1 - Nancy'); }); it('should check OnPush components in update mode when inputs change', () => { TestBed.configureTestingModule({declarations: [MyComponent, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); fixture.componentInstance.name = 'Bess'; fixture.detectChanges(); expect(fixture.componentInstance.comp.doCheckCount).toEqual(2); // View should update, as changed input marks view dirty expect(fixture.nativeElement.textContent.trim()).toEqual('2 - Bess'); fixture.componentInstance.name = 'George'; fixture.detectChanges(); // View should update, as changed input marks view dirty expect(fixture.componentInstance.comp.doCheckCount).toEqual(3); expect(fixture.nativeElement.textContent.trim()).toEqual('3 - George'); fixture.detectChanges(); expect(fixture.componentInstance.comp.doCheckCount).toEqual(4); // View should not be updated to "4", as inputs have not changed. expect(fixture.nativeElement.textContent.trim()).toEqual('3 - George'); }); it('should check OnPush components in update mode when component events occur', () => { TestBed.configureTestingModule({declarations: [MyComponent, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.componentInstance.comp.doCheckCount).toEqual(1); expect(fixture.nativeElement.textContent.trim()).toEqual('1 - Nancy'); const button = fixture.nativeElement.querySelector('button')!; button.click(); // No ticks should have been scheduled. expect(fixture.componentInstance.comp.doCheckCount).toEqual(1); expect(fixture.nativeElement.textContent.trim()).toEqual('1 - Nancy'); fixture.detectChanges(); // Because the onPush comp should be dirty, it should update once CD runs expect(fixture.componentInstance.comp.doCheckCount).toEqual(2); expect(fixture.nativeElement.textContent.trim()).toEqual('2 - Nancy'); }); it('should not check OnPush components in update mode when parent events occur', () => { @Component({ selector: 'button-parent', template: '<my-comp></my-comp><button id="parent" (click)="noop()"></button>', standalone: false, }) class ButtonParent { @ViewChild(MyComponent) comp!: MyComponent; noop() {} } TestBed.configureTestingModule({declarations: [MyComponent, ButtonParent]}); const fixture = TestBed.createComponent(ButtonParent); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toEqual('1 - Nancy'); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button#parent'); button.click(); fixture.detectChanges(); // The comp should still be clean. So doCheck will run, but the view should display 1. expect(fixture.componentInstance.comp.doCheckCount).toEqual(2); expect(fixture.nativeElement.textContent.trim()).toEqual('1 - Nancy'); }); it('should check parent OnPush components in update mode when child events occur', () => { @Component({ selector: 'button-parent', template: '{{ doCheckCount }} - <my-comp></my-comp>', changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class ButtonParent implements DoCheck { @ViewChild(MyComponent) comp!: MyComponent; noop() {} doCheckCount = 0; ngDoCheck(): void { this.doCheckCount++; } } @Component({ selector: 'my-button-app', template: '<button-parent></button-parent>', standalone: false, }) class MyButtonApp { @ViewChild(ButtonParent) parent!: ButtonParent; } TestBed.configureTestingModule({declarations: [MyButtonApp, MyComponent, ButtonParent]}); const fixture = TestBed.createComponent(MyButtonApp); fixture.detectChanges(); const parent = fixture.componentInstance.parent; const comp = parent.comp; expect(parent.doCheckCount).toEqual(1); expect(comp.doCheckCount).toEqual(1); expect(fixture.nativeElement.textContent.trim()).toEqual('1 - 1 - Nancy'); fixture.detectChanges(); expect(parent.doCheckCount).toEqual(2); // parent isn't checked, so child doCheck won't run expect(comp.doCheckCount).toEqual(1); expect(fixture.nativeElement.textContent.trim()).toEqual('1 - 1 - Nancy'); const button = fixture.nativeElement.querySelector('button'); button.click(); // No ticks should have been scheduled. expect(parent.doCheckCount).toEqual(2); expect(comp.doCheckCount).toEqual(1); fixture.detectChanges(); expect(parent.doCheckCount).toEqual(3); expect(comp.doCheckCount).toEqual(2); expect(fixture.nativeElement.textContent.trim()).toEqual('3 - 2 - Nancy'); }); it('should check parent OnPush components when child directive on a template emits event', fakeAsync(() => { @Directive({ selector: '[emitter]', standalone: false, }) class Emitter { @Output() event = new EventEmitter<string>(); ngOnInit() { setTimeout(() => { this.event.emit('new message'); }); } } @Component({ selector: 'my-app', template: '{{message}} <ng-template emitter (event)="message = $event"></ng-template>', changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class MyApp { message = 'initial message'; } const fixture = TestBed.configureTestingModule({ declarations: [MyApp, Emitter], }).createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toEqual('initial message'); tick(); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toEqual('new message'); })); });
{ "end_byte": 18900, "start_byte": 10775, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_spec.ts" }
angular/packages/core/test/acceptance/change_detection_spec.ts_18904_28410
scribe('ChangeDetectorRef', () => { describe('detectChanges()', () => { @Component({ selector: 'my-comp', template: '{{ name }}', changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class MyComp implements DoCheck { doCheckCount = 0; name = 'Nancy'; constructor(public cdr: ChangeDetectorRef) {} ngDoCheck() { this.doCheckCount++; } } @Component({ selector: 'parent-comp', template: `{{ doCheckCount}} - <my-comp></my-comp>`, standalone: false, }) class ParentComp implements DoCheck { @ViewChild(MyComp) myComp!: MyComp; doCheckCount = 0; constructor(public cdr: ChangeDetectorRef) {} ngDoCheck() { this.doCheckCount++; } } @Directive({ selector: '[dir]', standalone: false, }) class Dir { constructor(public cdr: ChangeDetectorRef) {} } it('should check the component view when called by component (even when OnPush && clean)', () => { TestBed.configureTestingModule({declarations: [MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Nancy'); fixture.componentInstance.name = 'Bess'; // as this is not an Input, the component stays clean fixture.componentInstance.cdr.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Bess'); }); it('should NOT call component doCheck when called by a component', () => { TestBed.configureTestingModule({declarations: [MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(fixture.componentInstance.doCheckCount).toEqual(1); // NOTE: in current Angular, detectChanges does not itself trigger doCheck, but you // may see doCheck called in some cases bc of the extra CD run triggered by zone.js. // It's important not to call doCheck to allow calls to detectChanges in that hook. fixture.componentInstance.cdr.detectChanges(); expect(fixture.componentInstance.doCheckCount).toEqual(1); }); it('should NOT check the component parent when called by a child component', () => { TestBed.configureTestingModule({declarations: [MyComp, ParentComp]}); const fixture = TestBed.createComponent(ParentComp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('1 - Nancy'); fixture.componentInstance.doCheckCount = 100; fixture.componentInstance.myComp.cdr.detectChanges(); expect(fixture.componentInstance.doCheckCount).toEqual(100); expect(fixture.nativeElement.textContent).toEqual('1 - Nancy'); }); it('should check component children when called by component if dirty or check-always', () => { TestBed.configureTestingModule({declarations: [MyComp, ParentComp]}); const fixture = TestBed.createComponent(ParentComp); fixture.detectChanges(); expect(fixture.componentInstance.doCheckCount).toEqual(1); fixture.componentInstance.myComp.name = 'Bess'; fixture.componentInstance.cdr.detectChanges(); expect(fixture.componentInstance.doCheckCount).toEqual(1); expect(fixture.componentInstance.myComp.doCheckCount).toEqual(2); // OnPush child is not dirty, so its change isn't rendered. expect(fixture.nativeElement.textContent).toEqual('1 - Nancy'); }); it('should not group detectChanges calls (call every time)', () => { TestBed.configureTestingModule({declarations: [MyComp, ParentComp]}); const fixture = TestBed.createComponent(ParentComp); fixture.detectChanges(); expect(fixture.componentInstance.doCheckCount).toEqual(1); fixture.componentInstance.cdr.detectChanges(); fixture.componentInstance.cdr.detectChanges(); expect(fixture.componentInstance.myComp.doCheckCount).toEqual(3); }); it('should check component view when called by directive on component node', () => { @Component({ template: '<my-comp dir></my-comp>', standalone: false, }) class MyApp { @ViewChild(MyComp) myComp!: MyComp; @ViewChild(Dir) dir!: Dir; } TestBed.configureTestingModule({declarations: [MyComp, Dir, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Nancy'); fixture.componentInstance.myComp.name = 'George'; fixture.componentInstance.dir.cdr.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('George'); }); it('should check host component when called by directive on element node', () => { @Component({ template: '{{ value }}<div dir></div>', standalone: false, }) class MyApp { @ViewChild(MyComp) myComp!: MyComp; @ViewChild(Dir) dir!: Dir; value = ''; } TestBed.configureTestingModule({declarations: [Dir, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); fixture.componentInstance.value = 'Frank'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Frank'); fixture.componentInstance.value = 'Joe'; fixture.componentInstance.dir.cdr.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Joe'); }); it('should check the host component when called from EmbeddedViewRef', () => { @Component({ template: '{{ name }}<div *ngIf="showing" dir></div>', standalone: false, }) class MyApp { @ViewChild(Dir) dir!: Dir; showing = true; name = 'Amelia'; } TestBed.configureTestingModule({declarations: [Dir, MyApp], imports: [CommonModule]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Amelia'); fixture.componentInstance.name = 'Emerson'; fixture.componentInstance.dir.cdr.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Emerson'); }); it('should support call in ngOnInit', () => { @Component({ template: '{{ value }}', standalone: false, }) class DetectChangesComp implements OnInit { value = 0; constructor(public cdr: ChangeDetectorRef) {} ngOnInit() { this.value++; this.cdr.detectChanges(); } } TestBed.configureTestingModule({declarations: [DetectChangesComp]}); const fixture = TestBed.createComponent(DetectChangesComp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('1'); }); ['OnInit', 'AfterContentInit', 'AfterViewInit', 'OnChanges'].forEach((hook) => { it(`should not go infinite loop when recursively called from children's ng${hook}`, () => { @Component({ template: '<child-comp [inp]="true"></child-comp>', standalone: false, }) class ParentComp { constructor(public cdr: ChangeDetectorRef) {} triggerChangeDetection() { this.cdr.detectChanges(); } } @Component({ template: '{{inp}}', selector: 'child-comp', standalone: false, }) class ChildComp { @Input() inp: any = ''; count = 0; constructor(public parentComp: ParentComp) {} ngOnInit() { this.check('OnInit'); } ngAfterContentInit() { this.check('AfterContentInit'); } ngAfterViewInit() { this.check('AfterViewInit'); } ngOnChanges() { this.check('OnChanges'); } check(h: string) { if (h === hook) { this.count++; if (this.count > 1) throw new Error(`ng${hook} should be called only once!`); this.parentComp.triggerChangeDetection(); } } } TestBed.configureTestingModule({declarations: [ParentComp, ChildComp]}); expect(() => { const fixture = TestBed.createComponent(ParentComp); fixture.detectChanges(); }).not.toThrow(); }); }); it('should support call in ngDoCheck', () => { @Component({ template: '{{doCheckCount}}', standalone: false, }) class DetectChangesComp { doCheckCount = 0; constructor(public cdr: ChangeDetectorRef) {} ngDoCheck() { this.doCheckCount++; this.cdr.detectChanges(); } } TestBed.configureTestingModule({declarations: [DetectChangesComp]}); const fixture = TestBed.createComponent(DetectChangesComp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('1'); });
{ "end_byte": 28410, "start_byte": 18904, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_spec.ts" }
angular/packages/core/test/acceptance/change_detection_spec.ts_28418_37524
('should support change detection triggered as a result of View queries processing', () => { @Component({ selector: 'app', template: ` <div *ngIf="visible" #ref>Visible text</div> `, standalone: false, }) class App { @ViewChildren('ref') ref!: QueryList<any>; visible = false; constructor(public changeDetectorRef: ChangeDetectorRef) {} ngAfterViewInit() { this.ref.changes.subscribe((refs: QueryList<any>) => { this.visible = false; this.changeDetectorRef.detectChanges(); }); } } TestBed.configureTestingModule({ declarations: [App], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe(''); // even though we set "visible" to `true`, we do not expect any content to be displayed, // since the flag is overridden in `ngAfterViewInit` back to `false` fixture.componentInstance.visible = true; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe(''); }); describe('dynamic views', () => { @Component({ selector: 'structural-comp', template: '{{ value }}', standalone: false, }) class StructuralComp { @Input() tmp!: TemplateRef<any>; value = 'one'; constructor(public vcr: ViewContainerRef) {} create() { return this.vcr.createEmbeddedView(this.tmp, {ctx: this}); } } it('should support ViewRef.detectChanges()', () => { @Component({ template: '<ng-template #foo let-ctx="ctx">{{ ctx.value }}</ng-template><structural-comp [tmp]="foo"></structural-comp>', standalone: false, }) class App { @ViewChild(StructuralComp) structuralComp!: StructuralComp; } TestBed.configureTestingModule({declarations: [App, StructuralComp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); const viewRef: EmbeddedViewRef<any> = fixture.componentInstance.structuralComp.create(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('oneone'); // check embedded view update fixture.componentInstance.structuralComp.value = 'two'; viewRef.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('onetwo'); // check root view update fixture.componentInstance.structuralComp.value = 'three'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('threethree'); }); it('should support ViewRef.detectChanges() directly after creation', () => { @Component({ template: '<ng-template #foo>Template text</ng-template><structural-comp [tmp]="foo">', standalone: false, }) class App { @ViewChild(StructuralComp) structuralComp!: StructuralComp; } TestBed.configureTestingModule({declarations: [App, StructuralComp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); const viewRef: EmbeddedViewRef<any> = fixture.componentInstance.structuralComp.create(); viewRef.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('oneTemplate text'); }); }); }); describe('attach/detach', () => { @Component({ selector: 'detached-comp', template: '{{ value }}', standalone: false, }) class DetachedComp implements DoCheck { value = 'one'; doCheckCount = 0; constructor(public cdr: ChangeDetectorRef) {} ngDoCheck() { this.doCheckCount++; } } @Component({ template: '<detached-comp></detached-comp>', standalone: false, }) class MyApp { @ViewChild(DetachedComp) comp!: DetachedComp; constructor(public cdr: ChangeDetectorRef) {} } it('should not check detached components', () => { TestBed.configureTestingModule({declarations: [MyApp, DetachedComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); fixture.componentInstance.comp.cdr.detach(); fixture.componentInstance.comp.value = 'two'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); }); it('should check re-attached components', () => { TestBed.configureTestingModule({declarations: [MyApp, DetachedComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); fixture.componentInstance.comp.cdr.detach(); fixture.componentInstance.comp.value = 'two'; fixture.componentInstance.comp.cdr.reattach(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('two'); }); it('should call lifecycle hooks on detached components', () => { TestBed.configureTestingModule({declarations: [MyApp, DetachedComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.componentInstance.comp.doCheckCount).toEqual(1); fixture.componentInstance.comp.cdr.detach(); fixture.detectChanges(); expect(fixture.componentInstance.comp.doCheckCount).toEqual(2); }); it('should check detached component when detectChanges is called', () => { TestBed.configureTestingModule({declarations: [MyApp, DetachedComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); fixture.componentInstance.comp.cdr.detach(); fixture.componentInstance.comp.value = 'two'; fixture.componentInstance.comp.cdr.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('two'); }); it('should not check detached component when markDirty is called', () => { TestBed.configureTestingModule({declarations: [MyApp, DetachedComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); const comp = fixture.componentInstance.comp; comp.cdr.detach(); comp.value = 'two'; comp.cdr.markForCheck(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); }); it('should detach any child components when parent is detached', () => { TestBed.configureTestingModule({declarations: [MyApp, DetachedComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); fixture.componentInstance.cdr.detach(); fixture.componentInstance.comp.value = 'two'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); fixture.componentInstance.cdr.reattach(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('two'); }); it('should detach OnPush components properly', () => { @Component({ selector: 'on-push-comp', template: '{{ value }}', changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class OnPushComp { @Input() value!: string; constructor(public cdr: ChangeDetectorRef) {} } @Component({ template: '<on-push-comp [value]="value"></on-push-comp>', standalone: false, }) class OnPushApp { @ViewChild(OnPushComp) onPushComp!: OnPushComp; value = ''; } TestBed.configureTestingModule({declarations: [OnPushApp, OnPushComp]}); const fixture = TestBed.createComponent(OnPushApp); fixture.detectChanges(); fixture.componentInstance.value = 'one'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); fixture.componentInstance.onPushComp.cdr.detach(); fixture.componentInstance.value = 'two'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one'); fixture.componentInstance.onPushComp.cdr.reattach(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('two'); }); });
{ "end_byte": 37524, "start_byte": 28418, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_spec.ts" }
angular/packages/core/test/acceptance/change_detection_spec.ts_37530_47134
scribe('markForCheck()', () => { @Component({ selector: 'on-push-comp', template: '{{ value }}', changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class OnPushComp implements DoCheck { value = 'one'; doCheckCount = 0; constructor(public cdr: ChangeDetectorRef) {} ngDoCheck() { this.doCheckCount++; } } @Component({ template: '{{ value }} - <on-push-comp></on-push-comp>', changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class OnPushParent { @ViewChild(OnPushComp) comp!: OnPushComp; value = 'one'; } it('should ensure OnPush components are checked', () => { TestBed.configureTestingModule({declarations: [OnPushParent, OnPushComp]}); const fixture = TestBed.createComponent(OnPushParent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - one'); fixture.componentInstance.comp.value = 'two'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - one'); fixture.componentInstance.comp.cdr.markForCheck(); // Change detection should not have run yet, since markForCheck // does not itself schedule change detection. expect(fixture.nativeElement.textContent).toEqual('one - one'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - two'); }); it('should never schedule change detection on its own', () => { TestBed.configureTestingModule({declarations: [OnPushParent, OnPushComp]}); const fixture = TestBed.createComponent(OnPushParent); fixture.detectChanges(); const comp = fixture.componentInstance.comp; expect(comp.doCheckCount).toEqual(1); comp.cdr.markForCheck(); comp.cdr.markForCheck(); expect(comp.doCheckCount).toEqual(1); }); it('should ensure ancestor OnPush components are checked', () => { TestBed.configureTestingModule({declarations: [OnPushParent, OnPushComp]}); const fixture = TestBed.createComponent(OnPushParent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - one'); fixture.componentInstance.value = 'two'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - one'); fixture.componentInstance.comp.cdr.markForCheck(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('two - one'); }); it('should ensure OnPush components in embedded views are checked', () => { @Component({ template: '{{ value }} - <on-push-comp *ngIf="showing"></on-push-comp>', changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class EmbeddedViewParent { @ViewChild(OnPushComp) comp!: OnPushComp; value = 'one'; showing = true; } TestBed.configureTestingModule({ declarations: [EmbeddedViewParent, OnPushComp], imports: [CommonModule], }); const fixture = TestBed.createComponent(EmbeddedViewParent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - one'); fixture.componentInstance.comp.value = 'two'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - one'); fixture.componentInstance.comp.cdr.markForCheck(); // markForCheck should not trigger change detection on its own. expect(fixture.nativeElement.textContent).toEqual('one - one'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - two'); fixture.componentInstance.value = 'two'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('one - two'); fixture.componentInstance.comp.cdr.markForCheck(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('two - two'); }); it('async pipe should trigger CD for embedded views where the declaration and insertion views are different', () => { @Component({ selector: 'insertion', changeDetection: ChangeDetectionStrategy.OnPush, template: ` <ng-container [ngTemplateOutlet]="template"> </ng-container> `, standalone: false, }) class Insertion { @Input() template!: TemplateRef<{}>; } // This component uses async pipe (which calls markForCheck) in a view that has different // insertion and declaration views. @Component({ changeDetection: ChangeDetectionStrategy.OnPush, template: ` <insertion [template]="ref"></insertion> <ng-template #ref> <span>{{value | async}}</span> </ng-template> `, standalone: false, }) class Declaration { value = new BehaviorSubject('initial value'); } const fixture = TestBed.configureTestingModule({ declarations: [Insertion, Declaration], }).createComponent(Declaration); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.textContent).toContain('initial value'); fixture.componentInstance.value.next('new value'); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.textContent).toContain('new value'); }); // TODO(kara): add test for dynamic views once bug fix is in }); describe('checkNoChanges', () => { let comp: NoChangesComp; @Component({ selector: 'no-changes-comp', template: '{{ value }}', standalone: false, }) class NoChangesComp { value = 1; doCheckCount = 0; contentCheckCount = 0; viewCheckCount = 0; ngDoCheck() { this.doCheckCount++; } ngAfterContentChecked() { this.contentCheckCount++; } ngAfterViewChecked() { this.viewCheckCount++; } constructor(public cdr: ChangeDetectorRef) { comp = this; } } @Component({ template: '{{ value }} - <no-changes-comp></no-changes-comp>', standalone: false, }) class AppComp { value = 1; constructor(public cdr: ChangeDetectorRef) {} } // Custom error handler that just rethrows all the errors from the // view, rather than logging them out. Used to keep our logs clean. class RethrowErrorHandler extends ErrorHandler { override handleError(error: any) { throw error; } } it('should throw if bindings in current view have changed', () => { TestBed.configureTestingModule({ declarations: [NoChangesComp], providers: [{provide: ErrorHandler, useClass: RethrowErrorHandler}], }); const fixture = TestBed.createComponent(NoChangesComp); expect(() => { fixture.componentInstance.cdr.checkNoChanges(); }).toThrowError( /ExpressionChangedAfterItHasBeenCheckedError: .+ Previous value: '.*undefined'. Current value: '.*1'/gi, ); }); it('should throw if interpolations in current view have changed', () => { TestBed.configureTestingModule({ declarations: [AppComp, NoChangesComp], providers: [{provide: ErrorHandler, useClass: RethrowErrorHandler}], }); const fixture = TestBed.createComponent(AppComp); expect(() => fixture.componentInstance.cdr.checkNoChanges()).toThrowError( /ExpressionChangedAfterItHasBeenCheckedError: .+ Previous value: '.*undefined'. Current value: '.*1'/gi, ); }); it('should throw if bindings in embedded view have changed', () => { @Component({ template: '<span *ngIf="showing">{{ showing }}</span>', standalone: false, }) class EmbeddedViewApp { showing = true; constructor(public cdr: ChangeDetectorRef) {} } TestBed.configureTestingModule({ declarations: [EmbeddedViewApp], imports: [CommonModule], providers: [{provide: ErrorHandler, useClass: RethrowErrorHandler}], }); const fixture = TestBed.createComponent(EmbeddedViewApp); expect(() => fixture.componentInstance.cdr.checkNoChanges()).toThrowError( /ExpressionChangedAfterItHasBeenCheckedError: .+ Previous value: '.*undefined'. Current value: '.*true'/gi, ); }); it('should NOT call lifecycle hooks', () => { TestBed.configureTestingModule({ declarations: [AppComp, NoChangesComp], providers: [{provide: ErrorHandler, useClass: RethrowErrorHandler}], }); const fixture = TestBed.createComponent(AppComp); fixture.detectChanges(); expect(comp.doCheckCount).toEqual(1); expect(comp.contentCheckCount).toEqual(1); expect(comp.viewCheckCount).toEqual(1); comp.value = 2; expect(() => fixture.componentInstance.cdr.checkNoChanges()).toThrow(); expect(comp.doCheckCount).toEqual(1); expect(comp.contentCheckCount).toEqual(1); expect(comp.viewCheckCount).toEqual(1); });
{ "end_byte": 47134, "start_byte": 37530, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_spec.ts" }
angular/packages/core/test/acceptance/change_detection_spec.ts_47142_55208
scribe('provideExperimentalCheckNoChangesForDebug', () => { // Needed because tests in this repo patch rAF to be setTimeout // and coalescing tries to get the native one but fails so // coalescing will run a timeout in the zone and cause an infinite loop. const previousRaf = global.requestAnimationFrame; beforeEach(() => { (global as any).requestAnimationFrame = undefined; }); afterEach(() => { (global as any).requestAnimationFrame = previousRaf; }); @Component({ changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, template: '{{state}}{{resolveReadPromise()}}', }) class MyApp { state = 'initial'; promise?: Promise<void>; private resolve?: Function; changeDetectorRef = inject(ChangeDetectorRef); createReadPromise() { this.promise = new Promise<void>((resolve) => { this.resolve = resolve; }); } resolveReadPromise() { this.resolve?.(); } } it('throws error if used after zoneless provider', async () => { TestBed.configureTestingModule({ providers: [ {provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID}, provideExperimentalCheckNoChangesForDebug({useNgZoneOnStable: true}), provideExperimentalZonelessChangeDetection(), ], }); expect(() => { TestBed.createComponent(MyApp); }).toThrowError(/must be after any other provider for `NgZone`/); }); it('throws error if used after zone provider', async () => { TestBed.configureTestingModule({ providers: [ {provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID}, provideExperimentalCheckNoChangesForDebug({useNgZoneOnStable: true}), provideZoneChangeDetection(), ], }); expect(() => { TestBed.createComponent(MyApp); }).toThrowError(/must be after any other provider for `NgZone`/); }); it('throws expression changed with useNgZoneOnStable', async () => { let error: RuntimeError | undefined = undefined; TestBed.configureTestingModule({ providers: [ {provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID}, provideExperimentalZonelessChangeDetection(), provideExperimentalCheckNoChangesForDebug({useNgZoneOnStable: true}), { provide: ErrorHandler, useValue: { handleError(e: unknown) { error = e as RuntimeError; }, }, }, ], }); let renderHookCalls = 0; TestBed.runInInjectionContext(() => { afterRender(() => { renderHookCalls++; }); }); const fixture = TestBed.createComponent(MyApp); await fixture.whenStable(); expect(renderHookCalls).toBe(1); fixture.componentInstance.createReadPromise(); TestBed.inject(NgZone).run(() => { fixture.componentInstance.state = 'new'; }); await fixture.componentInstance.promise; // should not have run appplicationRef.tick again expect(renderHookCalls).toBe(1); expect(error).toBeDefined(); expect(error!.code).toEqual(RuntimeErrorCode.EXPRESSION_CHANGED_AFTER_CHECKED); }); it('does not throw expression changed with useNgZoneOnStable if there is a change detection scheduled', async () => { let error: RuntimeError | undefined = undefined; TestBed.configureTestingModule({ providers: [ provideExperimentalZonelessChangeDetection(), provideExperimentalCheckNoChangesForDebug({useNgZoneOnStable: true}), { provide: ErrorHandler, useValue: { handleError(e: unknown) { error = e as RuntimeError; }, }, }, ], }); const fixture = TestBed.createComponent(MyApp); await fixture.whenStable(); fixture.componentInstance.createReadPromise(); TestBed.inject(NgZone).run(() => { setTimeout(() => { fixture.componentInstance.state = 'new'; fixture.componentInstance.changeDetectorRef.markForCheck(); }, 20); }); await fixture.componentInstance.promise; // checkNoChanges runs from zone.run call expect(error).toBeUndefined(); // checkNoChanges runs from the timeout fixture.componentInstance.createReadPromise(); await fixture.componentInstance.promise; expect(error).toBeUndefined(); }); it('throws expression changed with interval', async () => { let error: RuntimeError | undefined = undefined; TestBed.configureTestingModule({ providers: [ provideExperimentalZonelessChangeDetection(), provideExperimentalCheckNoChangesForDebug({interval: 5}), { provide: ErrorHandler, useValue: { handleError(e: unknown) { error = e as RuntimeError; }, }, }, ], }); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); fixture.componentInstance.state = 'new'; await new Promise<void>((resolve) => setTimeout(resolve, 10)); expect(error!.code).toEqual(RuntimeErrorCode.EXPRESSION_CHANGED_AFTER_CHECKED); }); it('does not throw expression changed with interval if change detection is scheduled', async () => { let error: RuntimeError | undefined = undefined; TestBed.configureTestingModule({ providers: [ provideExperimentalZonelessChangeDetection(), provideExperimentalCheckNoChangesForDebug({interval: 0}), { provide: ErrorHandler, useValue: { handleError(e: unknown) { error = e as RuntimeError; }, }, }, ], }); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); fixture.componentInstance.state = 'new'; // markForCheck schedules change detection fixture.componentInstance.changeDetectorRef.markForCheck(); // wait beyond the exhaustive check interval await new Promise<void>((resolve) => setTimeout(resolve, 1)); expect(error).toBeUndefined(); }); it('does not throw expression changed with interval if OnPush component an no exhaustive', async () => { let error: RuntimeError | undefined = undefined; TestBed.configureTestingModule({ providers: [ provideExperimentalZonelessChangeDetection(), provideExperimentalCheckNoChangesForDebug({interval: 0, exhaustive: false}), { provide: ErrorHandler, useValue: { handleError(e: unknown) { error = e as RuntimeError; }, }, }, ], }); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); fixture.componentInstance.state = 'new'; // wait beyond the exhaustive check interval await new Promise<void>((resolve) => setTimeout(resolve, 1)); expect(error).toBeUndefined(); }); }); }); });
{ "end_byte": 55208, "start_byte": 47142, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_spec.ts" }
angular/packages/core/test/acceptance/change_detection_spec.ts_55212_59956
scribe('OnPush markForCheck in lifecycle hooks', () => { describe('with check no changes enabled', () => createOnPushMarkForCheckTests(true)); describe('with check no changes disabled', () => createOnPushMarkForCheckTests(false)); function createOnPushMarkForCheckTests(checkNoChanges: boolean) { const detectChanges = (f: ComponentFixture<any>) => f.detectChanges(checkNoChanges); // 1. ngAfterViewInit and ngAfterViewChecked lifecycle hooks run after "OnPushComp" has // been refreshed. They can mark the component as dirty. Meaning that the "OnPushComp" // can be checked/refreshed in a subsequent change detection cycle. // 2. ngDoCheck and ngAfterContentChecked lifecycle hooks run before "OnPushComp" is // refreshed. This means that those hooks cannot leave the component as dirty because // the dirty state is reset afterwards. Though these hooks run every change detection // cycle before "OnPushComp" is considered for refreshing. Hence marking as dirty from // within such a hook can cause the component to checked/refreshed as intended. ['ngAfterViewInit', 'ngAfterViewChecked', 'ngAfterContentChecked', 'ngDoCheck'].forEach( (hookName) => { it(`should be able to mark component as dirty from within ${hookName}`, () => { @Component({ selector: 'on-push-comp', changeDetection: ChangeDetectionStrategy.OnPush, template: `<p>{{text}}</p>`, standalone: false, }) class OnPushComp { text = 'initial'; constructor(private _cdRef: ChangeDetectorRef) {} [hookName]() { this._cdRef.markForCheck(); } } @Component({ template: `<on-push-comp></on-push-comp>`, standalone: false, }) class TestApp { @ViewChild(OnPushComp) onPushComp!: OnPushComp; } TestBed.configureTestingModule({ declarations: [TestApp, OnPushComp], imports: [CommonModule], }); const fixture = TestBed.createComponent(TestApp); const pElement = fixture.nativeElement.querySelector('p') as HTMLElement; detectChanges(fixture); expect(pElement.textContent).toBe('initial'); // "OnPushComp" component should be re-checked since it has been left dirty // in the first change detection (through the lifecycle hook). Hence, setting // a programmatic value and triggering a new change detection cycle should cause // the text to be updated in the view. fixture.componentInstance.onPushComp.text = 'new'; detectChanges(fixture); expect(pElement.textContent).toBe('new'); }); }, ); // ngOnInit and ngAfterContentInit lifecycle hooks run once before "OnPushComp" is // refreshed/checked. This means they cannot mark the component as dirty because the // component dirty state will immediately reset after these hooks complete. ['ngOnInit', 'ngAfterContentInit'].forEach((hookName) => { it(`should not be able to mark component as dirty from within ${hookName}`, () => { @Component({ selector: 'on-push-comp', changeDetection: ChangeDetectionStrategy.OnPush, template: `<p>{{text}}</p>`, standalone: false, }) class OnPushComp { text = 'initial'; constructor(private _cdRef: ChangeDetectorRef) {} [hookName]() { this._cdRef.markForCheck(); } } @Component({ template: `<on-push-comp></on-push-comp>`, standalone: false, }) class TestApp { @ViewChild(OnPushComp) onPushComp!: OnPushComp; } TestBed.configureTestingModule({ declarations: [TestApp, OnPushComp], imports: [CommonModule], }); const fixture = TestBed.createComponent(TestApp); const pElement = fixture.nativeElement.querySelector('p') as HTMLElement; detectChanges(fixture); expect(pElement.textContent).toBe('initial'); fixture.componentInstance.onPushComp.text = 'new'; // this is a noop since the "OnPushComp" component is not marked as dirty. The // programmatically updated value will not be reflected in the rendered view. detectChanges(fixture); expect(pElement.textContent).toBe('initial'); }); }); } });
{ "end_byte": 59956, "start_byte": 55212, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_spec.ts" }
angular/packages/core/test/acceptance/change_detection_spec.ts_59960_66844
scribe('ExpressionChangedAfterItHasBeenCheckedError', () => { @Component({ template: '...', standalone: false, }) class MyApp { a: string = 'a'; b: string = 'b'; c: string = 'c'; unstableBooleanExpression: boolean = true; unstableStringExpression: string = 'initial'; unstableColorExpression: string = 'red'; unstableStyleMapExpression: {[key: string]: string} = {'color': 'red', 'margin': '10px'}; unstableClassMapExpression: {[key: string]: boolean} = {'classA': true, 'classB': false}; ngAfterViewChecked() { this.unstableBooleanExpression = false; this.unstableStringExpression = 'changed'; this.unstableColorExpression = 'green'; this.unstableStyleMapExpression = {'color': 'green', 'margin': '20px'}; this.unstableClassMapExpression = {'classA': false, 'classB': true}; } } function initComponent(overrides: {[key: string]: any}): ComponentFixture<MyApp> { TestBed.configureTestingModule({declarations: [MyApp]}); TestBed.overrideComponent(MyApp, {set: overrides}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); return fixture; } function initWithTemplate(template: string) { return initComponent({template}); } function initWithHostBindings(bindings: {[key: string]: string}) { return initComponent({host: bindings}); } it('should include field name in case of property binding', () => { const message = `Previous value for 'id': 'initial'. Current value: 'changed'`; expect(() => initWithTemplate('<div [id]="unstableStringExpression"></div>')).toThrowError( new RegExp(message), ); }); it('should include field name in case of property interpolation', () => { const message = `Previous value for 'id': 'Expressions: a and initial!'. Current value: 'Expressions: a and changed!'`; expect(() => initWithTemplate( '<div id="Expressions: {{ a }} and {{ unstableStringExpression }}!"></div>', ), ).toThrowError(new RegExp(message)); }); it('should include field name in case of attribute binding', () => { const message = `Previous value for 'attr.id': 'initial'. Current value: 'changed'`; expect(() => initWithTemplate('<div [attr.id]="unstableStringExpression"></div>'), ).toThrowError(new RegExp(message)); }); it('should include field name in case of attribute interpolation', () => { const message = `Previous value for 'attr.id': 'Expressions: a and initial!'. Current value: 'Expressions: a and changed!'`; expect(() => initWithTemplate( '<div attr.id="Expressions: {{ a }} and {{ unstableStringExpression }}!"></div>', ), ).toThrowError(new RegExp(message)); }); it('should only display a value of an expression that was changed in text interpolation', () => { expect(() => initWithTemplate('Expressions: {{ a }} and {{ unstableStringExpression }}!'), ).toThrowError(/Previous value: '.*?initial'. Current value: '.*?changed'/); }); it( 'should only display a value of an expression that was changed in text interpolation ' + 'that follows an element with property interpolation', () => { expect(() => { initWithTemplate(` <div id="Prop interpolation: {{ aVal }}"></div> Text interpolation: {{ unstableStringExpression }}. `); }).toThrowError(/Previous value: '.*?initial'. Current value: '.*?changed'/); }, ); it('should include style prop name in case of style binding', () => { const message = `Previous value for 'color': 'red'. Current value: 'green'`; expect(() => initWithTemplate('<div [style.color]="unstableColorExpression"></div>'), ).toThrowError(new RegExp(message)); }); it('should include class name in case of class binding', () => { const message = `Previous value for 'someClass': 'true'. Current value: 'false'`; expect(() => initWithTemplate('<div [class.someClass]="unstableBooleanExpression"></div>'), ).toThrowError(new RegExp(message)); }); it('should only display a value of an expression that was changed in text interpolation inside i18n block', () => { expect(() => initWithTemplate('<div i18n>Expression: {{ unstableStringExpression }}</div>'), ).toThrowError(/Previous value: '.*?initial'. Current value: '.*?changed'/); }); it('should only display a value of an expression for interpolation inside an i18n property', () => { expect(() => initWithTemplate( '<div i18n-title title="Expression: {{ unstableStringExpression }}"></div>', ), ).toThrowError(/Previous value: '.*?initial'. Current value: '.*?changed'/); }); it('should include field name in case of host property binding', () => { const message = `Previous value for 'id': 'initial'. Current value: 'changed'`; expect(() => initWithHostBindings({'[id]': 'unstableStringExpression'})).toThrowError( new RegExp(message), ); }); it('should include style prop name in case of host style bindings', () => { const message = `Previous value for 'color': 'red'. Current value: 'green'`; expect(() => initWithHostBindings({'[style.color]': 'unstableColorExpression'})).toThrowError( new RegExp(message), ); }); it('should include class name in case of host class bindings', () => { const message = `Previous value for 'someClass': 'true'. Current value: 'false'`; expect(() => initWithHostBindings({'[class.someClass]': 'unstableBooleanExpression'}), ).toThrowError(new RegExp(message)); }); // Note: the tests below currently fail in Ivy, but not in VE. VE behavior is correct and Ivy's // logic should be fixed by the upcoming styling refactor, we keep these tests to verify that. // // it('should not throw for style maps', () => { // expect(() => initWithTemplate('<div [style]="unstableStyleMapExpression"></div>')) // .not.toThrowError(); // }); // // it('should not throw for class maps', () => { // expect(() => initWithTemplate('<div [class]="unstableClassMapExpression"></div>')) // .not.toThrowError(); // }); // // it('should not throw for style maps as host bindings', () => { // expect(() => initWithHostBindings({'[style]': 'unstableStyleMapExpression'})) // .not.toThrowError(); // }); // // it('should not throw for class maps as host binding', () => { // expect(() => initWithHostBindings({'[class]': 'unstableClassMapExpression'})) // .not.toThrowError(); // }); }); });
{ "end_byte": 66844, "start_byte": 59960, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_spec.ts" }
angular/packages/core/test/acceptance/defer_spec.ts_0_5302
/** * @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, ɵPLATFORM_BROWSER_ID as PLATFORM_BROWSER_ID} from '@angular/common'; import { ApplicationRef, Attribute, ChangeDetectionStrategy, ChangeDetectorRef, Component, createComponent, Directive, EnvironmentInjector, ErrorHandler, inject, Injectable, InjectionToken, Input, NgModule, NgZone, Pipe, PipeTransform, PLATFORM_ID, QueryList, Type, ViewChildren, ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, ɵRuntimeError as RuntimeError, Injector, ElementRef, ViewChild, } from '@angular/core'; import {getComponentDef} from '@angular/core/src/render3/def_getters'; import { ComponentFixture, DeferBlockBehavior, fakeAsync, flush, TestBed, tick, } from '@angular/core/testing'; import {getInjectorResolutionPath} from '@angular/core/src/render3/util/injector_discovery_utils'; import {ActivatedRoute, provideRouter, Router, RouterOutlet} from '@angular/router'; import {ChainedInjector} from '@angular/core/src/render3/chained_injector'; import {global} from '../../src/util/global'; /** * Clears all associated directive defs from a given component class. * * This is a *hack* for TestBed, which compiles components in JIT mode * and can not remove dependencies and their imports in the same way as AOT. * From JIT perspective, all dependencies inside a defer block remain eager. * We need to clear this association to run tests that verify loading and * prefetching behavior. */ function clearDirectiveDefs(type: Type<unknown>): void { const cmpDef = getComponentDef(type); cmpDef!.dependencies = []; cmpDef!.directiveDefs = null; } /** * Emulates a dynamic import promise. * * Note: `setTimeout` is used to make `fixture.whenStable()` function * wait for promise resolution, since `whenStable()` relies on the state * of a macrotask queue. */ function dynamicImportOf<T>(type: T, timeout = 0): Promise<T> { return new Promise<T>((resolve) => { setTimeout(() => resolve(type), timeout); }); } /** * Emulates a failed dynamic import promise. */ function failedDynamicImport(): Promise<void> { return new Promise((_, reject) => { setTimeout(() => reject()); }); } /** * Helper function to await all pending dynamic imports * emulated using `dynamicImportOf` function. */ function allPendingDynamicImports() { return dynamicImportOf(null, 10); } /** * Invoke a callback function after a specified amount of time (in ms). */ function timer(delay: number): Promise<void> { return new Promise<void>((resolve) => { setTimeout(() => resolve(), delay); }); } /** * Allows to verify behavior of defer blocks by providing a set of * [time, expected output] pairs. Also allows to provide a function * instead of an expected output string, in which case the function * is invoked at a specified time. */ async function verifyTimeline( fixture: ComponentFixture<unknown>, ...slots: Array<[time: number, expected: string | VoidFunction]> ) { for (let i = 0; i < slots.length; i++) { const timeToWait = i === 0 ? slots[0][0] : slots[i][0] - slots[i - 1][0]; const slotValue = slots[i][1]; // This is an action, just invoke a function. if (typeof slotValue === 'function') { slotValue(); } tick(timeToWait); fixture.detectChanges(); if (typeof slotValue === 'string') { const actual = fixture.nativeElement.textContent.trim(); expect(actual).withContext(`${slots[i][0]}ms`).toBe(slotValue); } } } /** * Given a template, creates a component fixture and returns * a set of helper functions to trigger rendering of prefetching * of a defer block. */ function createFixture(template: string) { @Component({ selector: 'nested-cmp', standalone: true, template: '{{ block }}', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'simple-app', imports: [NestedCmp], template, }) class MyCmp { trigger = false; prefetchTrigger = false; } let loadingTimeout = 0; const deferDepsInterceptor = { intercept() { return () => { return [dynamicImportOf(NestedCmp, loadingTimeout)]; }; }, }; TestBed.configureTestingModule({ providers: [ ...COMMON_PROVIDERS, {provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}, ], }); clearDirectiveDefs(MyCmp); const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); const trigger = (loadingResourcesTime: number) => () => { loadingTimeout = loadingResourcesTime; fixture.componentInstance.trigger = true; fixture.detectChanges(); }; const triggerPrefetch = (loadingResourcesTime: number) => () => { loadingTimeout = loadingResourcesTime; fixture.componentInstance.prefetchTrigger = true; fixture.detectChanges(); }; return {trigger, triggerPrefetch, fixture}; } // Set `PLATFORM_ID` to a browser platform value to trigger defer loading // while running tests in Node. const COMMON_PROVIDERS = [{provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID}]; de
{ "end_byte": 5302, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/defer_spec.ts" }
angular/packages/core/test/acceptance/defer_spec.ts_5304_10260
ribe('@defer', () => { beforeEach(() => { TestBed.configureTestingModule({providers: COMMON_PROVIDERS}); }); it('should transition between placeholder, loading and loaded states', async () => { @Component({ selector: 'my-lazy-cmp', standalone: true, template: 'Hi!', }) class MyLazyCmp {} @Component({ standalone: true, selector: 'simple-app', imports: [MyLazyCmp], template: ` @defer (when isVisible) { <my-lazy-cmp /> } @loading { Loading... } @placeholder { Placeholder! } @error { Failed to load dependencies :( } `, }) class MyCmp { isVisible = false; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Placeholder'); fixture.componentInstance.isVisible = true; fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Loading'); // Wait for dependencies to load. await allPendingDynamicImports(); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('<my-lazy-cmp>Hi!</my-lazy-cmp>'); }); it('should work when only main block is present', async () => { @Component({ selector: 'my-lazy-cmp', standalone: true, template: 'Hi!', }) class MyLazyCmp {} @Component({ standalone: true, selector: 'simple-app', imports: [MyLazyCmp], template: ` <p>Text outside of a defer block</p> @defer (when isVisible) { <my-lazy-cmp /> } `, }) class MyCmp { isVisible = false; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Text outside of a defer block'); fixture.componentInstance.isVisible = true; fixture.detectChanges(); // Wait for dependencies to load. await allPendingDynamicImports(); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('<my-lazy-cmp>Hi!</my-lazy-cmp>'); }); it('should be able to use pipes injecting ChangeDetectorRef in defer blocks', async () => { @Pipe({name: 'test', standalone: true}) class TestPipe implements PipeTransform { changeDetectorRef = inject(ChangeDetectorRef); transform(value: any) { return value; } } @Component({ standalone: true, imports: [TestPipe], template: `@defer (when isVisible | test; prefetch when isVisible | test) {Hello}`, }) class MyCmp { isVisible = false; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe(''); fixture.componentInstance.isVisible = true; fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Hello'); }); it('should preserve execution order of dependencies', async () => { // Important note: the framework does *NOT* guarantee an exact order // in which directives are instantiated. Directives should not depend // on the order in which other directives are invoked. This test just // verifies that the order does not change when a particular part of // code is wrapped using the `@defer` block. const logs: string[] = []; @Directive({ standalone: true, selector: '[dirA]', }) class DirA { constructor(@Attribute('mode') mode: string) { logs.push(`DirA.${mode}`); } } @Directive({ standalone: true, selector: '[dirB]', }) class DirB { constructor(@Attribute('mode') mode: string) { logs.push(`DirB.${mode}`); } } @Directive({ standalone: true, selector: '[dirC]', }) class DirC { constructor(@Attribute('mode') mode: string) { logs.push(`DirC.${mode}`); } } @Component({ standalone: true, // Directive order is intentional here (different from the order // in which they are defined on the host element). imports: [DirC, DirB, DirA], template: ` @defer (when isVisible) { <div mode="defer" dirA dirB dirC></div> } <div mode="eager" dirA dirB dirC></div> `, }) class MyCmp { isVisible = true; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); const actual = {defer: [], eager: []}; for (const log of logs) { const [dir, category] = log.split('.'); (actual as {[key: string]: string[]})[category].push(dir); } // Expect that in both cases we have the same order. expect(actual.defer).toEqual(actual.eager); });
{ "end_byte": 10260, "start_byte": 5304, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/defer_spec.ts" }
angular/packages/core/test/acceptance/defer_spec.ts_10264_18424
ribe('with OnPush', () => { it('should render when @defer is used inside of an OnPush component', async () => { @Component({ selector: 'my-lazy-cmp', standalone: true, template: '{{ foo }}', }) class MyLazyCmp { foo = 'bar'; } @Component({ standalone: true, selector: 'simple-app', imports: [MyLazyCmp], changeDetection: ChangeDetectionStrategy.OnPush, template: ` @defer (on immediate) { <my-lazy-cmp /> } `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); // Wait for dependencies to load. await allPendingDynamicImports(); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('<my-lazy-cmp>bar</my-lazy-cmp>'); }); it('should render when @defer-loaded component uses OnPush', async () => { @Component({ selector: 'my-lazy-cmp', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, template: '{{ foo }}', }) class MyLazyCmp { foo = 'bar'; } @Component({ standalone: true, selector: 'simple-app', imports: [MyLazyCmp], template: ` @defer (on immediate) { <my-lazy-cmp /> } `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); // Wait for dependencies to load. await allPendingDynamicImports(); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('<my-lazy-cmp>bar</my-lazy-cmp>'); }); it('should render when both @defer-loaded and host component use OnPush', async () => { @Component({ selector: 'my-lazy-cmp', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, template: '{{ foo }}', }) class MyLazyCmp { foo = 'bar'; } @Component({ standalone: true, selector: 'simple-app', imports: [MyLazyCmp], changeDetection: ChangeDetectionStrategy.OnPush, template: ` @defer (on immediate) { <my-lazy-cmp /> } `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); // Wait for dependencies to load. await allPendingDynamicImports(); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('<my-lazy-cmp>bar</my-lazy-cmp>'); }); it('should render when both OnPush components used in other blocks (e.g. @placeholder)', async () => { @Component({ selector: 'my-lazy-cmp', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, template: '{{ foo }}', }) class MyLazyCmp { foo = 'main'; } @Component({ selector: 'another-lazy-cmp', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, template: '{{ foo }}', }) class AnotherLazyCmp { foo = 'placeholder'; } @Component({ standalone: true, selector: 'simple-app', imports: [MyLazyCmp, AnotherLazyCmp], changeDetection: ChangeDetectionStrategy.OnPush, template: ` @defer (when isVisible) { <my-lazy-cmp /> } @placeholder { <another-lazy-cmp /> } `, }) class MyCmp { isVisible = false; changeDetectorRef = inject(ChangeDetectorRef); triggerDeferBlock() { this.isVisible = true; this.changeDetectorRef.detectChanges(); } } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); // Expect placeholder to be rendered correctly. expect(fixture.nativeElement.outerHTML).toContain( '<another-lazy-cmp>placeholder</another-lazy-cmp>', ); fixture.componentInstance.triggerDeferBlock(); // Wait for dependencies to load. await allPendingDynamicImports(); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('<my-lazy-cmp>main</my-lazy-cmp>'); }); }); describe('`on` conditions', () => { it('should support `on immediate` condition', async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'Rendering {{ block }} block.', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'root-app', imports: [NestedCmp], template: ` @defer (on immediate) { <nested-cmp [block]="'primary'" /> } @placeholder { Placeholder } @loading { Loading } `, }) class RootCmp {} let loadingFnInvokedTimes = 0; const deferDepsInterceptor = { intercept() { return () => { loadingFnInvokedTimes++; return [dynamicImportOf(NestedCmp)]; }; }, }; TestBed.configureTestingModule({ providers: [ ...COMMON_PROVIDERS, {provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}, ], }); clearDirectiveDefs(RootCmp); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); // Expecting that no placeholder content would be rendered when // a loading block is present. expect(fixture.nativeElement.outerHTML).toContain('Loading'); // Expecting loading function to be triggered right away. expect(loadingFnInvokedTimes).toBe(1); await allPendingDynamicImports(); fixture.detectChanges(); // Expect that the loading resources function was not invoked again. expect(loadingFnInvokedTimes).toBe(1); // Verify primary block content. const primaryBlockHTML = fixture.nativeElement.outerHTML; expect(primaryBlockHTML).toContain( '<nested-cmp ng-reflect-block="primary">Rendering primary block.</nested-cmp>', ); // Expect that the loading resources function was not invoked again (counter remains 1). expect(loadingFnInvokedTimes).toBe(1); }); }); describe('directive matching', () => { it('should support directive matching in all blocks', async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'Rendering {{ block }} block.', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'simple-app', imports: [NestedCmp], template: ` @defer (when isVisible) { <nested-cmp [block]="'primary'" /> } @loading { Loading... <nested-cmp [block]="'loading'" /> } @placeholder { Placeholder! <nested-cmp [block]="'placeholder'" /> } @error { Failed to load dependencies :( <nested-cmp [block]="'error'" /> } `, }) class MyCmp { isVisible = false; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain( '<nested-cmp ng-reflect-block="placeholder">Rendering placeholder block.</nested-cmp>', ); fixture.componentInstance.isVisible = true; fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain( '<nested-cmp ng-reflect-block="loading">Rendering loading block.</nested-cmp>', ); // Wait for dependencies to load. await allPendingDynamicImports(); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain( '<nested-cmp ng-reflect-block="primary">Rendering primary block.</nested-cmp>', ); }); }); d
{ "end_byte": 18424, "start_byte": 10264, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/defer_spec.ts" }
angular/packages/core/test/acceptance/defer_spec.ts_18428_22550
ibe('minimum and after conditions', () => { it('should support minimum and after conditions', fakeAsync(() => { const {trigger, fixture} = createFixture(` @defer (when trigger; prefetch when prefetchTrigger) { <nested-cmp [block]="'Main'" /> } @loading (after 100ms; minimum 150ms) { Loading } @placeholder (minimum 100ms) { Placeholder } @error { Error } `); verifyTimeline( fixture, [50, 'Placeholder'], [100, trigger(170)], [150, 'Placeholder'], [250, 'Loading'], [300, 'Loading'], [450, 'Main'], ); })); it('should support @placeholder with `minimum`', fakeAsync(() => { const {trigger, fixture} = createFixture(` @defer (when trigger; prefetch when prefetchTrigger) { <nested-cmp [block]="'Main'" /> } @placeholder (minimum 100ms) { Placeholder } `); verifyTimeline(fixture, [0, trigger(40)], [90, 'Placeholder'], [100, 'Main']); })); it('should keep rendering @placeholder if trigger happened later', fakeAsync(() => { const {trigger, fixture} = createFixture(` @defer (when trigger; prefetch when prefetchTrigger) { <nested-cmp [block]="'Main'" /> } @placeholder (minimum 100ms) { Placeholder } `); verifyTimeline( fixture, [0, 'Placeholder'], [50, trigger(20)], [90, 'Placeholder'], [100, 'Main'], ); })); it( 'should transition from @placeholder to primary content ' + 'if it was prefetched', fakeAsync(() => { const {trigger, triggerPrefetch, fixture} = createFixture(` @defer (when trigger; prefetch when prefetchTrigger) { <nested-cmp [block]="'Main'" /> } @placeholder (minimum 100ms) { Placeholder } `); verifyTimeline( fixture, [0, 'Placeholder'], [20, triggerPrefetch(20)], [150, 'Placeholder'], [200, trigger(0)], [225, 'Main'], ); }), ); it('should support @loading with `minimum`', fakeAsync(() => { const {trigger, fixture} = createFixture(` @defer (when trigger; prefetch when prefetchTrigger) { <nested-cmp [block]="'Main'" /> } @loading (minimum 100ms) { Loading } `); verifyTimeline( fixture, [0, trigger(20)], // Even though loading happened in 20ms, // we still render @loading block for longer // period of time, since there was `minimum` defined. [95, 'Loading'], [100, 'Main'], ); })); it('should support @loading with `after` and `minimum`', fakeAsync(() => { const {trigger, fixture} = createFixture(` @defer (when trigger; prefetch when prefetchTrigger) { <nested-cmp [block]="'Main'" /> } @loading (after 100ms; minimum 150ms) { Loading } `); verifyTimeline( fixture, [0, trigger(150)], [50, ''], // Start showing loading after `after` ms. [100, 'Loading'], [150, 'Loading'], [200, 'Loading'], // Render main content after `after` + `minimum` ms. [300, 'Main'], ); })); it('should skip @loading when resources were prefetched', fakeAsync(() => { const {trigger, triggerPrefetch, fixture} = createFixture(` @defer (when trigger; prefetch when prefetchTrigger) { <nested-cmp [block]="'Main'" /> } @loading (minimum 100ms) { Loading } `); verifyTimeline( fixture, [0, triggerPrefetch(50)], [50, ''], [75, ''], [100, trigger(0)], // We go directly into the final state, since // resources were already preloaded. [125, 'Main'], ); })); }); d
{ "end_byte": 22550, "start_byte": 18428, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/defer_spec.ts" }
angular/packages/core/test/acceptance/defer_spec.ts_22554_31458
ibe('error handling', () => { it('should render an error block when loading fails', async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'Rendering {{ block }} block.', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'simple-app', imports: [NestedCmp], template: ` @defer (when isVisible) { <nested-cmp [block]="'primary'" /> } @loading { Loading... } @placeholder { Placeholder! } @error { Failed to load dependencies :( <nested-cmp [block]="'error'" /> } `, }) class MyCmp { isVisible = false; @ViewChildren(NestedCmp) cmps!: QueryList<NestedCmp>; } const deferDepsInterceptor = { intercept() { return () => [failedDynamicImport()]; }, }; TestBed.configureTestingModule({ providers: [{provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}], }); const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Placeholder'); fixture.componentInstance.isVisible = true; fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Loading'); // Wait for dependencies to load. await allPendingDynamicImports(); fixture.detectChanges(); // Verify that the error block is rendered. // Also verify that selector matching works in an error block. expect(fixture.nativeElement.outerHTML).toContain( '<nested-cmp ng-reflect-block="error">Rendering error block.</nested-cmp>', ); // Verify that queries work within an error block. expect(fixture.componentInstance.cmps.length).toBe(1); expect(fixture.componentInstance.cmps.get(0)?.block).toBe('error'); }); it('should report an error to the ErrorHandler if no `@error` block is defined', async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'NestedCmp', }) class NestedCmp {} @Component({ standalone: true, selector: 'simple-app', imports: [NestedCmp], template: ` @defer (when isVisible) { <nested-cmp /> } @loading { Loading... } @placeholder { Placeholder } `, }) class MyCmp { isVisible = false; } const deferDepsInterceptor = { intercept() { return () => [failedDynamicImport()]; }, }; const reportedErrors: Error[] = []; TestBed.configureTestingModule({ providers: [ { provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor, }, { provide: ErrorHandler, useClass: class extends ErrorHandler { override handleError(error: Error) { reportedErrors.push(error); } }, }, ], }); const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Placeholder'); fixture.componentInstance.isVisible = true; fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Loading'); // Wait for dependencies to load. await allPendingDynamicImports(); fixture.detectChanges(); // Verify that there was an error reported to the `ErrorHandler`. expect(reportedErrors.length).toBe(1); expect(reportedErrors[0].message).toContain('NG0750'); expect(reportedErrors[0].message).toContain(`(used in the 'MyCmp' component template)`); }); it('should not render `@error` block if loaded component has errors', async () => { @Component({ selector: 'cmp-with-error', standalone: true, template: 'CmpWithError', }) class CmpWithError { constructor() { throw new Error('CmpWithError produced an error'); } } @Component({ standalone: true, selector: 'simple-app', imports: [CmpWithError], template: ` @defer (when isVisible) { <cmp-with-error /> } @loading { Loading... } @error { Error } @placeholder { Placeholder } `, }) class MyCmp { isVisible = false; } const deferDepsInterceptor = { intercept() { return () => [dynamicImportOf(CmpWithError)]; }, }; const reportedErrors: Error[] = []; TestBed.configureTestingModule({ providers: [ { provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor, }, { provide: ErrorHandler, useClass: class extends ErrorHandler { override handleError(error: Error) { reportedErrors.push(error); } }, }, ], }); const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Placeholder'); fixture.componentInstance.isVisible = true; fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Loading'); // Wait for dependencies to load. await allPendingDynamicImports(); fixture.detectChanges(); // Expect an error to be reported to the `ErrorHandler`. expect(reportedErrors.length).toBe(1); expect(reportedErrors[0].message).toBe('CmpWithError produced an error'); // Expect that the `@loading` UI is removed, but the `@error` is *not* rendered, // because it was a component initialization error, not resource loading issue. expect(fixture.nativeElement.textContent).toBe(''); }); describe('with ngDevMode', () => { const _global: {ngDevMode: any} = global; let saveNgDevMode!: typeof ngDevMode; beforeEach(() => (saveNgDevMode = ngDevMode)); afterEach(() => (_global.ngDevMode = saveNgDevMode)); [true, false].forEach((devMode) => { it(`should log an error in the handler when there is no error block with devMode:${devMode}`, async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'Rendering {{ block }} block.', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'simple-app', imports: [NestedCmp], template: ` @defer (when isVisible) { <nested-cmp [block]="'primary'" /> } @loading { Loading... } @placeholder { Placeholder! } `, }) class MyCmp { isVisible = false; @ViewChildren(NestedCmp) cmps!: QueryList<NestedCmp>; } const deferDepsInterceptor = { intercept() { return () => [failedDynamicImport()]; }, }; const errorLogs: Error[] = []; @Injectable() class CustomErrorHandler { handleError(error: Error): void { errorLogs.push(error); } } TestBed.configureTestingModule({ providers: [ {provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}, { provide: ErrorHandler, useClass: CustomErrorHandler, }, ], }); const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Placeholder'); fixture.componentInstance.isVisible = true; fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Loading'); // ngDevMode should not be set earlier than here // as it would prevent the DEFER_BLOCK_DEPENDENCY_INTERCEPTOR from being set _global.ngDevMode = devMode; // Wait for dependencies to load. await allPendingDynamicImports(); fixture.detectChanges(); expect(errorLogs.length).toBe(1); const error = errorLogs[0]; expect(error).toBeInstanceOf(RuntimeError); expect(error.message).toMatch(/NG0750/); }); }); }); }); descr
{ "end_byte": 31458, "start_byte": 22554, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/defer_spec.ts" }
angular/packages/core/test/acceptance/defer_spec.ts_31462_40428
'queries', () => { it('should query for components within each block', async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'Rendering {{ block }} block.', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'simple-app', imports: [NestedCmp], template: ` @defer (when isVisible) { <nested-cmp [block]="'primary'" /> } @loading { Loading... <nested-cmp [block]="'loading'" /> } @placeholder { Placeholder! <nested-cmp [block]="'placeholder'" /> } @error { Failed to load dependencies :( <nested-cmp [block]="'error'" /> } `, }) class MyCmp { isVisible = false; @ViewChildren(NestedCmp) cmps!: QueryList<NestedCmp>; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.componentInstance.cmps.length).toBe(1); expect(fixture.componentInstance.cmps.get(0)?.block).toBe('placeholder'); expect(fixture.nativeElement.outerHTML).toContain( '<nested-cmp ng-reflect-block="placeholder">Rendering placeholder block.</nested-cmp>', ); fixture.componentInstance.isVisible = true; fixture.detectChanges(); expect(fixture.componentInstance.cmps.length).toBe(1); expect(fixture.componentInstance.cmps.get(0)?.block).toBe('loading'); expect(fixture.nativeElement.outerHTML).toContain( '<nested-cmp ng-reflect-block="loading">Rendering loading block.</nested-cmp>', ); // Wait for dependencies to load. await allPendingDynamicImports(); fixture.detectChanges(); expect(fixture.componentInstance.cmps.length).toBe(1); expect(fixture.componentInstance.cmps.get(0)?.block).toBe('primary'); expect(fixture.nativeElement.outerHTML).toContain( '<nested-cmp ng-reflect-block="primary">Rendering primary block.</nested-cmp>', ); }); }); describe('content projection', () => { it('should be able to project content into each block', async () => { @Component({ selector: 'cmp-a', standalone: true, template: 'CmpA', }) class CmpA {} @Component({ selector: 'cmp-b', standalone: true, template: 'CmpB', }) class CmpB {} @Component({ selector: 'nested-cmp', standalone: true, template: 'Rendering {{ block }} block.', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'my-app', imports: [NestedCmp], template: ` @defer (when isVisible) { <nested-cmp [block]="'primary'" /> <ng-content /> } @loading { Loading... <nested-cmp [block]="'loading'" /> } @placeholder { Placeholder! <nested-cmp [block]="'placeholder'" /> } @error { Failed to load dependencies :( <nested-cmp [block]="'error'" /> } `, }) class MyCmp { @Input() isVisible = false; } @Component({ standalone: true, selector: 'root-app', imports: [MyCmp, CmpA, CmpB], template: ` <my-app [isVisible]="isVisible"> Projected content. <b>Including tags</b> <cmp-a /> @defer (when isInViewport) { <cmp-b /> } @placeholder { Projected defer block placeholder. } </my-app> `, }) class RootCmp { isVisible = false; isInViewport = false; } const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain( '<nested-cmp ng-reflect-block="placeholder">Rendering placeholder block.</nested-cmp>', ); fixture.componentInstance.isVisible = true; fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain( '<nested-cmp ng-reflect-block="loading">Rendering loading block.</nested-cmp>', ); // Wait for dependencies to load. await allPendingDynamicImports(); fixture.detectChanges(); // Verify primary block content. const primaryBlockHTML = fixture.nativeElement.outerHTML; expect(primaryBlockHTML).toContain( '<nested-cmp ng-reflect-block="primary">Rendering primary block.</nested-cmp>', ); expect(primaryBlockHTML).toContain('Projected content.'); expect(primaryBlockHTML).toContain('<b>Including tags</b>'); expect(primaryBlockHTML).toContain('<cmp-a>CmpA</cmp-a>'); expect(primaryBlockHTML).toContain('Projected defer block placeholder.'); fixture.componentInstance.isInViewport = true; fixture.detectChanges(); // Wait for projected block dependencies to load. await allPendingDynamicImports(); fixture.detectChanges(); // Nested defer block was triggered and the `CmpB` content got rendered. expect(fixture.nativeElement.outerHTML).toContain('<cmp-b>CmpB</cmp-b>'); }); }); describe('nested blocks', () => { it('should be able to have nested blocks', async () => { @Component({ selector: 'cmp-a', standalone: true, template: 'CmpA', }) class CmpA {} @Component({ selector: 'nested-cmp', standalone: true, template: 'Rendering {{ block }} block.', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'root-app', imports: [NestedCmp, CmpA], template: ` @defer (when isVisible) { <nested-cmp [block]="'primary'" /> @defer (when isInViewport) { <cmp-a /> } @placeholder { Nested defer block placeholder. } } @placeholder { <nested-cmp [block]="'placeholder'" /> } `, }) class RootCmp { isVisible = false; isInViewport = false; } const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain( '<nested-cmp ng-reflect-block="placeholder">Rendering placeholder block.</nested-cmp>', ); fixture.componentInstance.isVisible = true; fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); // Verify primary block content. const primaryBlockHTML = fixture.nativeElement.outerHTML; expect(primaryBlockHTML).toContain( '<nested-cmp ng-reflect-block="primary">Rendering primary block.</nested-cmp>', ); // Make sure we have a nested block in a placeholder state. expect(primaryBlockHTML).toContain('Nested defer block placeholder.'); // Trigger condition for the nested block. fixture.componentInstance.isInViewport = true; fixture.detectChanges(); // Wait for nested block dependencies to load. await allPendingDynamicImports(); fixture.detectChanges(); // Nested defer block was triggered and the `CmpB` content got rendered. expect(fixture.nativeElement.outerHTML).toContain('<cmp-a>CmpA</cmp-a>'); }); it('should handle nested blocks that defer load the same dep', async () => { @Component({ selector: 'cmp-a', standalone: true, template: 'CmpA', }) class CmpA {} @Component({ standalone: true, selector: 'root-app', imports: [CmpA], template: ` @defer (on immediate) { <cmp-a /> @defer (on immediate) { <cmp-a /> } } `, }) class RootCmp {} const deferDepsInterceptor = { intercept() { return () => { return [dynamicImportOf(CmpA)]; }; }, }; TestBed.configureTestingModule({ providers: [{provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}], }); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); // Wait for the dependency fn promise to resolve. await allPendingDynamicImports(); fixture.detectChanges(); // Await all async work to be completed. await fixture.whenStable(); // Expect both <cmp-a> components to be rendered. expect(fixture.nativeElement.innerHTML.replaceAll('<!--container-->', '')).toBe( '<cmp-a>CmpA</cmp-a><cmp-a>CmpA</cmp-a>', ); }); }); descri
{ "end_byte": 40428, "start_byte": 31462, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/defer_spec.ts" }
angular/packages/core/test/acceptance/defer_spec.ts_40432_49155
prefetch', () => { /** * Sets up interceptors for when an idle callback is requested * and when it's cancelled. This is needed to keep track of calls * made to `requestIdleCallback` and `cancelIdleCallback` APIs. */ let id = 0; let idleCallbacksRequested: number; let idleCallbacksInvoked: number; let idleCallbacksCancelled: number; const onIdleCallbackQueue: Map<number, IdleRequestCallback> = new Map(); function resetCounters() { idleCallbacksRequested = 0; idleCallbacksInvoked = 0; idleCallbacksCancelled = 0; } resetCounters(); let nativeRequestIdleCallback: ( callback: IdleRequestCallback, options?: IdleRequestOptions, ) => number; let nativeCancelIdleCallback: (id: number) => void; const mockRequestIdleCallback = ( callback: IdleRequestCallback, options?: IdleRequestOptions, ): number => { onIdleCallbackQueue.set(id, callback); expect(idleCallbacksRequested).toBe(0); expect(NgZone.isInAngularZone()).toBe(true); idleCallbacksRequested++; return id++; }; const mockCancelIdleCallback = (id: number) => { onIdleCallbackQueue.delete(id); idleCallbacksRequested--; idleCallbacksCancelled++; }; const triggerIdleCallbacks = () => { for (const [_, callback] of onIdleCallbackQueue) { idleCallbacksInvoked++; callback(null!); } onIdleCallbackQueue.clear(); }; beforeEach(() => { nativeRequestIdleCallback = globalThis.requestIdleCallback; nativeCancelIdleCallback = globalThis.cancelIdleCallback; globalThis.requestIdleCallback = mockRequestIdleCallback; globalThis.cancelIdleCallback = mockCancelIdleCallback; resetCounters(); }); afterEach(() => { globalThis.requestIdleCallback = nativeRequestIdleCallback; globalThis.cancelIdleCallback = nativeCancelIdleCallback; onIdleCallbackQueue.clear(); resetCounters(); }); it('should be able to prefetch resources', async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'Rendering {{ block }} block.', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'root-app', imports: [NestedCmp], template: ` @defer (when deferCond; prefetch when prefetchCond) { <nested-cmp [block]="'primary'" /> } @placeholder { Placeholder } `, }) class RootCmp { deferCond = false; prefetchCond = false; } let loadingFnInvokedTimes = 0; const deferDepsInterceptor = { intercept() { return () => { loadingFnInvokedTimes++; return [dynamicImportOf(NestedCmp)]; }; }, }; TestBed.configureTestingModule({ providers: [{provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}], }); clearDirectiveDefs(RootCmp); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Placeholder'); // Make sure loading function is not yet invoked. expect(loadingFnInvokedTimes).toBe(0); // Trigger prefetching. fixture.componentInstance.prefetchCond = true; fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); // Expect that the loading resources function was invoked once. expect(loadingFnInvokedTimes).toBe(1); // Expect that placeholder content is still rendered. expect(fixture.nativeElement.outerHTML).toContain('Placeholder'); // Trigger main content. fixture.componentInstance.deferCond = true; fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); // Verify primary block content. const primaryBlockHTML = fixture.nativeElement.outerHTML; expect(primaryBlockHTML).toContain( '<nested-cmp ng-reflect-block="primary">Rendering primary block.</nested-cmp>', ); // Expect that the loading resources function was not invoked again (counter remains 1). expect(loadingFnInvokedTimes).toBe(1); }); it('should handle a case when prefetching fails', async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'Rendering {{ block }} block.', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'root-app', imports: [NestedCmp], template: ` @defer (when deferCond; prefetch when prefetchCond) { <nested-cmp [block]="'primary'" /> } @error { Loading failed } @placeholder { Placeholder } `, }) class RootCmp { deferCond = false; prefetchCond = false; } let loadingFnInvokedTimes = 0; const deferDepsInterceptor = { intercept() { return () => { loadingFnInvokedTimes++; return [failedDynamicImport()]; }; }, }; TestBed.configureTestingModule({ providers: [{provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}], }); clearDirectiveDefs(RootCmp); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Placeholder'); // Make sure loading function is not yet invoked. expect(loadingFnInvokedTimes).toBe(0); // Trigger prefetching. fixture.componentInstance.prefetchCond = true; fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); // Expect that the loading resources function was invoked once. expect(loadingFnInvokedTimes).toBe(1); // Expect that placeholder content is still rendered. expect(fixture.nativeElement.outerHTML).toContain('Placeholder'); // Trigger main content. fixture.componentInstance.deferCond = true; fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); // Since prefetching failed, expect the error block to be rendered. expect(fixture.nativeElement.outerHTML).toContain('Loading failed'); // Expect that the loading resources function was not invoked again (counter remains 1). expect(loadingFnInvokedTimes).toBe(1); }); it('should work when loading and prefetching were kicked off at the same time', async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'Rendering {{ block }} block.', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'root-app', imports: [NestedCmp], template: ` @defer (when deferCond; prefetch when deferCond) { <nested-cmp [block]="'primary'" /> } @error { Loading failed } @placeholder { Placeholder } `, }) class RootCmp { deferCond = false; } let loadingFnInvokedTimes = 0; const deferDepsInterceptor = { intercept() { return () => { loadingFnInvokedTimes++; return [dynamicImportOf(NestedCmp)]; }; }, }; TestBed.configureTestingModule({ providers: [{provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}], }); clearDirectiveDefs(RootCmp); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Placeholder'); // Make sure loading function is not yet invoked. expect(loadingFnInvokedTimes).toBe(0); // Trigger prefetching and loading at the same time. fixture.componentInstance.deferCond = true; fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); // Expect that the loading resources function was invoked once, // even though both main loading and prefetching were kicked off // at the same time. expect(loadingFnInvokedTimes).toBe(1); // Expect the main content to be rendered. expect(fixture.nativeElement.outerHTML).toContain('Rendering primary block'); }); it('sho
{ "end_byte": 49155, "start_byte": 40432, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/defer_spec.ts" }
angular/packages/core/test/acceptance/defer_spec.ts_49161_58628
pport `prefetch on idle` condition', async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'Rendering {{ block }} block.', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'root-app', imports: [NestedCmp], template: ` @defer (when deferCond; prefetch on idle) { <nested-cmp [block]="'primary'" /> } @placeholder { Placeholder } `, }) class RootCmp { deferCond = false; } let loadingFnInvokedTimes = 0; const deferDepsInterceptor = { intercept() { return () => { loadingFnInvokedTimes++; return [dynamicImportOf(NestedCmp)]; }; }, }; TestBed.configureTestingModule({ providers: [{provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}], }); clearDirectiveDefs(RootCmp); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Placeholder'); // Make sure loading function is not yet invoked. expect(loadingFnInvokedTimes).toBe(0); triggerIdleCallbacks(); await allPendingDynamicImports(); fixture.detectChanges(); // Expect that the loading resources function was invoked once. expect(loadingFnInvokedTimes).toBe(1); // Expect that placeholder content is still rendered. expect(fixture.nativeElement.outerHTML).toContain('Placeholder'); // Trigger main content. fixture.componentInstance.deferCond = true; fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); // Verify primary block content. const primaryBlockHTML = fixture.nativeElement.outerHTML; expect(primaryBlockHTML).toContain( '<nested-cmp ng-reflect-block="primary">Rendering primary block.</nested-cmp>', ); // Expect that the loading resources function was not invoked again (counter remains 1). expect(loadingFnInvokedTimes).toBe(1); }); it('should trigger prefetching based on `on idle` only once', async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'Rendering {{ block }} block.', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'root-app', imports: [NestedCmp], template: ` @for (item of items; track item) { @defer (when deferCond; prefetch on idle) { <nested-cmp [block]="'primary for \`' + item + '\`'" /> } @placeholder { Placeholder \`{{ item }}\` } } `, }) class RootCmp { deferCond = false; items = ['a', 'b', 'c']; } let loadingFnInvokedTimes = 0; const deferDepsInterceptor = { intercept() { return () => { loadingFnInvokedTimes++; return [dynamicImportOf(NestedCmp)]; }; }, }; TestBed.configureTestingModule({ providers: [{provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}], }); clearDirectiveDefs(RootCmp); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Placeholder `a`'); expect(fixture.nativeElement.outerHTML).toContain('Placeholder `b`'); expect(fixture.nativeElement.outerHTML).toContain('Placeholder `c`'); // Make sure loading function is not yet invoked. expect(loadingFnInvokedTimes).toBe(0); triggerIdleCallbacks(); await allPendingDynamicImports(); fixture.detectChanges(); // Expect that the loading resources function was invoked once. expect(loadingFnInvokedTimes).toBe(1); // Expect that placeholder content is still rendered. expect(fixture.nativeElement.outerHTML).toContain('Placeholder `a`'); // Trigger main content. fixture.componentInstance.deferCond = true; fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); // Verify primary blocks content. expect(fixture.nativeElement.outerHTML).toContain('Rendering primary for `a` block'); expect(fixture.nativeElement.outerHTML).toContain('Rendering primary for `b` block'); expect(fixture.nativeElement.outerHTML).toContain('Rendering primary for `c` block'); // Expect that the loading resources function was not invoked again (counter remains 1). expect(loadingFnInvokedTimes).toBe(1); }); it('should trigger fetching based on `on idle` only once', async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'Rendering {{ block }} block.', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'root-app', imports: [NestedCmp], template: ` @for (item of items; track item) { @defer (on idle; prefetch on idle) { <nested-cmp [block]="'primary for \`' + item + '\`'" /> } @placeholder { Placeholder \`{{ item }}\` } } `, }) class RootCmp { items = ['a', 'b', 'c']; } let loadingFnInvokedTimes = 0; const deferDepsInterceptor = { intercept() { return () => { loadingFnInvokedTimes++; return [dynamicImportOf(NestedCmp)]; }; }, }; TestBed.configureTestingModule({ providers: [{provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}], }); clearDirectiveDefs(RootCmp); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Placeholder `a`'); expect(fixture.nativeElement.outerHTML).toContain('Placeholder `b`'); expect(fixture.nativeElement.outerHTML).toContain('Placeholder `c`'); // Make sure loading function is not yet invoked. expect(loadingFnInvokedTimes).toBe(0); triggerIdleCallbacks(); await allPendingDynamicImports(); fixture.detectChanges(); // Expect that the loading resources function was invoked once. expect(loadingFnInvokedTimes).toBe(1); // Verify primary blocks content. expect(fixture.nativeElement.outerHTML).toContain('Rendering primary for `a` block'); expect(fixture.nativeElement.outerHTML).toContain('Rendering primary for `b` block'); expect(fixture.nativeElement.outerHTML).toContain('Rendering primary for `c` block'); // Expect that the loading resources function was not invoked again (counter remains 1). expect(loadingFnInvokedTimes).toBe(1); }); it('should support `prefetch on immediate` condition', async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'Rendering {{ block }} block.', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'root-app', imports: [NestedCmp], template: ` @defer (when deferCond; prefetch on immediate) { <nested-cmp [block]="'primary'" /> } @placeholder { Placeholder } `, }) class RootCmp { deferCond = false; } let loadingFnInvokedTimes = 0; const deferDepsInterceptor = { intercept() { return () => { loadingFnInvokedTimes++; return [dynamicImportOf(NestedCmp)]; }; }, }; TestBed.configureTestingModule({ providers: [ ...COMMON_PROVIDERS, {provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}, ], }); clearDirectiveDefs(RootCmp); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Placeholder'); // Expecting loading function to be triggered right away. expect(loadingFnInvokedTimes).toBe(1); await allPendingDynamicImports(); fixture.detectChanges(); // Expect that the loading resources function was invoked once. expect(loadingFnInvokedTimes).toBe(1); // Expect that placeholder content is still rendered. expect(fixture.nativeElement.outerHTML).toContain('Placeholder'); // Trigger main content. fixture.componentInstance.deferCond = true; fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); // Verify primary block content. const primaryBlockHTML = fixture.nativeElement.outerHTML; expect(primaryBlockHTML).toContain( '<nested-cmp ng-reflect-block="primary">Rendering primary block.</nested-cmp>', ); // Expect that the loading resources function was not invoked again (counter remains 1). expect(loadingFnInvokedTimes).toBe(1); }); it('should
{ "end_byte": 58628, "start_byte": 49161, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/defer_spec.ts" }
angular/packages/core/test/acceptance/defer_spec.ts_58634_68360
nested defer blocks with `on idle` triggers', async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'Primary block content.', }) class NestedCmp { @Input() block!: string; } @Component({ selector: 'another-nested-cmp', standalone: true, template: 'Nested block component.', }) class AnotherNestedCmp {} @Component({ standalone: true, selector: 'root-app', imports: [NestedCmp, AnotherNestedCmp], template: ` @defer (on idle; prefetch on idle) { <nested-cmp [block]="'primary for \`' + item + '\`'" /> <!-- Expecting that nested defer block would be initialized in a subsequent "requestIdleCallback" call. --> @defer (on idle) { <another-nested-cmp /> } @placeholder { Nested block placeholder } @loading { Nested block loading } } @placeholder { Root block placeholder } `, }) class RootCmp {} let loadingFnInvokedTimes = 0; const deferDepsInterceptor = { intercept() { return () => { loadingFnInvokedTimes++; const nextDeferredComponent = loadingFnInvokedTimes === 1 ? NestedCmp : AnotherNestedCmp; return [dynamicImportOf(nextDeferredComponent)]; }; }, }; TestBed.configureTestingModule({ providers: [{provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}], }); clearDirectiveDefs(RootCmp); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Root block placeholder'); // Make sure loading function is not yet invoked. expect(loadingFnInvokedTimes).toBe(0); // Trigger all scheduled callbacks and await all mocked dynamic imports. triggerIdleCallbacks(); await allPendingDynamicImports(); fixture.detectChanges(); // Expect that the loading resources function was invoked once. expect(loadingFnInvokedTimes).toBe(1); // Verify primary blocks content. expect(fixture.nativeElement.outerHTML).toContain('Primary block content'); // Verify that nested defer block is in a placeholder mode. expect(fixture.nativeElement.outerHTML).toContain('Nested block placeholder'); // Expect that the loading resources function was not invoked again (counter remains 1). expect(loadingFnInvokedTimes).toBe(1); triggerIdleCallbacks(); await allPendingDynamicImports(); fixture.detectChanges(); // Verify that nested defer block now renders the main content. expect(fixture.nativeElement.outerHTML).toContain('Nested block component'); // We loaded a nested block dependency, expect counter to be 2. expect(loadingFnInvokedTimes).toBe(2); }); it('should not request idle callback for each block in a for loop', async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'Rendering {{ block }} block.', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'root-app', imports: [NestedCmp], template: ` @for (item of items; track item) { @defer (on idle; prefetch on idle) { <nested-cmp [block]="'primary for \`' + item + '\`'" /> } @placeholder { Placeholder \`{{ item }}\` } } `, }) class RootCmp { items = ['a', 'b', 'c']; } let loadingFnInvokedTimes = 0; const deferDepsInterceptor = { intercept() { return () => { loadingFnInvokedTimes++; return [dynamicImportOf(NestedCmp)]; }; }, }; TestBed.configureTestingModule({ providers: [{provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}], }); clearDirectiveDefs(RootCmp); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Placeholder `a`'); expect(fixture.nativeElement.outerHTML).toContain('Placeholder `b`'); expect(fixture.nativeElement.outerHTML).toContain('Placeholder `c`'); // Make sure loading function is not yet invoked. expect(loadingFnInvokedTimes).toBe(0); // Trigger all scheduled callbacks and await all mocked dynamic imports. triggerIdleCallbacks(); await allPendingDynamicImports(); fixture.detectChanges(); // Expect that the loading resources function was invoked once. expect(loadingFnInvokedTimes).toBe(1); // Verify primary blocks content. expect(fixture.nativeElement.outerHTML).toContain('Rendering primary for `a` block'); expect(fixture.nativeElement.outerHTML).toContain('Rendering primary for `b` block'); expect(fixture.nativeElement.outerHTML).toContain('Rendering primary for `c` block'); // Expect that the loading resources function was not invoked again (counter remains 1). expect(loadingFnInvokedTimes).toBe(1); }); it('should delay nested defer blocks with `on idle` triggers', async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'Primary block content.', }) class NestedCmp { @Input() block!: string; } @Component({ selector: 'another-nested-cmp', standalone: true, template: 'Nested block component.', }) class AnotherNestedCmp {} @Component({ standalone: true, selector: 'root-app', imports: [NestedCmp, AnotherNestedCmp], template: ` @defer (on idle; prefetch on idle) { <nested-cmp [block]="'primary for \`' + item + '\`'" /> <!-- Expecting that nested defer block would be initialized in a subsequent "requestIdleCallback" call. --> @defer (on idle) { <another-nested-cmp /> } @placeholder { Nested block placeholder } @loading { Nested block loading } } @placeholder { Root block placeholder } `, }) class RootCmp {} let loadingFnInvokedTimes = 0; const deferDepsInterceptor = { intercept() { return () => { loadingFnInvokedTimes++; const nextDeferredComponent = loadingFnInvokedTimes === 1 ? NestedCmp : AnotherNestedCmp; return [dynamicImportOf(nextDeferredComponent)]; }; }, }; TestBed.configureTestingModule({ providers: [{provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}], }); clearDirectiveDefs(RootCmp); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Root block placeholder'); // Make sure loading function is not yet invoked. expect(loadingFnInvokedTimes).toBe(0); // Trigger all scheduled callbacks and await all mocked dynamic imports. triggerIdleCallbacks(); await allPendingDynamicImports(); fixture.detectChanges(); // Expect that the loading resources function was invoked once. expect(loadingFnInvokedTimes).toBe(1); // Verify primary blocks content. expect(fixture.nativeElement.outerHTML).toContain('Primary block content'); // Verify that nested defer block is in a placeholder mode. expect(fixture.nativeElement.outerHTML).toContain('Nested block placeholder'); // Expect that the loading resources function was not invoked again (counter remains 1). expect(loadingFnInvokedTimes).toBe(1); triggerIdleCallbacks(); await allPendingDynamicImports(); fixture.detectChanges(); // Verify that nested defer block now renders the main content. expect(fixture.nativeElement.outerHTML).toContain('Nested block component'); // We loaded a nested block dependency, expect counter to be 2. expect(loadingFnInvokedTimes).toBe(2); }); it('should clear idle handlers when defer block is triggered', async () => { @Component({ standalone: true, selector: 'root-app', template: ` @defer (when isVisible; on idle; prefetch on idle) { Hello world! } `, }) class RootCmp { isVisible = false; } TestBed.configureTestingModule({}); clearDirectiveDefs(RootCmp); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); // Expecting that an idle callback was requested. expect(idleCallbacksRequested).toBe(1); expect(idleCallbacksInvoked).toBe(0); expect(idleCallbacksCancelled).toBe(0); // Trigger defer block. fixture.componentInstance.isVisible = true; fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); // Expecting that an idle callback was cancelled and never invoked. expect(idleCallbacksRequested).toBe(0); expect(idleCallbacksInvoked).toBe(0); expect(idleCallbacksCancelled).toBe(1); }); }); // Note: these c
{ "end_byte": 68360, "start_byte": 58634, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/defer_spec.ts" }
angular/packages/core/test/acceptance/defer_spec.ts_68364_74951
specifically use `on interaction`, however // the resolution logic is the same for all triggers. describe('trigger resolution', () => { it('should resolve a trigger is outside the defer block', fakeAsync(() => { @Component({ standalone: true, template: ` @defer (on interaction(trigger)) { Main content } @placeholder { Placeholder } <div> <div> <div> <button #trigger></button> </div> </div> </div> `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content'); })); it('should resolve a trigger on a component outside the defer block', fakeAsync(() => { @Component({selector: 'some-comp', template: '<button></button>', standalone: true}) class SomeComp {} @Component({ standalone: true, imports: [SomeComp], template: ` @defer (on interaction(trigger)) { Main content } @placeholder { Placeholder } <div> <div> <div> <some-comp #trigger/> </div> </div> </div> `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content'); })); it('should resolve a trigger that is on a parent element', fakeAsync(() => { @Component({ standalone: true, template: ` <button #trigger> <div> <div> @defer (on interaction(trigger)) { Main content } @placeholder { Placeholder } </div> </div> </button> `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content'); })); it('should resolve a trigger that is inside a parent embedded view', fakeAsync(() => { @Component({ standalone: true, template: ` @if (cond) { <button #trigger></button> @if (cond) { @if (cond) { @defer (on interaction(trigger)) { Main content } @placeholder { Placeholder } } } } `, }) class MyCmp { cond = true; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content'); })); it('should resolve a trigger that is on a component in a parent embedded view', fakeAsync(() => { @Component({selector: 'some-comp', template: '<button></button>', standalone: true}) class SomeComp {} @Component({ standalone: true, imports: [SomeComp], template: ` @if (cond) { <some-comp #trigger/> @if (cond) { @if (cond) { @defer (on interaction(trigger)) { Main content } @placeholder { Placeholder } } } } `, }) class MyCmp { cond = true; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content'); })); it('should resolve a trigger that is inside the placeholder', fakeAsync(() => { @Component({ standalone: true, template: ` @defer (on interaction(trigger)) { Main content } @placeholder { Placeholder <div><div><div><button #trigger></button></div></div></div> } `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content'); })); it('should resolve a trigger that is a component inside the placeholder', fakeAsync(() => { @Component({selector: 'some-comp', template: '<button></button>', standalone: true}) class SomeComp {} @Component({ standalone: true, imports: [SomeComp], template: ` @defer (on interaction(trigger)) { Main content } @placeholder { Placeholder <div><div><div><some-comp #trigger/></div></div></div> } `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content'); })); }); describe('intera
{ "end_byte": 74951, "start_byte": 68364, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/defer_spec.ts" }
angular/packages/core/test/acceptance/defer_spec.ts_74955_85421
n triggers', () => { it('should load the deferred content when the trigger is clicked', fakeAsync(() => { @Component({ standalone: true, template: ` @defer (on interaction(trigger)) { Main content } @placeholder { Placeholder } <button #trigger></button> `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content'); })); it('should load the deferred content when the trigger receives a keyboard event', fakeAsync(() => { // Domino doesn't support creating custom events so we have to skip this test. if (!isBrowser) { return; } @Component({ standalone: true, template: ` @defer (on interaction(trigger)) { Main content } @placeholder { Placeholder } <button #trigger></button> `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); button.dispatchEvent(new Event('keydown')); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content'); })); it('should load the deferred content when an implicit trigger is clicked', fakeAsync(() => { @Component({ standalone: true, template: ` @defer (on interaction) { Main content } @placeholder { <button>Placeholder</button> } `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content'); })); it('should load the deferred content if a child of the trigger is clicked', fakeAsync(() => { @Component({ standalone: true, template: ` @defer (on interaction(trigger)) { Main content } @placeholder { Placeholder } <div #trigger> <div> <button></button> </div> </div> `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content'); })); it('should support multiple deferred blocks with the same trigger', fakeAsync(() => { @Component({ standalone: true, template: ` @defer (on interaction(trigger)) { Main content 1 } @placeholder { Placeholder 1 } @defer (on interaction(trigger)) { Main content 2 } @placeholder { Placeholder 2 } <button #trigger></button> `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder 1 Placeholder 2'); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content 1 Main content 2'); })); it('should unbind the trigger events when the deferred block is loaded', fakeAsync(() => { @Component({ standalone: true, template: ` @defer (on interaction(trigger)) {Main content} <button #trigger></button> `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); const spy = spyOn(button, 'removeEventListener'); button.click(); fixture.detectChanges(); flush(); expect(spy).toHaveBeenCalledTimes(2); expect(spy).toHaveBeenCalledWith('click', jasmine.any(Function), jasmine.any(Object)); expect(spy).toHaveBeenCalledWith('keydown', jasmine.any(Function), jasmine.any(Object)); })); it('should unbind the trigger events when the trigger is destroyed', fakeAsync(() => { @Component({ standalone: true, template: ` @if (renderBlock) { @defer (on interaction(trigger)) {Main content} <button #trigger></button> } `, }) class MyCmp { renderBlock = true; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); const spy = spyOn(button, 'removeEventListener'); fixture.componentInstance.renderBlock = false; fixture.detectChanges(); expect(spy).toHaveBeenCalledTimes(2); expect(spy).toHaveBeenCalledWith('click', jasmine.any(Function), jasmine.any(Object)); expect(spy).toHaveBeenCalledWith('keydown', jasmine.any(Function), jasmine.any(Object)); })); it('should unbind the trigger events when the deferred block is destroyed', fakeAsync(() => { @Component({ standalone: true, template: ` @if (renderBlock) { @defer (on interaction(trigger)) {Main content} } <button #trigger></button> `, }) class MyCmp { renderBlock = true; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); const spy = spyOn(button, 'removeEventListener'); fixture.componentInstance.renderBlock = false; fixture.detectChanges(); expect(spy).toHaveBeenCalledTimes(2); expect(spy).toHaveBeenCalledWith('click', jasmine.any(Function), jasmine.any(Object)); expect(spy).toHaveBeenCalledWith('keydown', jasmine.any(Function), jasmine.any(Object)); })); it('should remove placeholder content on interaction', fakeAsync(() => { @Component({ standalone: true, template: ` @defer (on interaction(trigger)) { Main content } @placeholder { <div>placeholder</div> } <button #trigger></button> `, }) class MyCmp {} TestBed.configureTestingModule({}); const appRef = TestBed.inject(ApplicationRef); const zone = TestBed.inject(NgZone); const componentRef = createComponent(MyCmp, { environmentInjector: TestBed.inject(EnvironmentInjector), }); const button = componentRef.location.nativeElement.querySelector('button'); zone.run(() => { appRef.attachView(componentRef.hostView); }); expect(componentRef.location.nativeElement.innerHTML).toContain('<div>placeholder</div>'); zone.run(() => { button.click(); }); tick(); expect(componentRef.location.nativeElement.innerHTML).not.toContain('<div>placeholder</div>'); })); it('should prefetch resources on interaction', fakeAsync(() => { @Component({ standalone: true, selector: 'root-app', template: ` @defer (when isLoaded; prefetch on interaction(trigger)) {Main content} <button #trigger></button> `, }) class MyCmp { // We need a `when` trigger here so that `on idle` doesn't get added automatically. readonly isLoaded = false; } let loadingFnInvokedTimes = 0; TestBed.configureTestingModule({ providers: [ { provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: { intercept: () => () => { loadingFnInvokedTimes++; return []; }, }, }, ], }); clearDirectiveDefs(MyCmp); const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(loadingFnInvokedTimes).toBe(0); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); flush(); expect(loadingFnInvokedTimes).toBe(1); })); it('should prefetch resources on interaction with an implicit trigger', fakeAsync(() => { @Component({ standalone: true, selector: 'root-app', template: ` @defer (when isLoaded; prefetch on interaction) { Main content } @placeholder { <button></button> } `, }) class MyCmp { // We need a `when` trigger here so that `on idle` doesn't get added automatically. readonly isLoaded = false; } let loadingFnInvokedTimes = 0; TestBed.configureTestingModule({ providers: [ { provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: { intercept: () => () => { loadingFnInvokedTimes++; return []; }, }, }, ], }); clearDirectiveDefs(MyCmp); const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(loadingFnInvokedTimes).toBe(0); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); flush(); expect(loadingFnInvokedTimes).toBe(1); })); }); describe('hover tr
{ "end_byte": 85421, "start_byte": 74955, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/defer_spec.ts" }
angular/packages/core/test/acceptance/defer_spec.ts_85425_94891
rs', () => { it('should load the deferred content when the trigger is hovered', fakeAsync(() => { // Domino doesn't support creating custom events so we have to skip this test. if (!isBrowser) { return; } @Component({ standalone: true, template: ` @defer (on hover(trigger)) { Main content } @placeholder { Placeholder } <button #trigger></button> `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); button.dispatchEvent(new Event('mouseenter')); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content'); })); it('should load the deferred content with an implicit trigger element', fakeAsync(() => { // Domino doesn't support creating custom events so we have to skip this test. if (!isBrowser) { return; } @Component({ standalone: true, template: ` @defer (on hover) { Main content } @placeholder { <button>Placeholder</button> } `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); button.dispatchEvent(new Event('mouseenter')); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content'); })); it('should support multiple deferred blocks with the same hover trigger', fakeAsync(() => { // Domino doesn't support creating custom events so we have to skip this test. if (!isBrowser) { return; } @Component({ standalone: true, template: ` @defer (on hover(trigger)) { Main content 1 } @placeholder { Placeholder 1 } @defer (on hover(trigger)) { Main content 2 } @placeholder { Placeholder 2 } <button #trigger></button> `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder 1 Placeholder 2'); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); button.dispatchEvent(new Event('mouseenter')); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content 1 Main content 2'); })); it('should unbind the trigger events when the deferred block is loaded', fakeAsync(() => { // Domino doesn't support creating custom events so we have to skip this test. if (!isBrowser) { return; } @Component({ standalone: true, template: ` @defer (on hover(trigger)) { Main content } <button #trigger></button> `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); const spy = spyOn(button, 'removeEventListener'); button.dispatchEvent(new Event('mouseenter')); fixture.detectChanges(); flush(); expect(spy).toHaveBeenCalledTimes(3); expect(spy).toHaveBeenCalledWith('mouseenter', jasmine.any(Function), jasmine.any(Object)); expect(spy).toHaveBeenCalledWith('mouseover', jasmine.any(Function), jasmine.any(Object)); expect(spy).toHaveBeenCalledWith('focusin', jasmine.any(Function), jasmine.any(Object)); })); it('should unbind the trigger events when the trigger is destroyed', fakeAsync(() => { // Domino doesn't support creating custom events so we have to skip this test. if (!isBrowser) { return; } @Component({ standalone: true, template: ` @if (renderBlock) { @defer (on hover(trigger)) { Main content } <button #trigger></button> } `, }) class MyCmp { renderBlock = true; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); const spy = spyOn(button, 'removeEventListener'); fixture.componentInstance.renderBlock = false; fixture.detectChanges(); expect(spy).toHaveBeenCalledTimes(3); expect(spy).toHaveBeenCalledWith('mouseenter', jasmine.any(Function), jasmine.any(Object)); expect(spy).toHaveBeenCalledWith('mouseover', jasmine.any(Function), jasmine.any(Object)); expect(spy).toHaveBeenCalledWith('focusin', jasmine.any(Function), jasmine.any(Object)); })); it('should unbind the trigger events when the deferred block is destroyed', fakeAsync(() => { // Domino doesn't support creating custom events so we have to skip this test. if (!isBrowser) { return; } @Component({ standalone: true, template: ` @if (renderBlock) { @defer (on hover(trigger)) { Main content } } <button #trigger></button> `, }) class MyCmp { renderBlock = true; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); const spy = spyOn(button, 'removeEventListener'); fixture.componentInstance.renderBlock = false; fixture.detectChanges(); expect(spy).toHaveBeenCalledTimes(3); expect(spy).toHaveBeenCalledWith('mouseenter', jasmine.any(Function), jasmine.any(Object)); expect(spy).toHaveBeenCalledWith('mouseover', jasmine.any(Function), jasmine.any(Object)); expect(spy).toHaveBeenCalledWith('focusin', jasmine.any(Function), jasmine.any(Object)); })); it('should prefetch resources on hover', fakeAsync(() => { // Domino doesn't support creating custom events so we have to skip this test. if (!isBrowser) { return; } @Component({ standalone: true, selector: 'root-app', template: ` @defer (when isLoaded; prefetch on hover(trigger)) { Main content } <button #trigger></button> `, }) class MyCmp { // We need a `when` trigger here so that `on idle` doesn't get added automatically. readonly isLoaded = false; } let loadingFnInvokedTimes = 0; TestBed.configureTestingModule({ providers: [ { provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: { intercept: () => () => { loadingFnInvokedTimes++; return []; }, }, }, ], }); clearDirectiveDefs(MyCmp); const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(loadingFnInvokedTimes).toBe(0); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); button.dispatchEvent(new Event('mouseenter')); fixture.detectChanges(); flush(); expect(loadingFnInvokedTimes).toBe(1); })); it('should prefetch resources when an implicit trigger is hovered', fakeAsync(() => { // Domino doesn't support creating custom events so we have to skip this test. if (!isBrowser) { return; } @Component({ standalone: true, selector: 'root-app', template: ` @defer (when isLoaded; prefetch on hover) { Main content } @placeholder { <button></button> } `, }) class MyCmp { // We need a `when` trigger here so that `on idle` doesn't get added automatically. readonly isLoaded = false; } let loadingFnInvokedTimes = 0; TestBed.configureTestingModule({ providers: [ { provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: { intercept: () => () => { loadingFnInvokedTimes++; return []; }, }, }, ], }); clearDirectiveDefs(MyCmp); const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(loadingFnInvokedTimes).toBe(0); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); button.dispatchEvent(new Event('mouseenter')); fixture.detectChanges(); flush(); expect(loadingFnInvokedTimes).toBe(1); })); }); describe('`on timer`
{ "end_byte": 94891, "start_byte": 85425, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/defer_spec.ts" }
angular/packages/core/test/acceptance/defer_spec.ts_94895_102855
ggers', () => { it('should trigger based on `on timer` condition', async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'Rendering {{ block }} block.', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'root-app', imports: [NestedCmp], template: ` @for (item of items; track item) { @defer (on timer(500ms)) { <nested-cmp [block]="'primary for \`' + item + '\`'" /> } @placeholder { Placeholder \`{{ item }}\` } } `, }) class RootCmp { items = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; } let loadingFnInvokedTimes = 0; const deferDepsInterceptor = { intercept() { return () => { loadingFnInvokedTimes++; return [dynamicImportOf(NestedCmp)]; }; }, }; TestBed.configureTestingModule({ providers: [{provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}], }); clearDirectiveDefs(RootCmp); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Placeholder `a`'); expect(fixture.nativeElement.outerHTML).toContain('Placeholder `b`'); expect(fixture.nativeElement.outerHTML).toContain('Placeholder `c`'); // Make sure loading function is not yet invoked. expect(loadingFnInvokedTimes).toBe(0); await timer(1000); await allPendingDynamicImports(); // fetching dependencies of the defer block fixture.detectChanges(); // Expect that the loading resources function was invoked once. expect(loadingFnInvokedTimes).toBe(1); // Verify primary blocks content. expect(fixture.nativeElement.outerHTML).toContain('Rendering primary for `a` block'); expect(fixture.nativeElement.outerHTML).toContain('Rendering primary for `b` block'); expect(fixture.nativeElement.outerHTML).toContain('Rendering primary for `c` block'); // Expect that the loading resources function was not invoked again (counter remains 1). expect(loadingFnInvokedTimes).toBe(1); // Adding an extra item to the list fixture.componentInstance.items = ['a', 'b', 'c', 'd']; fixture.detectChanges(); // Make sure loading function is still 1 (i.e. wasn't invoked again). expect(loadingFnInvokedTimes).toBe(1); }); it('should trigger nested `on timer` condition', async () => { @Component({ standalone: true, selector: 'root-app', template: ` @defer (on timer(100ms)) { primary[top] @defer (on timer(100ms)) { primary[nested] } @placeholder { placeholder[nested] } } @placeholder { placeholder[top] } `, }) class RootCmp {} TestBed.configureTestingModule({}); clearDirectiveDefs(RootCmp); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('placeholder[top]'); await timer(110); fixture.detectChanges(); // Verify primary blocks content after triggering top-level @defer. expect(fixture.nativeElement.outerHTML).toContain('primary[top]'); expect(fixture.nativeElement.outerHTML).toContain('placeholder[nested]'); await timer(110); fixture.detectChanges(); // Verify that nested @defer block was triggered as well. expect(fixture.nativeElement.outerHTML).toContain('primary[top]'); expect(fixture.nativeElement.outerHTML).toContain('primary[nested]'); }); }); describe('`prefetch on timer` triggers', () => { it('should trigger prefetching based on `on timer` condition', async () => { @Component({ selector: 'nested-cmp', standalone: true, template: 'Rendering {{ block }} block.', }) class NestedCmp { @Input() block!: string; } @Component({ standalone: true, selector: 'root-app', imports: [NestedCmp], template: ` @for (item of items; track item) { @defer (when shouldTrigger; prefetch on timer(100ms)) { <nested-cmp [block]="'primary for \`' + item + '\`'" /> } @placeholder { Placeholder \`{{ item }}\` } } `, }) class RootCmp { shouldTrigger = false; items = ['a', 'b', 'c']; } let loadingFnInvokedTimes = 0; const deferDepsInterceptor = { intercept() { return () => { loadingFnInvokedTimes++; return [dynamicImportOf(NestedCmp)]; }; }, }; TestBed.configureTestingModule({ providers: [{provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}], }); clearDirectiveDefs(RootCmp); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(fixture.nativeElement.outerHTML).toContain('Placeholder `a`'); expect(fixture.nativeElement.outerHTML).toContain('Placeholder `b`'); expect(fixture.nativeElement.outerHTML).toContain('Placeholder `c`'); // Make sure loading function is not yet invoked. expect(loadingFnInvokedTimes).toBe(0); await timer(200); await allPendingDynamicImports(); // fetching dependencies of the defer block fixture.detectChanges(); // Expect that the loading resources function was invoked once. expect(loadingFnInvokedTimes).toBe(1); // Trigger rendering of all defer blocks. fixture.componentInstance.shouldTrigger = true; fixture.detectChanges(); // Verify primary blocks content. expect(fixture.nativeElement.outerHTML).toContain('Rendering primary for `a` block'); expect(fixture.nativeElement.outerHTML).toContain('Rendering primary for `b` block'); expect(fixture.nativeElement.outerHTML).toContain('Rendering primary for `c` block'); // Make sure the loading function wasn't invoked again (count remains `1`). expect(loadingFnInvokedTimes).toBe(1); }); it('should trigger prefetching and rendering based on `on timer` condition', fakeAsync(() => { const {fixture} = createFixture(` @defer (on timer(200ms); prefetch on timer(100ms)) { <nested-cmp [block]="'Main'" /> } @placeholder { Placeholder } `); verifyTimeline(fixture, [50, 'Placeholder'], [150, 'Placeholder'], [250, 'Main']); })); it('should clear timeout callbacks when defer block is triggered', fakeAsync(() => { const setSpy = spyOn(globalThis, 'setTimeout'); const clearSpy = spyOn(globalThis, 'clearTimeout'); @Component({ standalone: true, selector: 'root-app', template: ` @defer (when isVisible; on timer(200ms); prefetch on timer(100ms)) { Hello world! } `, }) class RootCmp { isVisible = false; } TestBed.configureTestingModule({}); clearDirectiveDefs(RootCmp); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); // Trigger defer block fixture.componentInstance.isVisible = true; fixture.detectChanges(); // The `clearTimeout` was called synchronously, because the `when` // condition was triggered, which resulted in timers cleanup. expect(setSpy).toHaveBeenCalledTimes(2); expect(clearSpy).toHaveBeenCalledTimes(2); })); }); describe('viewport tri
{ "end_byte": 102855, "start_byte": 94895, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/defer_spec.ts" }
angular/packages/core/test/acceptance/defer_spec.ts_102859_112365
s', () => { let activeObservers: MockIntersectionObserver[] = []; let nativeIntersectionObserver: typeof IntersectionObserver; beforeEach(() => { nativeIntersectionObserver = globalThis.IntersectionObserver; globalThis.IntersectionObserver = MockIntersectionObserver; }); afterEach(() => { globalThis.IntersectionObserver = nativeIntersectionObserver; activeObservers = []; }); /** * Mocked out implementation of the native IntersectionObserver API. We need to * mock it out for tests, because it's unsupported in Domino and we can't trigger * it reliably in the browser. */ class MockIntersectionObserver implements IntersectionObserver { root = null; rootMargin = null!; thresholds = null!; observedElements = new Set<Element>(); private elementsInView = new Set<Element>(); constructor(private callback: IntersectionObserverCallback) { activeObservers.push(this); } static invokeCallbacksForElement(element: Element, isInView: boolean) { for (const observer of activeObservers) { const elements = observer.elementsInView; const wasInView = elements.has(element); if (isInView) { elements.add(element); } else { elements.delete(element); } observer.invokeCallback(); if (wasInView) { elements.add(element); } else { elements.delete(element); } } } private invokeCallback() { for (const el of this.observedElements) { this.callback( [ { target: el, isIntersecting: this.elementsInView.has(el), // Unsupported properties. boundingClientRect: null!, intersectionRatio: null!, intersectionRect: null!, rootBounds: null, time: null!, }, ], this, ); } } observe(element: Element) { this.observedElements.add(element); // Native observers fire their callback as soon as an // element is observed so we try to mimic it here. this.invokeCallback(); } unobserve(element: Element) { this.observedElements.delete(element); } disconnect() { this.observedElements.clear(); this.elementsInView.clear(); } takeRecords(): IntersectionObserverEntry[] { throw new Error('Not supported'); } } it('should load the deferred content when the trigger is in the viewport', fakeAsync(() => { @Component({ standalone: true, template: ` @defer (on viewport(trigger)) { Main content } @placeholder { Placeholder } <button #trigger></button> `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); MockIntersectionObserver.invokeCallbacksForElement(button, true); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content'); })); it('should load the deferred content when an implicit trigger is in the viewport', fakeAsync(() => { @Component({ standalone: true, template: ` @defer (on viewport) { Main content } @placeholder { <button>Placeholder</button> } `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); MockIntersectionObserver.invokeCallbacksForElement(button, true); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content'); })); it('should not load the content if the trigger is not in the view yet', fakeAsync(() => { @Component({ standalone: true, template: ` @defer (on viewport(trigger)) { Main content } @placeholder { Placeholder } <button #trigger></button> `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); MockIntersectionObserver.invokeCallbacksForElement(button, false); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); MockIntersectionObserver.invokeCallbacksForElement(button, false); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder'); MockIntersectionObserver.invokeCallbacksForElement(button, true); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content'); })); it('should support multiple deferred blocks with the same trigger', fakeAsync(() => { @Component({ standalone: true, template: ` @defer (on viewport(trigger)) { Main content 1 } @placeholder { Placeholder 1 } @defer (on viewport(trigger)) { Main content 2 } @placeholder { Placeholder 2 } <button #trigger></button> `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toBe('Placeholder 1 Placeholder 2'); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); MockIntersectionObserver.invokeCallbacksForElement(button, true); fixture.detectChanges(); flush(); expect(fixture.nativeElement.textContent.trim()).toBe('Main content 1 Main content 2'); })); it('should stop observing the trigger when the deferred block is loaded', fakeAsync(() => { @Component({ standalone: true, template: ` @defer (on viewport(trigger)) { Main content } <button #trigger></button> `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); expect(activeObservers.length).toBe(1); expect(activeObservers[0].observedElements.size).toBe(1); expect(activeObservers[0].observedElements.has(button)).toBe(true); MockIntersectionObserver.invokeCallbacksForElement(button, true); fixture.detectChanges(); flush(); expect(activeObservers.length).toBe(1); expect(activeObservers[0].observedElements.size).toBe(0); })); it('should stop observing the trigger when the trigger is destroyed', fakeAsync(() => { @Component({ standalone: true, template: ` @if (renderBlock) { @defer (on viewport(trigger)) { Main content } <button #trigger></button> } `, }) class MyCmp { renderBlock = true; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); expect(activeObservers.length).toBe(1); expect(activeObservers[0].observedElements.size).toBe(1); expect(activeObservers[0].observedElements.has(button)).toBe(true); fixture.componentInstance.renderBlock = false; fixture.detectChanges(); expect(activeObservers.length).toBe(1); expect(activeObservers[0].observedElements.size).toBe(0); })); it('should stop observing the trigger when the deferred block is destroyed', fakeAsync(() => { @Component({ standalone: true, template: ` @if (renderBlock) { @defer (on viewport(trigger)) { Main content } } <button #trigger></button> `, }) class MyCmp { renderBlock = true; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); expect(activeObservers.length).toBe(1); expect(activeObservers[0].observedElements.size).toBe(1); expect(activeObservers[0].observedElements.has(button)).toBe(true); fixture.componentInstance.renderBlock = false; fixture.detectChanges(); expect(activeObservers.length).toBe(1); expect(activeObservers[0].observedElements.size).toBe(0); })); it('should disconnec
{ "end_byte": 112365, "start_byte": 102859, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/defer_spec.ts" }
angular/packages/core/test/acceptance/defer_spec.ts_112371_121508
intersection observer once all deferred blocks have been loaded', fakeAsync(() => { @Component({ standalone: true, template: ` <button #triggerOne></button> @defer (on viewport(triggerOne)) { One } <button #triggerTwo></button> @defer (on viewport(triggerTwo)) { Two } `, }) class MyCmp {} const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(activeObservers.length).toBe(1); const buttons = Array.from<HTMLElement>(fixture.nativeElement.querySelectorAll('button')); const observer = activeObservers[0]; const disconnectSpy = spyOn(observer, 'disconnect').and.callThrough(); expect(Array.from(observer.observedElements)).toEqual(buttons); MockIntersectionObserver.invokeCallbacksForElement(buttons[0], true); fixture.detectChanges(); expect(disconnectSpy).not.toHaveBeenCalled(); expect(Array.from(observer.observedElements)).toEqual([buttons[1]]); MockIntersectionObserver.invokeCallbacksForElement(buttons[1], true); fixture.detectChanges(); expect(disconnectSpy).toHaveBeenCalled(); expect(observer.observedElements.size).toBe(0); })); it('should prefetch resources when the trigger comes into the viewport', fakeAsync(() => { @Component({ standalone: true, selector: 'root-app', template: ` @defer (when isLoaded; prefetch on viewport(trigger)) { Main content } <button #trigger></button> `, }) class MyCmp { // We need a `when` trigger here so that `on idle` doesn't get added automatically. readonly isLoaded = false; } let loadingFnInvokedTimes = 0; TestBed.configureTestingModule({ providers: [ { provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: { intercept: () => () => { loadingFnInvokedTimes++; return []; }, }, }, ], }); clearDirectiveDefs(MyCmp); const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(loadingFnInvokedTimes).toBe(0); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); MockIntersectionObserver.invokeCallbacksForElement(button, true); fixture.detectChanges(); flush(); expect(loadingFnInvokedTimes).toBe(1); })); it('should prefetch resources when an implicit trigger comes into the viewport', fakeAsync(() => { @Component({ standalone: true, selector: 'root-app', template: ` @defer (when isLoaded; prefetch on viewport) { Main content } @placeholder { <button></button> } `, }) class MyCmp { // We need a `when` trigger here so that `on idle` doesn't get added automatically. readonly isLoaded = false; } let loadingFnInvokedTimes = 0; TestBed.configureTestingModule({ providers: [ { provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: { intercept: () => () => { loadingFnInvokedTimes++; return []; }, }, }, ], }); clearDirectiveDefs(MyCmp); const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); expect(loadingFnInvokedTimes).toBe(0); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); MockIntersectionObserver.invokeCallbacksForElement(button, true); fixture.detectChanges(); flush(); expect(loadingFnInvokedTimes).toBe(1); })); it('should load deferred content in a loop', fakeAsync(() => { @Component({ standalone: true, template: ` @for (item of items; track item) { @defer (on viewport) {d{{item}} } @placeholder {<button>p{{item}} </button>} } `, }) class MyCmp { items = [1, 2, 3, 4, 5, 6]; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); const buttons = Array.from<Element>(fixture.nativeElement.querySelectorAll('button')); const items = fixture.componentInstance.items; // None of the blocks are loaded yet. expect(fixture.nativeElement.textContent.trim()).toBe('p1 p2 p3 p4 p5 p6'); // First half of the blocks is loaded. for (let i = 0; i < items.length / 2; i++) { MockIntersectionObserver.invokeCallbacksForElement(buttons[i], true); fixture.detectChanges(); flush(); } expect(fixture.nativeElement.textContent.trim()).toBe('d1 d2 d3 p4 p5 p6'); // Second half of the blocks is loaded. for (let i = items.length / 2; i < items.length; i++) { MockIntersectionObserver.invokeCallbacksForElement(buttons[i], true); fixture.detectChanges(); flush(); } expect(fixture.nativeElement.textContent.trim()).toBe('d1 d2 d3 d4 d5 d6'); })); }); describe('DOM-based events cleanup', () => { it('should unbind `interaction` trigger events when the deferred block is loaded', async () => { @Component({ standalone: true, template: ` @defer ( when isVisible; on interaction(trigger); prefetch on interaction(prefetchTrigger) ) { Main content } <button #trigger></button> <div #prefetchTrigger></div> `, }) class MyCmp { isVisible = false; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); const triggerSpy = spyOn(button, 'removeEventListener'); const div = fixture.nativeElement.querySelector('div'); const prefetchSpy = spyOn(div, 'removeEventListener'); fixture.componentInstance.isVisible = true; fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); // Verify that trigger element is cleaned up. expect(triggerSpy).toHaveBeenCalledTimes(2); expect(triggerSpy).toHaveBeenCalledWith('click', jasmine.any(Function), jasmine.any(Object)); expect(triggerSpy).toHaveBeenCalledWith( 'keydown', jasmine.any(Function), jasmine.any(Object), ); // Verify that prefetch trigger element is cleaned up. expect(prefetchSpy).toHaveBeenCalledTimes(2); expect(prefetchSpy).toHaveBeenCalledWith('click', jasmine.any(Function), jasmine.any(Object)); expect(prefetchSpy).toHaveBeenCalledWith( 'keydown', jasmine.any(Function), jasmine.any(Object), ); }); it('should unbind `hover` trigger events when the deferred block is loaded', async () => { @Component({ standalone: true, template: ` @defer ( when isVisible; on hover(trigger); prefetch on hover(prefetchTrigger) ) { Main content } <button #trigger></button> <div #prefetchTrigger></div> `, }) class MyCmp { isVisible = false; } const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); const triggerSpy = spyOn(button, 'removeEventListener'); const div = fixture.nativeElement.querySelector('div'); const prefetchSpy = spyOn(div, 'removeEventListener'); fixture.componentInstance.isVisible = true; fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); // Verify that trigger element is cleaned up. expect(triggerSpy).toHaveBeenCalledTimes(3); expect(triggerSpy).toHaveBeenCalledWith( 'mouseenter', jasmine.any(Function), jasmine.any(Object), ); expect(triggerSpy).toHaveBeenCalledWith( 'mouseover', jasmine.any(Function), jasmine.any(Object), ); expect(triggerSpy).toHaveBeenCalledWith( 'focusin', jasmine.any(Function), jasmine.any(Object), ); // Verify that prefetch trigger element is cleaned up. expect(prefetchSpy).toHaveBeenCalledTimes(3); expect(prefetchSpy).toHaveBeenCalledWith( 'mouseenter', jasmine.any(Function), jasmine.any(Object), ); expect(prefetchSpy).toHaveBeenCalledWith( 'mouseover', jasmine.any(Function), jasmine.any(Object), ); expect(prefetchSpy).toHaveBeenCalledWith( 'focusin', jasmine.any(Function), jasmine.any(Object), ); }); }); describe('DI', () => {
{ "end_byte": 121508, "start_byte": 112371, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/defer_spec.ts" }
angular/packages/core/test/acceptance/defer_spec.ts_121512_129295
t('should provide access to tokens from a parent component', async () => { const TokenA = new InjectionToken('A'); const TokenB = new InjectionToken('B'); @Component({ standalone: true, selector: 'parent-cmp', template: '<ng-content />', providers: [{provide: TokenA, useValue: 'TokenA.ParentCmp'}], }) class ParentCmp {} @Component({ standalone: true, selector: 'child-cmp', template: 'Token A: {{ parentTokenA }} | Token B: {{ parentTokenB }}', }) class ChildCmp { parentTokenA = inject(TokenA); parentTokenB = inject(TokenB); } @Component({ standalone: true, selector: 'app-root', template: ` <parent-cmp> @defer (when isVisible) { <child-cmp /> } </parent-cmp> `, imports: [ChildCmp, ParentCmp], providers: [{provide: TokenB, useValue: 'TokenB.RootCmp'}], }) class RootCmp { isVisible = true; } const deferDepsInterceptor = { intercept() { return () => { return [dynamicImportOf(ChildCmp)]; }; }, }; TestBed.configureTestingModule({ providers: [{provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}], deferBlockBehavior: DeferBlockBehavior.Playthrough, }); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); // Verify that tokens from parent components are available for injection // inside a component within a `@defer` block. const tokenA = 'TokenA.ParentCmp'; const tokenB = 'TokenB.RootCmp'; expect(fixture.nativeElement.innerHTML).toContain( `<child-cmp>Token A: ${tokenA} | Token B: ${tokenB}</child-cmp>`, ); }); it( 'should provide access to tokens from a parent component ' + 'for components instantiated via `createComponent` call (when a corresponding NodeInjector is used in the call), ' + 'but attached to the ApplicationRef', async () => { const TokenA = new InjectionToken('A'); const TokenB = new InjectionToken('B'); @NgModule({ providers: [{provide: TokenB, useValue: 'TokenB value'}], }) class MyModule {} @Component({ selector: 'lazy', standalone: true, imports: [MyModule], template: ` Lazy Component! Token: {{ token }} `, }) class Lazy { token = inject(TokenA); } @Component({ standalone: true, imports: [Lazy], template: ` @defer (on immediate) { <lazy /> } `, }) class Dialog {} @Component({ standalone: true, selector: 'app-root', providers: [{provide: TokenA, useValue: 'TokenA from RootCmp'}], template: ` <div #container></div> `, }) class RootCmp { injector = inject(Injector); appRef = inject(ApplicationRef); envInjector = inject(EnvironmentInjector); @ViewChild('container', {read: ElementRef}) container!: ElementRef; openModal() { const hostElement = this.container.nativeElement; const componentRef = createComponent(Dialog, { hostElement, elementInjector: this.injector, environmentInjector: this.envInjector, }); this.appRef.attachView(componentRef.hostView); componentRef.changeDetectorRef.detectChanges(); } } const deferDepsInterceptor = { intercept() { return () => { return [dynamicImportOf(Lazy)]; }; }, }; TestBed.configureTestingModule({ providers: [ {provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}, ], deferBlockBehavior: DeferBlockBehavior.Playthrough, }); const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); fixture.componentInstance.openModal(); // The call above instantiates a component that uses a `@defer` block, // so we need to wait for dynamic imports to complete. await allPendingDynamicImports(); fixture.detectChanges(); // Verify that tokens from parent components are available for injection // inside a component within a `@defer` block. expect(fixture.nativeElement.innerHTML).toContain( `<lazy> Lazy Component! Token: TokenA from RootCmp </lazy>`, ); }, ); }); describe('NgModules', () => { it('should provide access to tokens from imported NgModules', async () => { let serviceInitCount = 0; const TokenA = new InjectionToken(''); @Injectable() class Service { id = 'ChartsModule.Service'; constructor() { serviceInitCount++; } } @Component({ selector: 'chart', template: 'Service:{{ svc.id }}|TokenA:{{ tokenA }}', standalone: false, }) class Chart { svc = inject(Service); tokenA = inject(TokenA); } @NgModule({ providers: [Service], declarations: [Chart], exports: [Chart], }) class ChartsModule {} @Component({ selector: 'chart-collection', template: '<chart />', standalone: true, imports: [ChartsModule], }) class ChartCollectionComponent {} @Component({ selector: 'app-root', standalone: true, template: ` @for(item of items; track $index) { @defer (when isVisible) { <chart-collection /> } } `, imports: [ChartCollectionComponent], providers: [{provide: TokenA, useValue: 'MyCmp.A'}], }) class MyCmp { items = [1, 2, 3]; isVisible = true; } const deferDepsInterceptor = { intercept() { return () => { return [dynamicImportOf(ChartCollectionComponent)]; }; }, }; TestBed.configureTestingModule({ providers: [{provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}], deferBlockBehavior: DeferBlockBehavior.Playthrough, }); clearDirectiveDefs(MyCmp); const fixture = TestBed.createComponent(MyCmp); fixture.detectChanges(); await allPendingDynamicImports(); fixture.detectChanges(); // Verify that the `Service` injectable was initialized only once, // even though it was injected in 3 instances of the `<chart>` component, // used within defer blocks. expect(serviceInitCount).toBe(1); expect(fixture.nativeElement.querySelectorAll('chart').length).toBe(3); // Verify that a service defined within an NgModule can inject services // provided within the same NgModule. const serviceFromNgModule = 'Service:ChartsModule.Service'; // Make sure sure that a nested `<chart>` component from the defer block // can inject tokens provided in parent component (that contains `@defer` // in its template). const tokenFromRootComponent = 'TokenA:MyCmp.A'; expect(fixture.nativeElement.innerHTML).toContain( `<chart>${serviceFromNgModule}|${tokenFromRootComponent}</chart>`, ); }); }); describe('Router', () => {
{ "end_byte": 129295, "start_byte": 121512, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/defer_spec.ts" }
angular/packages/core/test/acceptance/defer_spec.ts_129299_132559
it('should inject correct `ActivatedRoutes` in components within defer blocks', async () => { let deferCmpEnvInjector: EnvironmentInjector; const TokenA = new InjectionToken<string>('TokenA'); @NgModule({ providers: [{provide: TokenA, useValue: 'nested'}], }) class MyModuleA {} @Component({ standalone: true, imports: [RouterOutlet], template: '<router-outlet />', }) class App {} @Component({ standalone: true, selector: 'another-child', imports: [CommonModule, MyModuleA], template: 'another child: {{route.snapshot.url[0]}} | token: {{tokenA}}', }) class AnotherChild { route = inject(ActivatedRoute); tokenA = inject(TokenA); constructor() { deferCmpEnvInjector = inject(EnvironmentInjector); } } @Component({ standalone: true, imports: [CommonModule, AnotherChild], template: ` child: {{route.snapshot.url[0]}} | token: {{tokenA}} @defer (on immediate) { <another-child /> } `, }) class Child { route = inject(ActivatedRoute); tokenA = inject(TokenA); } const deferDepsInterceptor = { intercept() { return () => { return [dynamicImportOf(AnotherChild, 10)]; }; }, }; TestBed.configureTestingModule({ providers: [ {provide: TokenA, useValue: 'root'}, {provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID}, {provide: ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, useValue: deferDepsInterceptor}, provideRouter([ {path: 'a', component: Child}, {path: 'b', component: Child}, ]), ], }); clearDirectiveDefs(Child); const app = TestBed.createComponent(App); await TestBed.inject(Router).navigateByUrl('/a'); app.detectChanges(); await allPendingDynamicImports(); app.detectChanges(); expect(app.nativeElement.innerHTML).toContain('child: a | token: root'); expect(app.nativeElement.innerHTML).toContain('another child: a | token: nested'); // Navigate to `/b` await TestBed.inject(Router).navigateByUrl('/b'); app.detectChanges(); await allPendingDynamicImports(); app.detectChanges(); // Make sure that the `getInjectorResolutionPath` debugging utility // (used by DevTools) doesn't expose Router's `OutletInjector` in // the resolution path. `OutletInjector` is a special case, because it // doesn't store any tokens itself, we point to the parent injector instead. const resolutionPath = getInjectorResolutionPath(deferCmpEnvInjector!); for (const inj of resolutionPath) { expect(inj).not.toBeInstanceOf(ChainedInjector); } // Expect that `ActivatedRoute` information get updated inside // of a component used in a `@defer` block. expect(app.nativeElement.innerHTML).toContain('child: b | token: root'); expect(app.nativeElement.innerHTML).toContain('another child: b | token: nested'); }); }); });
{ "end_byte": 132559, "start_byte": 129299, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/defer_spec.ts" }
angular/packages/core/test/acceptance/view_container_ref_spec.ts_0_2300
/** * @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, DOCUMENT} from '@angular/common'; import {computeMsgId} from '@angular/compiler'; import { ChangeDetectorRef, Compiler, Component, createComponent, createEnvironmentInjector, Directive, DoCheck, ElementRef, EmbeddedViewRef, EnvironmentInjector, ErrorHandler, InjectionToken, Injector, Input, NgModule, NgModuleRef, NO_ERRORS_SCHEMA, OnDestroy, OnInit, Pipe, PipeTransform, QueryList, Renderer2, RendererFactory2, RendererType2, Sanitizer, TemplateRef, ViewChild, ViewChildren, ViewContainerRef, ɵsetDocument, } from '@angular/core'; import {ngDevModeResetPerfCounters} from '@angular/core/src/util/ng_dev_mode'; import {ComponentFixture, TestBed, TestComponentRenderer} from '@angular/core/testing'; import {clearTranslations, loadTranslations} from '@angular/localize'; import {By, DomSanitizer} from '@angular/platform-browser'; import {expect} from '@angular/platform-browser/testing/src/matchers'; describe('ViewContainerRef', () => { /** * Gets the inner HTML of the given element with all HTML comments and Angular internal * reflect attributes omitted. This makes HTML comparisons easier and less verbose. */ function getElementHtml(element: Element) { return element.innerHTML .replace(/<!--(\W|\w)*?-->/g, '') .replace(/\sng-reflect-\S*="[^"]*"/g, ''); } /** * Helper method to retrieve the text content of the given element. This method also strips all * leading and trailing whitespace and removes all newlines. This makes element content * comparisons easier and less verbose. */ function getElementText(element: Element): string { return element.textContent!.trim().replace(/\r?\n/g, ' ').replace(/ +/g, ' '); } beforeEach(() => { TestBed.configureTestingModule({ declarations: [ StructDir, ViewContainerRefComp, ViewContainerRefApp, DestroyCasesComp, ConstructorDir, ConstructorApp, ConstructorAppWithQueries, ], }); }); afterEach(() => clearTranslations());
{ "end_byte": 2300, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_container_ref_spec.ts" }
angular/packages/core/test/acceptance/view_container_ref_spec.ts_2304_12478
escribe('create', () => { it('should support view queries inside embedded views created in dir constructors', () => { const fixture = TestBed.createComponent(ConstructorApp); fixture.detectChanges(); expect(fixture.componentInstance.foo).toBeInstanceOf(ElementRef); expect(fixture.componentInstance.foo.nativeElement).toEqual( fixture.debugElement.nativeElement.querySelector('span'), ); }); it('should ensure results in views created in constructors do not appear before template node results', () => { const fixture = TestBed.createComponent(ConstructorAppWithQueries); fixture.detectChanges(); expect(fixture.componentInstance.foo).toBeInstanceOf(TemplateRef); }); it('should construct proper TNode / DOM tree when embedded views are created in a directive constructor', () => { @Component({ selector: 'view-insertion-test-cmpt', template: `<div>before<ng-template constructorDir><span>|middle|</span></ng-template>after</div>`, standalone: false, }) class ViewInsertionTestCmpt {} TestBed.configureTestingModule({declarations: [ViewInsertionTestCmpt, ConstructorDir]}); const fixture = TestBed.createComponent(ViewInsertionTestCmpt); expect(fixture.nativeElement).toHaveText('before|middle|after'); }); it('should use comment node of host ng-container as insertion marker', () => { @Component({ template: 'hello', standalone: false, }) class HelloComp {} @Component({ template: ` <ng-container vcref></ng-container> `, standalone: false, }) class TestComp { @ViewChild(VCRefDirective, {static: true}) vcRefDir!: VCRefDirective; } TestBed.configureTestingModule({declarations: [TestComp, VCRefDirective, HelloComp]}); const fixture = TestBed.createComponent(TestComp); const {vcref, elementRef} = fixture.componentInstance.vcRefDir; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toMatch( /<!--(ng-container)?-->/, 'Expected only one comment node to be generated.', ); const testParent = document.createElement('div'); testParent.appendChild(elementRef.nativeElement); expect(testParent.textContent).toBe(''); expect(testParent.childNodes.length).toBe(1); expect(testParent.childNodes[0].nodeType).toBe(Node.COMMENT_NODE); // Add a test component to the view container ref to ensure that // the "ng-container" comment was used as marker for the insertion. const ref = vcref.createComponent(HelloComp); fixture.detectChanges(); expect(testParent.textContent).toBe('hello'); expect(testParent.childNodes.length).toBe(2); expect(testParent.childNodes[0].nodeType).toBe(Node.ELEMENT_NODE); expect(testParent.childNodes[0].textContent).toBe('hello'); expect(testParent.childNodes[1].nodeType).toBe(Node.COMMENT_NODE); ref.destroy(); }); it('should support attribute selectors in dynamically created components', () => { @Component({ selector: '[hello]', template: 'Hello', standalone: false, }) class HelloComp {} @Component({ template: ` <ng-container #container></ng-container> `, standalone: false, }) class TestComp { @ViewChild('container', {read: ViewContainerRef}) vcRef!: ViewContainerRef; createComponent() { return this.vcRef.createComponent(HelloComp); } } TestBed.configureTestingModule({declarations: [TestComp, HelloComp]}); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).not.toContain('Hello'); const ref = fixture.componentInstance.createComponent(); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).toContain('Hello'); ref.destroy(); }); it('should view queries in dynamically created components', () => { @Component({ selector: 'dynamic-cmpt-with-view-queries', template: `<div #foo></div>`, standalone: false, }) class DynamicCompWithViewQueries { @ViewChildren('foo') fooList!: QueryList<ElementRef>; } @Component({ selector: 'test-cmp', template: ``, standalone: false, }) class TestCmp { constructor(readonly vcRf: ViewContainerRef) {} } const fixture = TestBed.createComponent(TestCmp); const cmpRef = fixture.componentInstance.vcRf.createComponent(DynamicCompWithViewQueries); fixture.detectChanges(); expect(cmpRef.instance.fooList.length).toBe(1); expect(cmpRef.instance.fooList.first).toBeInstanceOf(ElementRef); }); describe('element namespaces', () => { function runTestWithSelectors(svgSelector: string, mathMLSelector: string) { it('should be set correctly for host elements of dynamically created components', () => { @Component({ selector: svgSelector, template: '<svg><g></g></svg>', standalone: false, }) class SvgComp {} @Component({ selector: mathMLSelector, template: '<math><matrix></matrix></math>', standalone: false, }) class MathMLComp {} @Component({ template: ` <ng-container #svg></ng-container> <ng-container #mathml></ng-container> `, standalone: false, }) class TestComp { @ViewChild('svg', {read: ViewContainerRef}) svgVCRef!: ViewContainerRef; @ViewChild('mathml', {read: ViewContainerRef}) mathMLVCRef!: ViewContainerRef; constructor() {} createDynamicComponents() { this.svgVCRef.createComponent(SvgComp); this.mathMLVCRef.createComponent(MathMLComp); } } function _document(): any { // Tell Ivy about the global document ɵsetDocument(document); return document; } TestBed.configureTestingModule({ declarations: [TestComp, SvgComp, MathMLComp], providers: [{provide: DOCUMENT, useFactory: _document, deps: []}], }); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); fixture.componentInstance.createDynamicComponents(); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('svg').namespaceURI).toEqual( 'http://www.w3.org/2000/svg', ); expect(fixture.nativeElement.querySelector('math').namespaceURI).toEqual( 'http://www.w3.org/1998/Math/MathML', ); }); } runTestWithSelectors('svg[some-attr]', 'math[some-attr]'); // Also test with selector that has element name in uppercase runTestWithSelectors('SVG[some-attr]', 'MATH[some-attr]'); }); it('should apply attributes and classes to host element based on selector', () => { @Component({ selector: '[attr-a=a].class-a:not(.class-b):not([attr-b=b]).class-c[attr-c]', template: 'Hello', standalone: false, }) class HelloComp {} @Component({ template: ` <div id="factory" attr-a="a-original" class="class-original"></div> <div id="vcr"> <ng-container #container></ng-container> </div> `, standalone: false, }) class TestComp { @ViewChild('container', {read: ViewContainerRef}) vcRef!: ViewContainerRef; constructor( public injector: EnvironmentInjector, private elementRef: ElementRef, ) {} createComponentViaVCRef() { return this.vcRef.createComponent(HelloComp); } createComponentViaFactory() { return createComponent(HelloComp, { environmentInjector: this.injector, hostElement: this.elementRef.nativeElement.querySelector('#factory'), }); } } TestBed.configureTestingModule({declarations: [TestComp, HelloComp]}); const fixture = TestBed.createComponent(TestComp); fixture.detectChanges(); const firstRef = fixture.componentInstance.createComponentViaVCRef(); const secondRef = fixture.componentInstance.createComponentViaFactory(); fixture.detectChanges(); // Verify host element for a component created via `vcRef.createComponent` method const vcrHostElement = fixture.nativeElement.querySelector('#vcr > div'); expect(vcrHostElement.classList.contains('class-a')).toBe(true); // `class-b` should not be present, since it's wrapped in `:not()` selector expect(vcrHostElement.classList.contains('class-b')).toBe(false); expect(vcrHostElement.classList.contains('class-c')).toBe(true); expect(vcrHostElement.getAttribute('attr-a')).toBe('a'); // `attr-b` should not be present, since it's wrapped in `:not()` selector expect(vcrHostElement.getAttribute('attr-b')).toBe(null); expect(vcrHostElement.getAttribute('attr-c')).toBe(''); // Verify host element for a component created using `factory.createComponent` method when // also passing element selector as an argument const factoryHostElement = fixture.nativeElement.querySelector('#factory'); // Verify original attrs and classes are still present expect(factoryHostElement.classList.contains('class-original')).toBe(true); expect(factoryHostElement.getAttribute('attr-a')).toBe('a-original'); // Make sure selector-based attrs and classes were not added to the host element expect(factoryHostElement.classList.contains('class-a')).toBe(false); expect(factoryHostElement.getAttribute('attr-c')).toBe(null); firstRef.destroy(); secondRef.destroy(); }); });
{ "end_byte": 12478, "start_byte": 2304, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_container_ref_spec.ts" }
angular/packages/core/test/acceptance/view_container_ref_spec.ts_12482_18726
scribe('insert', () => { it('should not blow up on destroy when inserting a view that is already attached', () => { const fixture = TestBed.createComponent(ViewContainerRefApp); fixture.detectChanges(); const template0 = fixture.componentInstance.vcrComp.templates.first; const viewContainerRef = fixture.componentInstance.vcrComp.vcr; const ref0 = viewContainerRef.createEmbeddedView(template0); // Insert the view again at the same index viewContainerRef.insert(ref0, 0); expect(() => { fixture.destroy(); }).not.toThrow(); expect(fixture.nativeElement.textContent).toEqual('0'); }); it('should move views if they are already attached', () => { const fixture = TestBed.createComponent(ViewContainerRefApp); fixture.detectChanges(); const templates = fixture.componentInstance.vcrComp.templates.toArray(); const viewContainerRef = fixture.componentInstance.vcrComp.vcr; const ref0 = viewContainerRef.createEmbeddedView(templates[0]); const ref1 = viewContainerRef.createEmbeddedView(templates[1]); const ref2 = viewContainerRef.createEmbeddedView(templates[2]); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('012'); // Insert the view again at a different index viewContainerRef.insert(ref0, 2); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('120'); }); it('should do nothing when a view is re-inserted / moved at the same index', () => { const fixture = TestBed.createComponent(ViewContainerRefApp); fixture.detectChanges(); const templates = fixture.componentInstance.vcrComp.templates.toArray(); const viewContainerRef = fixture.componentInstance.vcrComp.vcr; const ref0 = viewContainerRef.createEmbeddedView(templates[0]); expect(fixture.nativeElement.textContent).toEqual('0'); // insert again at the same place but without specifying any index viewContainerRef.insert(ref0); expect(fixture.nativeElement.textContent).toEqual('0'); }); it('should insert a view already inserted into another container', () => { @Component({ selector: 'test-cmpt', template: ` <ng-template #t>content</ng-template> before|<ng-template #c1></ng-template>|middle|<ng-template #c2></ng-template>|after `, standalone: false, }) class TestComponent { @ViewChild('t', {static: true}) t!: TemplateRef<{}>; @ViewChild('c1', {static: true, read: ViewContainerRef}) c1!: ViewContainerRef; @ViewChild('c2', {static: true, read: ViewContainerRef}) c2!: ViewContainerRef; } TestBed.configureTestingModule({declarations: [TestComponent]}); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); const cmpt = fixture.componentInstance; const native = fixture.nativeElement; expect(native.textContent.trim()).toEqual('before||middle||after'); // create and insert an embedded view into the c1 container const viewRef = cmpt.c1.createEmbeddedView(cmpt.t, {}); expect(native.textContent.trim()).toEqual('before|content|middle||after'); expect(cmpt.c1.indexOf(viewRef)).toBe(0); expect(cmpt.c2.indexOf(viewRef)).toBe(-1); // move the existing embedded view into the c2 container cmpt.c2.insert(viewRef); expect(native.textContent.trim()).toEqual('before||middle|content|after'); expect(cmpt.c1.indexOf(viewRef)).toBe(-1); expect(cmpt.c2.indexOf(viewRef)).toBe(0); }); it('should add embedded views at the right position in the DOM tree (ng-template next to other ng-template)', () => { @Component({ template: `before|<ng-template #a>A</ng-template><ng-template #b>B</ng-template>|after`, standalone: false, }) class TestCmp { @ViewChild('a', {static: true}) ta!: TemplateRef<{}>; @ViewChild('b', {static: true}) tb!: TemplateRef<{}>; @ViewChild('a', {static: true, read: ViewContainerRef}) ca!: ViewContainerRef; @ViewChild('b', {static: true, read: ViewContainerRef}) cb!: ViewContainerRef; } const fixture = TestBed.createComponent(TestCmp); const testCmpInstance = fixture.componentInstance; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('before||after'); testCmpInstance.cb.createEmbeddedView(testCmpInstance.tb); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('before|B|after'); testCmpInstance.ca.createEmbeddedView(testCmpInstance.ta); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('before|AB|after'); }); }); describe('move', () => { it('should insert detached views in move()', () => { const fixture = TestBed.createComponent(ViewContainerRefApp); fixture.detectChanges(); const templates = fixture.componentInstance.vcrComp.templates.toArray(); const viewContainerRef = fixture.componentInstance.vcrComp.vcr; const ref0 = viewContainerRef.createEmbeddedView(templates[0]); const ref1 = viewContainerRef.createEmbeddedView(templates[1]); const ref2 = viewContainerRef.createEmbeddedView(templates[2]); viewContainerRef.detach(0); viewContainerRef.move(ref0, 0); expect(fixture.nativeElement.textContent).toEqual('012'); }); }); it('should not throw when calling remove() on an empty container', () => { const fixture = TestBed.createComponent(ViewContainerRefApp); fixture.detectChanges(); const viewContainerRef = fixture.componentInstance.vcrComp.vcr; expect(viewContainerRef.length).toBe(0); expect(() => viewContainerRef.remove()).not.toThrow(); }); it('should not throw when calling detach() on an empty container', () => { const fixture = TestBed.createComponent(ViewContainerRefApp); fixture.detectChanges(); const viewContainerRef = fixture.componentInstance.vcrComp.vcr; expect(viewContainerRef.length).toBe(0); expect(() => viewContainerRef.detach()).not.toThrow(); });
{ "end_byte": 18726, "start_byte": 12482, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_container_ref_spec.ts" }
angular/packages/core/test/acceptance/view_container_ref_spec.ts_18730_26052
scribe('destroy should clean the DOM in all cases:', () => { function executeTest(template: string) { TestBed.overrideTemplate(DestroyCasesComp, template).configureTestingModule({ schemas: [NO_ERRORS_SCHEMA], }); const fixture = TestBed.createComponent(DestroyCasesComp); fixture.detectChanges(); const initial = fixture.nativeElement.innerHTML; const structDirs = fixture.componentInstance.structDirs.toArray(); structDirs.forEach((structDir) => structDir.create()); fixture.detectChanges(); expect(fixture.nativeElement).toHaveText('Foo'); structDirs.forEach((structDir) => structDir.destroy()); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual(initial); } it('when nested ng-container', () => { executeTest(` <ng-template structDir> <before></before> <ng-container> <before></before> <ng-container> <inside>Foo</inside> </ng-container> <after></after> </ng-container> <after></after> </ng-template>`); }); it('when ViewContainerRef is on a ng-container', () => { executeTest(` <ng-template #foo> <span>Foo</span> </ng-template> <ng-template structDir> <before></before> <ng-container [ngTemplateOutlet]="foo"> <inside></inside> </ng-container> <after></after> </ng-template>`); }); it('when ViewContainerRef is on an element', () => { executeTest(` <ng-template #foo> <span>Foo</span> </ng-template> <ng-template structDir> <before></before> <div [ngTemplateOutlet]="foo"> <inside></inside> </div> <after></after> </ng-template>`); }); it('when ViewContainerRef is on a ng-template', () => { executeTest(` <ng-template #foo> <span>Foo</span> </ng-template> <ng-template structDir> <before></before> <ng-template [ngTemplateOutlet]="foo"></ng-template> <after></after> </ng-template>`); }); it('when ViewContainerRef is on an element inside a ng-container', () => { executeTest(` <ng-template #foo> <span>Foo</span> </ng-template> <ng-template structDir> <before></before> <ng-container> <before></before> <div [ngTemplateOutlet]="foo"> <inside></inside> </div> <after></after> </ng-container> <after></after> </ng-template>`); }); it('when ViewContainerRef is on an element inside a ng-container with i18n', () => { loadTranslations({ [computeMsgId('Bar')]: 'o', [computeMsgId( '{$START_TAG_BEFORE}{$CLOSE_TAG_BEFORE}{$START_TAG_DIV}{$START_TAG_INSIDE}{$CLOSE_TAG_INSIDE}{$CLOSE_TAG_DIV}{$START_TAG_AFTER}{$CLOSE_TAG_AFTER}', )]: 'F{$START_TAG_DIV}{$CLOSE_TAG_DIV}o', }); executeTest(` <ng-template #foo> <span i18n>Bar</span> </ng-template> <ng-template structDir> <before></before> <ng-container i18n> <before></before> <div [ngTemplateOutlet]="foo"> <inside></inside> </div> <after></after> </ng-container> <after></after> </ng-template>`); }); it('when ViewContainerRef is on an element, and i18n is on the parent ViewContainerRef', () => { loadTranslations({ [computeMsgId( '{$START_TAG_BEFORE}{$CLOSE_TAG_BEFORE}{$START_TAG_DIV}{$START_TAG_IN}{$CLOSE_TAG_IN}{$CLOSE_TAG_DIV}{$START_TAG_AFTER}{$CLOSE_TAG_AFTER}', )]: '{$START_TAG_DIV}{$CLOSE_TAG_DIV}{$START_TAG_BEFORE}oo{$CLOSE_TAG_BEFORE}', [computeMsgId('{VAR_SELECT, select, other {|{INTERPOLATION}|}}')]: '{VAR_SELECT, select, other {|{INTERPOLATION}|}}', }); executeTest(` <ng-template #foo> <span>F</span> </ng-template> <ng-template structDir i18n> <before></before> <div [ngTemplateOutlet]="foo"> <in></in> </div> <after></after> </ng-template>`); }); }); describe('length', () => { it('should return the number of embedded views', () => { TestBed.configureTestingModule({declarations: [EmbeddedViewInsertionComp, VCRefDirective]}); const fixture = TestBed.createComponent(EmbeddedViewInsertionComp); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); expect(vcRefDir.vcref.length).toEqual(0); vcRefDir.createView('A'); vcRefDir.createView('B'); vcRefDir.createView('C'); fixture.detectChanges(); expect(vcRefDir.vcref.length).toEqual(3); vcRefDir.vcref.detach(1); fixture.detectChanges(); expect(vcRefDir.vcref.length).toEqual(2); vcRefDir.vcref.clear(); fixture.detectChanges(); expect(vcRefDir.vcref.length).toEqual(0); }); }); describe('get and indexOf', () => { beforeEach(() => { TestBed.configureTestingModule({declarations: [EmbeddedViewInsertionComp, VCRefDirective]}); }); it('should retrieve a ViewRef from its index, and vice versa', () => { const fixture = TestBed.createComponent(EmbeddedViewInsertionComp); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); vcRefDir.createView('A'); vcRefDir.createView('B'); vcRefDir.createView('C'); fixture.detectChanges(); let viewRef = vcRefDir.vcref.get(0); expect(vcRefDir.vcref.indexOf(viewRef!)).toEqual(0); viewRef = vcRefDir.vcref.get(1); expect(vcRefDir.vcref.indexOf(viewRef!)).toEqual(1); viewRef = vcRefDir.vcref.get(2); expect(vcRefDir.vcref.indexOf(viewRef!)).toEqual(2); }); it('should handle out of bounds cases', () => { const fixture = TestBed.createComponent(EmbeddedViewInsertionComp); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); vcRefDir.createView('A'); fixture.detectChanges(); expect(vcRefDir.vcref.get(-1)).toBeNull(); expect(vcRefDir.vcref.get(42)).toBeNull(); const viewRef = vcRefDir.vcref.get(0); vcRefDir.vcref.remove(0); expect(vcRefDir.vcref.indexOf(viewRef!)).toEqual(-1); }); it('should return -1 as indexOf when no views were inserted', () => { const fixture = TestBed.createComponent(ViewContainerRefComp); fixture.detectChanges(); const cmpt = fixture.componentInstance; const viewRef = cmpt.templates.first.createEmbeddedView({}); // ViewContainerRef is empty and we've got a reference to a view that was not attached // anywhere expect(cmpt.vcr.indexOf(viewRef)).toBe(-1); cmpt.vcr.insert(viewRef); expect(cmpt.vcr.indexOf(viewRef)).toBe(0); cmpt.vcr.remove(0); expect(cmpt.vcr.indexOf(viewRef)).toBe(-1); }); });
{ "end_byte": 26052, "start_byte": 18730, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_container_ref_spec.ts" }
angular/packages/core/test/acceptance/view_container_ref_spec.ts_26056_33590
scribe('move', () => { it('should move embedded views and associated DOM nodes without recreating them', () => { TestBed.configureTestingModule({declarations: [EmbeddedViewInsertionComp, VCRefDirective]}); const fixture = TestBed.createComponent(EmbeddedViewInsertionComp); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); vcRefDir.createView('A'); vcRefDir.createView('B'); vcRefDir.createView('C'); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>ABC'); // The DOM is manually modified here to ensure that the text node is actually moved fixture.nativeElement.childNodes[2].nodeValue = '**A**'; expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>**A**BC'); let viewRef = vcRefDir.vcref.get(0); vcRefDir.vcref.move(viewRef!, 2); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>BC**A**'); vcRefDir.vcref.move(viewRef!, 0); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>**A**BC'); vcRefDir.vcref.move(viewRef!, 1); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>B**A**C'); expect(() => vcRefDir.vcref.move(viewRef!, -1)).toThrow(); expect(() => vcRefDir.vcref.move(viewRef!, 42)).toThrow(); }); }); describe('getters for the anchor node', () => { it('should work on templates', () => { @Component({ template: ` <ng-template vcref let-name>{{name}}</ng-template> <footer></footer> `, standalone: false, }) class TestComponent { @ViewChild(VCRefDirective, {static: true}) vcRefDir!: VCRefDirective; } TestBed.configureTestingModule({declarations: [VCRefDirective, TestComponent]}); const fixture = TestBed.createComponent(TestComponent); const {vcRefDir} = fixture.componentInstance; fixture.detectChanges(); expect(vcRefDir.vcref.element.nativeElement.nodeType).toBe(Node.COMMENT_NODE); // In Ivy, the comment for the view container ref has text that implies // that the comment is a placeholder for a container. expect(vcRefDir.vcref.element.nativeElement.textContent).toEqual('container'); expect(vcRefDir.vcref.injector.get(ElementRef).nativeElement.textContent).toEqual( 'container', ); expect(getElementHtml(vcRefDir.vcref.parentInjector.get(ElementRef).nativeElement)).toBe( '<footer></footer>', ); }); it('should work on elements', () => { @Component({ template: ` <header vcref></header> <footer></footer> `, standalone: false, }) class TestComponent { @ViewChild(VCRefDirective, {static: true}) vcRefDir!: VCRefDirective; } TestBed.configureTestingModule({declarations: [VCRefDirective, TestComponent]}); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); const vcref = fixture.componentInstance.vcRefDir.vcref; expect(vcref.element.nativeElement.tagName.toLowerCase()).toEqual('header'); expect(vcref.injector.get(ElementRef).nativeElement.tagName.toLowerCase()).toEqual('header'); }); it('should work on components', () => { @Component({ selector: 'header-cmp', template: ``, standalone: false, }) class HeaderCmp {} @Component({ template: ` <header-cmp vcref></header-cmp> <footer></footer> `, standalone: false, }) class TestComponent { @ViewChild(VCRefDirective, {static: true}) vcRefDir!: VCRefDirective; } TestBed.configureTestingModule({declarations: [HeaderCmp, VCRefDirective, TestComponent]}); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); const vcref = fixture.componentInstance.vcRefDir.vcref; expect(vcref.element.nativeElement.tagName.toLowerCase()).toEqual('header-cmp'); expect(vcref.injector.get(ElementRef).nativeElement.tagName.toLowerCase()).toEqual( 'header-cmp', ); }); }); describe('detach', () => { beforeEach(() => { TestBed.configureTestingModule({declarations: [EmbeddedViewInsertionComp, VCRefDirective]}); // Tests depend on perf counters. In order to have clean perf counters at the beginning of a // test, we reset those here. ngDevModeResetPerfCounters(); }); it('should detach the right embedded view when an index is specified', () => { const fixture = TestBed.createComponent(EmbeddedViewInsertionComp); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); const viewA = vcRefDir.createView('A'); vcRefDir.createView('B'); vcRefDir.createView('C'); const viewD = vcRefDir.createView('D'); vcRefDir.createView('E'); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>ABCDE'); vcRefDir.vcref.detach(3); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>ABCE'); expect(viewD.destroyed).toBeFalsy(); vcRefDir.vcref.detach(0); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>BCE'); expect(viewA.destroyed).toBeFalsy(); expect(() => vcRefDir.vcref.detach(-1)).toThrow(); expect(() => vcRefDir.vcref.detach(42)).toThrow(); expect(ngDevMode!.rendererDestroyNode).toBe(0); }); it('should detach the last embedded view when no index is specified', () => { const fixture = TestBed.createComponent(EmbeddedViewInsertionComp); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); vcRefDir.createView('A'); vcRefDir.createView('B'); vcRefDir.createView('C'); vcRefDir.createView('D'); const viewE = vcRefDir.createView('E'); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>ABCDE'); vcRefDir.vcref.detach(); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>ABCD'); expect(viewE.destroyed).toBeFalsy(); expect(ngDevMode!.rendererDestroyNode).toBe(0); }); it('should not throw when destroying a detached component view', () => { @Component({ selector: 'dynamic-cmp', standalone: false, }) class DynamicCmp {} @Component({ selector: 'test-cmp', standalone: false, }) class TestCmp { constructor(public vcRef: ViewContainerRef) {} } const fixture = TestBed.createComponent(TestCmp); fixture.detectChanges(); const vcRef = fixture.componentInstance.vcRef; const cmpRef = vcRef.createComponent(DynamicCmp); fixture.detectChanges(); vcRef.detach(vcRef.indexOf(cmpRef.hostView)); expect(() => { cmpRef.destroy(); }).not.toThrow(); }); });
{ "end_byte": 33590, "start_byte": 26056, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_container_ref_spec.ts" }
angular/packages/core/test/acceptance/view_container_ref_spec.ts_33594_38746
scribe('remove', () => { beforeEach(() => { TestBed.configureTestingModule({declarations: [EmbeddedViewInsertionComp, VCRefDirective]}); const _origRendererFactory = TestBed.inject(RendererFactory2); const _origCreateRenderer = _origRendererFactory.createRenderer; _origRendererFactory.createRenderer = function (element: any, type: RendererType2 | null) { const renderer = _origCreateRenderer.call(_origRendererFactory, element, type); renderer.destroyNode = () => {}; return renderer; }; // Tests depend on perf counters. In order to have clean perf counters at the beginning of a // test, we reset those here. ngDevModeResetPerfCounters(); }); it('should remove the right embedded view when an index is specified', () => { const fixture = TestBed.createComponent(EmbeddedViewInsertionComp); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); const viewA = vcRefDir.createView('A'); vcRefDir.createView('B'); vcRefDir.createView('C'); const viewD = vcRefDir.createView('D'); vcRefDir.createView('E'); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>ABCDE'); vcRefDir.vcref.remove(3); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>ABCE'); expect(viewD.destroyed).toBeTruthy(); vcRefDir.vcref.remove(0); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>BCE'); expect(viewA.destroyed).toBeTruthy(); expect(() => vcRefDir.vcref.remove(-1)).toThrow(); expect(() => vcRefDir.vcref.remove(42)).toThrow(); expect(ngDevMode!.rendererDestroyNode).toBe(2); }); it('should remove the last embedded view when no index is specified', () => { const fixture = TestBed.createComponent(EmbeddedViewInsertionComp); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); vcRefDir.createView('A'); vcRefDir.createView('B'); vcRefDir.createView('C'); vcRefDir.createView('D'); const viewE = vcRefDir.createView('E'); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>ABCDE'); vcRefDir.vcref.remove(); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>ABCD'); expect(viewE.destroyed).toBeTruthy(); expect(ngDevMode!.rendererDestroyNode).toBe(1); }); it('should throw when trying to insert a removed or destroyed view', () => { const fixture = TestBed.createComponent(EmbeddedViewInsertionComp); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); const viewA = vcRefDir.createView('A'); const viewB = vcRefDir.createView('B'); fixture.detectChanges(); vcRefDir.vcref.remove(); fixture.detectChanges(); expect(() => vcRefDir.vcref.insert(viewB)).toThrow(); viewA.destroy(); fixture.detectChanges(); expect(() => vcRefDir.vcref.insert(viewA)).toThrow(); }); }); describe('dependant views', () => { it('should not throw when view removes another view upon removal', () => { @Component({ template: ` <div *ngIf="visible" [template]="parent">I host a template</div> <ng-template #parent> <div [template]="child">I host a child template</div> </ng-template> <ng-template #child> I am child template </ng-template> `, standalone: false, }) class AppComponent { visible = true; constructor(private readonly vcr: ViewContainerRef) {} add<C>(template: TemplateRef<C>): EmbeddedViewRef<C> { return this.vcr.createEmbeddedView(template); } remove<C>(viewRef: EmbeddedViewRef<C>) { this.vcr.remove(this.vcr.indexOf(viewRef)); } } @Directive({ selector: '[template]', standalone: false, }) class TemplateDirective<C> implements OnInit, OnDestroy { @Input() template!: TemplateRef<C>; ref!: EmbeddedViewRef<C>; constructor(private readonly host: AppComponent) {} ngOnInit() { this.ref = this.host.add(this.template); this.ref.detectChanges(); } ngOnDestroy() { this.host.remove(this.ref); } } TestBed.configureTestingModule({ imports: [CommonModule], declarations: [AppComponent, TemplateDirective], }); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); fixture.componentRef.instance.visible = false; fixture.detectChanges(); }); });
{ "end_byte": 38746, "start_byte": 33594, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_container_ref_spec.ts" }
angular/packages/core/test/acceptance/view_container_ref_spec.ts_38750_45732
scribe('createEmbeddedView (incl. insert)', () => { it('should work on elements', () => { @Component({ template: ` <ng-template #tplRef let-name>{{name}}</ng-template> <header vcref [tplRef]="tplRef"></header> <footer></footer> `, standalone: false, }) class TestComponent {} TestBed.configureTestingModule({declarations: [TestComponent, VCRefDirective]}); const fixture = TestBed.createComponent(TestComponent); const vcRef = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<header vcref=""></header><footer></footer>', ); vcRef.createView('A'); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<header vcref=""></header>A<footer></footer>', ); vcRef.createView('B'); vcRef.createView('C'); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<header vcref=""></header>ABC<footer></footer>', ); vcRef.createView('Y', 0); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<header vcref=""></header>YABC<footer></footer>', ); expect(() => vcRef.createView('Z', -1)).toThrow(); expect(() => vcRef.createView('Z', 5)).toThrow(); }); it('should work on components', () => { @Component({ selector: 'header-cmp', template: ``, standalone: false, }) class HeaderComponent {} @Component({ template: ` <ng-template #tplRef let-name>{{name}}</ng-template> <header-cmp vcref [tplRef]="tplRef"></header-cmp> <footer></footer> `, standalone: false, }) class TestComponent {} TestBed.configureTestingModule({ declarations: [TestComponent, HeaderComponent, VCRefDirective], }); const fixture = TestBed.createComponent(TestComponent); const vcRef = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<header-cmp vcref=""></header-cmp><footer></footer>', ); vcRef.createView('A'); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<header-cmp vcref=""></header-cmp>A<footer></footer>', ); vcRef.createView('B'); vcRef.createView('C'); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<header-cmp vcref=""></header-cmp>ABC<footer></footer>', ); vcRef.createView('Y', 0); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<header-cmp vcref=""></header-cmp>YABC<footer></footer>', ); expect(() => vcRef.createView('Z', -1)).toThrow(); expect(() => vcRef.createView('Z', 5)).toThrow(); }); it('should work with multiple instances of view container refs', () => { @Component({ template: ` <ng-template #tplRef let-name>{{name}}</ng-template> <div vcref [tplRef]="tplRef"></div> <div vcref [tplRef]="tplRef"></div> `, standalone: false, }) class TestComponent {} TestBed.configureTestingModule({declarations: [TestComponent, VCRefDirective]}); const fixture = TestBed.createComponent(TestComponent); const vcRefs = fixture.debugElement .queryAll(By.directive(VCRefDirective)) .map((debugEl) => debugEl.injector.get(VCRefDirective)); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<div vcref=""></div><div vcref=""></div>', ); vcRefs[0].createView('A'); vcRefs[1].createView('B'); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<div vcref=""></div>A<div vcref=""></div>B', ); }); it('should work on templates', () => { @Component({ template: ` <ng-template vcref #tplRef [tplRef]="tplRef" let-name>{{name}}</ng-template> <footer></footer> `, standalone: false, }) class TestComponent { @ViewChild(VCRefDirective, {static: true}) vcRef!: VCRefDirective; } TestBed.configureTestingModule({declarations: [TestComponent, VCRefDirective]}); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); const {vcRef} = fixture.componentInstance; expect(getElementHtml(fixture.nativeElement)).toEqual('<footer></footer>'); vcRef.createView('A'); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('A<footer></footer>'); vcRef.createView('B'); vcRef.createView('C'); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('ABC<footer></footer>'); vcRef.createView('Y', 0); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('YABC<footer></footer>'); expect(() => vcRef!.createView('Z', -1)).toThrow(); expect(() => vcRef!.createView('Z', 5)).toThrow(); }); it('should apply directives and pipes of the host view to the TemplateRef', () => { @Component({ selector: 'child', template: `{{name}}`, standalone: false, }) class Child { @Input() name: string | undefined; } @Pipe({ name: 'starPipe', standalone: false, }) class StarPipe implements PipeTransform { transform(value: any) { return `**${value}**`; } } @Component({ template: ` <ng-template #foo> <child [name]="'C' | starPipe"></child> </ng-template> <child vcref [tplRef]="foo" [name]="'A' | starPipe"></child> <child [name]="'B' | starPipe"></child> `, standalone: false, }) class SomeComponent {} TestBed.configureTestingModule({ declarations: [Child, StarPipe, SomeComponent, VCRefDirective], }); const fixture = TestBed.createComponent(SomeComponent); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef!); vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef!); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child vcref="">**A**</child><child>**C**</child><child>**C**</child><child>**B**</child>', ); }); });
{ "end_byte": 45732, "start_byte": 38750, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_container_ref_spec.ts" }
angular/packages/core/test/acceptance/view_container_ref_spec.ts_45736_54364
scribe('createComponent', () => { let templateExecutionCounter = 0; beforeEach(() => (templateExecutionCounter = 0)); it('should work without Injector and NgModuleRef', () => { @Component({ selector: 'embedded-cmp', template: `foo`, standalone: false, }) class EmbeddedComponent implements DoCheck, OnInit { ngOnInit() { templateExecutionCounter++; } ngDoCheck() { templateExecutionCounter++; } } TestBed.configureTestingModule({ declarations: [EmbeddedViewInsertionComp, VCRefDirective, EmbeddedComponent], }); const fixture = TestBed.createComponent(EmbeddedViewInsertionComp); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>'); expect(templateExecutionCounter).toEqual(0); const componentRef = vcRefDir.vcref.createComponent(EmbeddedComponent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<p vcref=""></p><embedded-cmp>foo</embedded-cmp>', ); expect(templateExecutionCounter).toEqual(2); vcRefDir.vcref.detach(0); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>'); expect(templateExecutionCounter).toEqual(2); vcRefDir.vcref.insert(componentRef.hostView); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<p vcref=""></p><embedded-cmp>foo</embedded-cmp>', ); expect(templateExecutionCounter).toEqual(3); }); it('should work with NgModuleRef and Injector', () => { @Component({ selector: 'embedded-cmp', template: `foo`, standalone: false, }) class EmbeddedComponent implements DoCheck, OnInit { constructor(public s: String) {} ngOnInit() { templateExecutionCounter++; } ngDoCheck() { templateExecutionCounter++; } } TestBed.configureTestingModule({ declarations: [EmbeddedViewInsertionComp, VCRefDirective, EmbeddedComponent], }); @NgModule({ providers: [ {provide: String, useValue: 'root_module'}, // We need to provide the following tokens because otherwise view engine // will throw when creating a component factory in debug mode. {provide: Sanitizer, useValue: TestBed.inject(DomSanitizer)}, {provide: ErrorHandler, useValue: TestBed.inject(ErrorHandler)}, {provide: RendererFactory2, useValue: TestBed.inject(RendererFactory2)}, ], }) class MyAppModule {} @NgModule({providers: [{provide: String, useValue: 'some_module'}]}) class SomeModule {} // Compile test modules in order to be able to pass the NgModuleRef or the // module injector to the ViewContainerRef create component method. const compiler = TestBed.inject(Compiler); const appModuleFactory = compiler.compileModuleSync(MyAppModule); const someModuleFactory = compiler.compileModuleSync(SomeModule); const appModuleRef = appModuleFactory.create(null); const someModuleRef = someModuleFactory.create(null); const fixture = TestBed.createComponent(EmbeddedViewInsertionComp); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>'); expect(templateExecutionCounter).toEqual(0); let componentRef = vcRefDir.vcref.createComponent(EmbeddedComponent, { index: 0, injector: someModuleRef.injector, }); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<p vcref=""></p><embedded-cmp>foo</embedded-cmp>', ); expect(templateExecutionCounter).toEqual(2); expect(componentRef.instance.s).toEqual('some_module'); componentRef = vcRefDir.vcref.createComponent(EmbeddedComponent, { index: 0, ngModuleRef: appModuleRef, }); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<p vcref=""></p><embedded-cmp>foo</embedded-cmp><embedded-cmp>foo</embedded-cmp>', ); expect(componentRef.instance.s).toEqual('root_module'); expect(templateExecutionCounter).toEqual(5); }); it('should support projectable nodes', () => { TestBed.configureTestingModule({ declarations: [EmbeddedViewInsertionComp, VCRefDirective, EmbeddedComponentWithNgContent], }); const fixture = TestBed.createComponent(EmbeddedViewInsertionComp); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>'); const myNode = document.createElement('div'); const myText = document.createTextNode('bar'); const myText2 = document.createTextNode('baz'); myNode.appendChild(myText); myNode.appendChild(myText2); vcRefDir.vcref.createComponent(EmbeddedComponentWithNgContent, { index: 0, projectableNodes: [[myNode]], }); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<p vcref=""></p><embedded-cmp-with-ngcontent><div>barbaz</div><hr></embedded-cmp-with-ngcontent>', ); }); it('should support reprojection of projectable nodes', () => { @Component({ selector: 'reprojector', template: `<embedded-cmp-with-ngcontent><ng-content></ng-content></embedded-cmp-with-ngcontent>`, standalone: false, }) class Reprojector {} TestBed.configureTestingModule({ declarations: [ EmbeddedViewInsertionComp, VCRefDirective, Reprojector, EmbeddedComponentWithNgContent, ], }); const fixture = TestBed.createComponent(EmbeddedViewInsertionComp); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>'); const myNode = document.createElement('div'); const myText = document.createTextNode('bar'); const myText2 = document.createTextNode('baz'); myNode.appendChild(myText); myNode.appendChild(myText2); vcRefDir.vcref.createComponent(Reprojector, {index: 0, projectableNodes: [[myNode]]}); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<p vcref=""></p><reprojector><embedded-cmp-with-ngcontent><hr><div>barbaz</div></embedded-cmp-with-ngcontent></reprojector>', ); }); it('should support many projectable nodes with many slots', () => { TestBed.configureTestingModule({ declarations: [EmbeddedViewInsertionComp, VCRefDirective, EmbeddedComponentWithNgContent], }); const fixture = TestBed.createComponent(EmbeddedViewInsertionComp); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual('<p vcref=""></p>'); vcRefDir.vcref.createComponent(EmbeddedComponentWithNgContent, { index: 0, projectableNodes: [ [document.createTextNode('1'), document.createTextNode('2')], [document.createTextNode('3'), document.createTextNode('4')], ], }); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<p vcref=""></p><embedded-cmp-with-ngcontent>12<hr>34</embedded-cmp-with-ngcontent>', ); }); it('should not throw when calling destroy() multiple times for a ComponentRef', () => { @Component({ template: '', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.componentRef.destroy(); expect(() => fixture.componentRef.destroy()).not.toThrow(); });
{ "end_byte": 54364, "start_byte": 45736, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_container_ref_spec.ts" }
angular/packages/core/test/acceptance/view_container_ref_spec.ts_54370_63102
('should create the root node in the correct namespace when previous node is SVG', () => { @Component({ template: ` <div>Some random content</div> <!-- Note that it's important for the test that the <svg> element is last. --> <svg></svg> `, standalone: false, }) class TestComp { constructor(public viewContainerRef: ViewContainerRef) {} } @Component({ selector: 'dynamic-comp', template: '', standalone: false, }) class DynamicComponent {} TestBed.configureTestingModule({declarations: [DynamicComponent]}); const fixture = TestBed.createComponent(TestComp); // Note: it's important that we **don't** call `fixture.detectChanges` between here and // the component being created, because running change detection will reset Ivy's // namespace state which will make the test pass. const componentRef = fixture.componentInstance.viewContainerRef.createComponent(DynamicComponent); const element = componentRef.location.nativeElement; expect((element.namespaceURI || '').toLowerCase()).not.toContain('svg'); componentRef.destroy(); }); it('should be compatible with componentRef generated via TestBed.createComponent in component factory', () => { @Component({ selector: 'child', template: `Child Component`, standalone: false, }) class Child {} @Component({ selector: 'comp', template: '<ng-template #ref></ng-template>', standalone: false, }) class Comp { @ViewChild('ref', {read: ViewContainerRef, static: true}) viewContainerRef!: ViewContainerRef; ngOnInit() { const makeComponentFactory = (componentType: any) => ({ create: () => TestBed.createComponent(componentType).componentRef, }); this.viewContainerRef.createComponent(makeComponentFactory(Child) as any); } } TestBed.configureTestingModule({declarations: [Comp, Child]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).toContain('Child Component'); }); it('should return ComponentRef with ChangeDetectorRef attached to root view', () => { @Component({ selector: 'dynamic-cmp', template: ``, standalone: false, }) class DynamicCmp { doCheckCount = 0; ngDoCheck() { this.doCheckCount++; } } @Component({ template: ``, standalone: false, }) class TestCmp { constructor(public viewContainerRef: ViewContainerRef) {} } const fixture = TestBed.createComponent(TestCmp); const testCmpInstance = fixture.componentInstance; const dynamicCmpRef = testCmpInstance.viewContainerRef.createComponent(DynamicCmp); // change detection didn't run at all expect(dynamicCmpRef.instance.doCheckCount).toBe(0); // running change detection on the dynamicCmpRef level dynamicCmpRef.changeDetectorRef.detectChanges(); expect(dynamicCmpRef.instance.doCheckCount).toBe(1); // running change detection on the TestBed fixture level fixture.changeDetectorRef.detectChanges(); expect(dynamicCmpRef.instance.doCheckCount).toBe(2); // The injector should retrieve the change detector ref for DynamicComp. As such, // the doCheck hook for DynamicComp should NOT run upon ref.detectChanges(). const changeDetector = dynamicCmpRef.injector.get(ChangeDetectorRef); changeDetector.detectChanges(); expect(dynamicCmpRef.instance.doCheckCount).toBe(2); }); describe('createComponent using Type', () => { const TOKEN_A = new InjectionToken('A'); const TOKEN_B = new InjectionToken('B'); @Component({ selector: 'child-a', template: `[Child Component A]`, standalone: false, }) class ChildA {} @Component({ selector: 'child-b', template: ` [Child Component B] <ng-content></ng-content> {{ tokenA }} {{ tokenB }} `, standalone: false, }) class ChildB { constructor( private injector: Injector, public renderer: Renderer2, ) {} get tokenA() { return this.injector.get(TOKEN_A); } get tokenB() { return this.injector.get(TOKEN_B); } } @Component({ selector: 'app', template: '', providers: [{provide: TOKEN_B, useValue: '[TokenB - Value]'}], standalone: false, }) class App { constructor( public viewContainerRef: ViewContainerRef, public ngModuleRef: NgModuleRef<unknown>, public injector: Injector, ) {} } @NgModule({ declarations: [App, ChildA, ChildB], providers: [{provide: TOKEN_A, useValue: '[TokenA - Value]'}], }) class AppModule {} let fixture!: ComponentFixture<App>; beforeEach(() => { TestBed.configureTestingModule({imports: [AppModule]}); fixture = TestBed.createComponent(App); fixture.detectChanges(); }); it('should be able to create a component when Type is provided', () => { fixture.componentInstance.viewContainerRef.createComponent(ChildA); expect(fixture.nativeElement.parentNode.textContent).toContain('[Child Component A]'); }); it('should maintain connection with module injector when custom injector is provided', () => { const comp = fixture.componentInstance; const environmentInjector = createEnvironmentInjector( [{provide: TOKEN_B, useValue: '[TokenB - CustomValue]'}], TestBed.inject(EnvironmentInjector), ); // Use factory-less way of creating a component. comp.viewContainerRef.createComponent(ChildB, {injector: environmentInjector}); fixture.detectChanges(); // Custom injector provides only `TOKEN_B`, // so `TOKEN_A` should be retrieved from the module injector. expect(getElementText(fixture.nativeElement.parentNode)).toContain( '[TokenA - Value] [TokenB - CustomValue]', ); // Use factory-based API to compare the output with the factory-less one. const factoryBasedChildB = createComponent(ChildB, {environmentInjector}); fixture.detectChanges(); // Custom injector provides only `TOKEN_B`, // so `TOKEN_A` should be retrieved from the module injector expect(getElementText(fixture.nativeElement.parentNode)).toContain( '[TokenA - Value] [TokenB - CustomValue]', ); }); it('should throw if class without @Component decorator is used as Component type', () => { class MyClassWithoutComponentDecorator {} const createComponent = () => { fixture.componentInstance.viewContainerRef.createComponent( MyClassWithoutComponentDecorator, ); }; expect(createComponent).toThrowError( /Provided Component class doesn't contain Component definition./, ); }); describe('`options` argument handling', () => { it('should work correctly when an empty object is provided', () => { fixture.componentInstance.viewContainerRef.createComponent(ChildA, {}); expect(fixture.nativeElement.parentNode.textContent).toContain('[Child Component A]'); }); it('should take provided `options` arguments into account', () => { const {viewContainerRef, ngModuleRef, injector} = fixture.componentInstance; viewContainerRef.createComponent(ChildA); const projectableNode = document.createElement('div'); const textNode = document.createTextNode('[Projectable Node]'); projectableNode.appendChild(textNode); const projectableNodes = [[projectableNode]]; // Insert ChildB in front of ChildA (since index = 0) viewContainerRef.createComponent(ChildB, { index: 0, injector, ngModuleRef, projectableNodes, }); fixture.detectChanges(); expect(getElementText(fixture.nativeElement.parentNode)).toContain( '[Child Component B] ' + '[Projectable Node] ' + '[TokenA - Value] ' + '[TokenB - Value] ' + '[Child Component A]', ); }); }); }); });
{ "end_byte": 63102, "start_byte": 54370, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_container_ref_spec.ts" }
angular/packages/core/test/acceptance/view_container_ref_spec.ts_63106_71903
scribe('insertion points and declaration points', () => { @Directive({ selector: '[tplDir]', standalone: false, }) class InsertionDir { @Input() set tplDir(tpl: TemplateRef<any> | null) { tpl ? this.vcr.createEmbeddedView(tpl) : this.vcr.clear(); } constructor(public vcr: ViewContainerRef) {} } // see running stackblitz example: https://stackblitz.com/edit/angular-w3myy6 it('should work with a template declared in a different component view from insertion', () => { @Component({ selector: 'child', template: `<div [tplDir]="tpl">{{name}}</div>`, standalone: false, }) class Child { @Input() tpl: TemplateRef<any> | null = null; name = 'Child'; } @Component({ template: ` <ng-template #foo> <div>{{name}}</div> </ng-template> <child [tpl]="foo"></child> `, standalone: false, }) class Parent { name = 'Parent'; } TestBed.configureTestingModule({declarations: [Child, Parent, InsertionDir]}); const fixture = TestBed.createComponent(Parent); const child = fixture.debugElement.query(By.directive(Child)).componentInstance; fixture.detectChanges(); // Context should be inherited from the declaration point, not the // insertion point, so the template should read 'Parent'. expect(getElementHtml(fixture.nativeElement)).toEqual( `<child><div>Child</div><div>Parent</div></child>`, ); child.tpl = null; fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual(`<child><div>Child</div></child>`); }); // see running stackblitz example: https://stackblitz.com/edit/angular-3vplec it('should work with nested for loops with different declaration / insertion points', () => { @Component({ selector: 'loop-comp', template: ` <ng-template ngFor [ngForOf]="rows" [ngForTemplate]="tpl"> </ng-template> `, standalone: false, }) class LoopComp { @Input() tpl!: TemplateRef<any>; @Input() rows!: any[]; name = 'Loop'; } @Component({ template: ` <ng-template #rowTemplate let-row> <ng-template #cellTemplate let-cell> <div>{{cell}} - {{row.value}} - {{name}}</div> </ng-template> <loop-comp [tpl]="cellTemplate" [rows]="row.data"></loop-comp> </ng-template> <loop-comp [tpl]="rowTemplate" [rows]="rows"></loop-comp> `, standalone: false, }) class Parent { name = 'Parent'; rows = [ {data: ['1', '2'], value: 'one'}, {data: ['3', '4'], value: 'two'}, ]; } TestBed.configureTestingModule({declarations: [LoopComp, Parent], imports: [CommonModule]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<loop-comp>' + '<loop-comp><div>1 - one - Parent</div><div>2 - one - Parent</div></loop-comp>' + '<loop-comp><div>3 - two - Parent</div><div>4 - two - Parent</div></loop-comp>' + '</loop-comp>', ); fixture.componentInstance.rows = [ {data: ['5', '6'], value: 'three'}, {data: ['7'], value: 'four'}, ]; fixture.componentInstance.name = 'New name!'; fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<loop-comp>' + '<loop-comp><div>5 - three - New name!</div><div>6 - three - New name!</div></loop-comp>' + '<loop-comp><div>7 - four - New name!</div></loop-comp>' + '</loop-comp>', ); }); it('should insert elements in the proper order when template root is an ng-container', () => { @Component({ template: ` <ng-container *ngFor="let item of items">|{{ item }}|</ng-container> `, standalone: false, }) class App { items = ['one', 'two', 'three']; } TestBed.configureTestingModule({imports: [CommonModule], declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|one||two||three|'); fixture.componentInstance.items.unshift('zero'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|zero||one||two||three|'); fixture.componentInstance.items.push('four'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|zero||one||two||three||four|'); fixture.componentInstance.items.splice(3, 0, 'two point five'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe( '|zero||one||two||two point five||three||four|', ); }); it('should insert elements in the proper order when template root is an ng-container and is wrapped by an ng-container', () => { @Component({ template: ` <ng-container> <ng-container *ngFor="let item of items">|{{ item }}|</ng-container> </ng-container> `, standalone: false, }) class App { items = ['one', 'two', 'three']; } TestBed.configureTestingModule({imports: [CommonModule], declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|one||two||three|'); fixture.componentInstance.items.unshift('zero'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|zero||one||two||three|'); fixture.componentInstance.items.push('four'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|zero||one||two||three||four|'); fixture.componentInstance.items.splice(3, 0, 'two point five'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe( '|zero||one||two||two point five||three||four|', ); }); it('should insert elements in the proper order when template root is an ng-container and first node is a ng-container', () => { @Component({ template: ` <ng-container *ngFor="let item of items"><ng-container>|{{ item }}|</ng-container></ng-container> `, standalone: false, }) class App { items = ['one', 'two', 'three']; } TestBed.configureTestingModule({imports: [CommonModule], declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|one||two||three|'); fixture.componentInstance.items.unshift('zero'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|zero||one||two||three|'); fixture.componentInstance.items.push('four'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|zero||one||two||three||four|'); fixture.componentInstance.items.splice(3, 0, 'two point five'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe( '|zero||one||two||two point five||three||four|', ); }); it('should insert elements in the proper order when template root is an ng-container, wrapped in an ng-container with the root node as an ng-container', () => { @Component({ template: ` <ng-container> <ng-container *ngFor="let item of items"><ng-container>|{{ item }}|</ng-container></ng-container> </ng-container> `, standalone: false, }) class App { items = ['one', 'two', 'three']; } TestBed.configureTestingModule({imports: [CommonModule], declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|one||two||three|'); fixture.componentInstance.items.unshift('zero'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|zero||one||two||three|'); fixture.componentInstance.items.push('four'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|zero||one||two||three||four|'); fixture.componentInstance.items.splice(3, 0, 'two point five'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe( '|zero||one||two||two point five||three||four|', ); });
{ "end_byte": 71903, "start_byte": 63106, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_container_ref_spec.ts" }
angular/packages/core/test/acceptance/view_container_ref_spec.ts_71909_73093
('should insert elements in the proper order when the first child node is an ICU expression', () => { @Component({ template: ` <ng-container *ngFor="let item of items">{count, select, other {|{{ item }}|}}</ng-container> `, standalone: false, }) class App { items = ['one', 'two', 'three']; } TestBed.configureTestingModule({imports: [CommonModule], declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|one||two||three|'); fixture.componentInstance.items.unshift('zero'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|zero||one||two||three|'); fixture.componentInstance.items.push('four'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('|zero||one||two||three||four|'); fixture.componentInstance.items.splice(3, 0, 'two point five'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe( '|zero||one||two||two point five||three||four|', ); }); });
{ "end_byte": 73093, "start_byte": 71909, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_container_ref_spec.ts" }
angular/packages/core/test/acceptance/view_container_ref_spec.ts_73097_81324
scribe('lifecycle hooks', () => { // Angular 5 reference: https://stackblitz.com/edit/lifecycle-hooks-vcref const log: string[] = []; @Component({ selector: 'hooks', template: `{{name}}`, standalone: false, }) class ComponentWithHooks { @Input() name: string | undefined; private log(msg: string) { log.push(msg); } ngOnChanges() { this.log('onChanges-' + this.name); } ngOnInit() { this.log('onInit-' + this.name); } ngDoCheck() { this.log('doCheck-' + this.name); } ngAfterContentInit() { this.log('afterContentInit-' + this.name); } ngAfterContentChecked() { this.log('afterContentChecked-' + this.name); } ngAfterViewInit() { this.log('afterViewInit-' + this.name); } ngAfterViewChecked() { this.log('afterViewChecked-' + this.name); } ngOnDestroy() { this.log('onDestroy-' + this.name); } } it('should call all hooks in correct order when creating with createEmbeddedView', () => { @Component({ template: ` <ng-template #foo> <hooks [name]="'C'"></hooks> </ng-template> <hooks vcref [tplRef]="foo" [name]="'A'"></hooks> <hooks [name]="'B'"></hooks> `, standalone: false, }) class SomeComponent {} log.length = 0; TestBed.configureTestingModule({ declarations: [SomeComponent, ComponentWithHooks, VCRefDirective], }); const fixture = TestBed.createComponent(SomeComponent); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); expect(log).toEqual([ 'onChanges-A', 'onInit-A', 'doCheck-A', 'onChanges-B', 'onInit-B', 'doCheck-B', 'afterContentInit-A', 'afterContentChecked-A', 'afterContentInit-B', 'afterContentChecked-B', 'afterViewInit-A', 'afterViewChecked-A', 'afterViewInit-B', 'afterViewChecked-B', ]); log.length = 0; fixture.detectChanges(); expect(log).toEqual([ 'doCheck-A', 'doCheck-B', 'afterContentChecked-A', 'afterContentChecked-B', 'afterViewChecked-A', 'afterViewChecked-B', ]); log.length = 0; vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef!); expect(getElementHtml(fixture.nativeElement)).toEqual( '<hooks vcref="">A</hooks><hooks></hooks><hooks>B</hooks>', ); expect(log).toEqual([]); log.length = 0; fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<hooks vcref="">A</hooks><hooks>C</hooks><hooks>B</hooks>', ); expect(log).toEqual([ 'doCheck-A', 'doCheck-B', 'onChanges-C', 'onInit-C', 'doCheck-C', 'afterContentInit-C', 'afterContentChecked-C', 'afterViewInit-C', 'afterViewChecked-C', 'afterContentChecked-A', 'afterContentChecked-B', 'afterViewChecked-A', 'afterViewChecked-B', ]); log.length = 0; fixture.detectChanges(); expect(log).toEqual([ 'doCheck-A', 'doCheck-B', 'doCheck-C', 'afterContentChecked-C', 'afterViewChecked-C', 'afterContentChecked-A', 'afterContentChecked-B', 'afterViewChecked-A', 'afterViewChecked-B', ]); log.length = 0; const viewRef = vcRefDir.vcref.detach(0); fixture.detectChanges(); expect(log).toEqual([ 'doCheck-A', 'doCheck-B', 'afterContentChecked-A', 'afterContentChecked-B', 'afterViewChecked-A', 'afterViewChecked-B', ]); log.length = 0; vcRefDir.vcref.insert(viewRef!); fixture.detectChanges(); expect(log).toEqual([ 'doCheck-A', 'doCheck-B', 'doCheck-C', 'afterContentChecked-C', 'afterViewChecked-C', 'afterContentChecked-A', 'afterContentChecked-B', 'afterViewChecked-A', 'afterViewChecked-B', ]); log.length = 0; vcRefDir.vcref.remove(0); fixture.detectChanges(); expect(log).toEqual([ 'onDestroy-C', 'doCheck-A', 'doCheck-B', 'afterContentChecked-A', 'afterContentChecked-B', 'afterViewChecked-A', 'afterViewChecked-B', ]); }); it('should call all hooks in correct order when creating with createComponent', () => { @Component({ template: ` <hooks vcref [name]="'A'"></hooks> <hooks [name]="'B'"></hooks> `, standalone: false, }) class SomeComponent {} log.length = 0; TestBed.configureTestingModule({ declarations: [SomeComponent, VCRefDirective, ComponentWithHooks], }); const fixture = TestBed.createComponent(SomeComponent); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); expect(log).toEqual([ 'onChanges-A', 'onInit-A', 'doCheck-A', 'onChanges-B', 'onInit-B', 'doCheck-B', 'afterContentInit-A', 'afterContentChecked-A', 'afterContentInit-B', 'afterContentChecked-B', 'afterViewInit-A', 'afterViewChecked-A', 'afterViewInit-B', 'afterViewChecked-B', ]); log.length = 0; fixture.detectChanges(); expect(log).toEqual([ 'doCheck-A', 'doCheck-B', 'afterContentChecked-A', 'afterContentChecked-B', 'afterViewChecked-A', 'afterViewChecked-B', ]); log.length = 0; const componentRef = vcRefDir.vcref.createComponent(ComponentWithHooks); expect(getElementHtml(fixture.nativeElement)).toEqual( '<hooks vcref="">A</hooks><hooks></hooks><hooks>B</hooks>', ); expect(log).toEqual([]); componentRef.instance.name = 'D'; log.length = 0; fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<hooks vcref="">A</hooks><hooks>D</hooks><hooks>B</hooks>', ); expect(log).toEqual([ 'doCheck-A', 'doCheck-B', 'onInit-D', 'doCheck-D', 'afterContentInit-D', 'afterContentChecked-D', 'afterViewInit-D', 'afterViewChecked-D', 'afterContentChecked-A', 'afterContentChecked-B', 'afterViewChecked-A', 'afterViewChecked-B', ]); log.length = 0; fixture.detectChanges(); expect(log).toEqual([ 'doCheck-A', 'doCheck-B', 'doCheck-D', 'afterContentChecked-D', 'afterViewChecked-D', 'afterContentChecked-A', 'afterContentChecked-B', 'afterViewChecked-A', 'afterViewChecked-B', ]); log.length = 0; const viewRef = vcRefDir.vcref.detach(0); fixture.detectChanges(); expect(log).toEqual([ 'doCheck-A', 'doCheck-B', 'afterContentChecked-A', 'afterContentChecked-B', 'afterViewChecked-A', 'afterViewChecked-B', ]); log.length = 0; vcRefDir.vcref.insert(viewRef!); fixture.detectChanges(); expect(log).toEqual([ 'doCheck-A', 'doCheck-B', 'doCheck-D', 'afterContentChecked-D', 'afterViewChecked-D', 'afterContentChecked-A', 'afterContentChecked-B', 'afterViewChecked-A', 'afterViewChecked-B', ]); log.length = 0; vcRefDir.vcref.remove(0); fixture.detectChanges(); expect(log).toEqual([ 'onDestroy-D', 'doCheck-A', 'doCheck-B', 'afterContentChecked-A', 'afterContentChecked-B', 'afterViewChecked-A', 'afterViewChecked-B', ]); }); });
{ "end_byte": 81324, "start_byte": 73097, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_container_ref_spec.ts" }
angular/packages/core/test/acceptance/view_container_ref_spec.ts_81328_82936
scribe('host bindings', () => { it('should support host bindings on dynamically created components', () => { @Component({ selector: 'host-bindings', host: {'id': 'attribute', '[title]': 'title'}, template: ``, standalone: false, }) class HostBindingCmpt { title = 'initial'; } @Component({ template: `<ng-template vcref></ng-template>`, standalone: false, }) class TestComponent { @ViewChild(VCRefDirective, {static: true}) vcRefDir!: VCRefDirective; } TestBed.configureTestingModule({ declarations: [TestComponent, VCRefDirective, HostBindingCmpt], }); const fixture = TestBed.createComponent(TestComponent); const {vcRefDir} = fixture.componentInstance; fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toBe(''); const componentRef = vcRefDir.vcref.createComponent(HostBindingCmpt); fixture.detectChanges(); expect(fixture.nativeElement.children[0].tagName).toBe('HOST-BINDINGS'); expect(fixture.nativeElement.children[0].getAttribute('id')).toBe('attribute'); expect(fixture.nativeElement.children[0].getAttribute('title')).toBe('initial'); componentRef.instance.title = 'changed'; fixture.detectChanges(); expect(fixture.nativeElement.children[0].tagName).toBe('HOST-BINDINGS'); expect(fixture.nativeElement.children[0].getAttribute('id')).toBe('attribute'); expect(fixture.nativeElement.children[0].getAttribute('title')).toBe('changed'); }); });
{ "end_byte": 82936, "start_byte": 81328, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_container_ref_spec.ts" }
angular/packages/core/test/acceptance/view_container_ref_spec.ts_82940_91023
scribe('projection', () => { it('should project the ViewContainerRef content along its host, in an element', () => { @Component({ selector: 'child', template: '<div><ng-content></ng-content></div>', standalone: false, }) class Child {} @Component({ selector: 'parent', template: ` <ng-template #foo> <span>{{name}}</span> </ng-template> <child> <header vcref [tplRef]="foo" [name]="name">blah</header> </child>`, standalone: false, }) class Parent { name: string = 'bar'; } TestBed.configureTestingModule({declarations: [Child, Parent, VCRefDirective]}); const fixture = TestBed.createComponent(Parent); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><div><header vcref="">blah</header></div></child>', ); vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef!); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><div><header vcref="">blah</header><span>bar</span></div></child>', ); }); it('should project the ViewContainerRef content along its host, in a view', () => { @Component({ selector: 'child-with-view', template: `Before (inside)-<ng-content *ngIf="show"></ng-content>-After (inside)`, standalone: false, }) class ChildWithView { show: boolean = true; } @Component({ selector: 'parent', template: ` <ng-template #foo> <span>{{name}}</span> </ng-template> <child-with-view> Before projected <header vcref [tplRef]="foo" [name]="name">blah</header> After projected </child-with-view>`, standalone: false, }) class Parent { name: string = 'bar'; } TestBed.configureTestingModule({declarations: [ChildWithView, Parent, VCRefDirective]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child-with-view>Before (inside)- Before projected <header vcref="">blah</header> After projected -After (inside)</child-with-view>', ); vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef!); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child-with-view>Before (inside)- Before projected <header vcref="">blah</header><span>bar</span> After projected -After (inside)</child-with-view>', ); }); it('should handle empty re-projection into the root of a view', () => { @Component({ selector: 'root-comp', template: `<ng-template [ngIf]="show"><ng-content></ng-content></ng-template>`, standalone: false, }) class RootComp { @Input() show: boolean = true; } @Component({ selector: 'my-app', template: `<root-comp [show]="show"><ng-content></ng-content><div></div></root-comp>`, standalone: false, }) class MyApp { show = true; } TestBed.configureTestingModule({declarations: [MyApp, RootComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('div').length).toBe(1); fixture.componentInstance.show = false; fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('div').length).toBe(0); }); describe('with select', () => { @Component({ selector: 'child-with-selector', template: ` <p class="a"><ng-content select="header"></ng-content></p> <p class="b"><ng-content></ng-content></p>`, standalone: false, }) class ChildWithSelector {} it('should project the ViewContainerRef content along its host, when the host matches a selector', () => { @Component({ selector: 'parent', template: ` <ng-template #foo> <span>{{name}}</span> </ng-template> <child-with-selector> <header vcref [tplRef]="foo" [name]="name">blah</header> </child-with-selector> `, standalone: false, }) class Parent { name: string = 'bar'; } TestBed.configureTestingModule({declarations: [Parent, ChildWithSelector, VCRefDirective]}); const fixture = TestBed.createComponent(Parent); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child-with-selector><p class="a"><header vcref="">blah</header></p><p class="b"></p></child-with-selector>', ); vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef!); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child-with-selector><p class="a"><header vcref="">blah</header><span>bar</span></p><p class="b"></p></child-with-selector>', ); }); it('should create embedded view when ViewContainerRef is inside projection', () => { @Component({ selector: 'content-comp', template: '<ng-content></ng-content>', standalone: false, }) class ContentComp {} @Component({ selector: 'my-comp', template: ` <content-comp> <div #target></div> </content-comp> <ng-template #source>My Content</ng-template> `, standalone: false, }) class MyComp { @ViewChild('source', {static: true}) source!: TemplateRef<{}>; @ViewChild('target', {read: ViewContainerRef, static: true}) target!: ViewContainerRef; ngOnInit() { this.target.createEmbeddedView(this.source); } } TestBed.configureTestingModule({declarations: [MyComp, ContentComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(fixture.debugElement.nativeElement.innerHTML).toContain('My Content'); }); it('should not project the ViewContainerRef content, when the host does not match a selector', () => { @Component({ selector: 'parent', template: ` <ng-template #foo> <span>{{name}}</span> </ng-template> <child-with-selector> <footer vcref [tplRef]="foo" [name]="name">blah</footer> </child-with-selector> `, standalone: false, }) class Parent { name: string = 'bar'; } TestBed.configureTestingModule({declarations: [Parent, ChildWithSelector, VCRefDirective]}); const fixture = TestBed.createComponent(Parent); const vcRefDir = fixture.debugElement .query(By.directive(VCRefDirective)) .injector.get(VCRefDirective); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child-with-selector><p class="a"></p><p class="b"><footer vcref="">blah</footer></p></child-with-selector>', ); vcRefDir.vcref.createEmbeddedView(vcRefDir.tplRef!); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child-with-selector><p class="a"></p><p class="b"><footer vcref="">blah</footer><span>bar</span></p></child-with-selector>', ); }); }); });
{ "end_byte": 91023, "start_byte": 82940, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_container_ref_spec.ts" }
angular/packages/core/test/acceptance/view_container_ref_spec.ts_91027_97875
scribe('root view container ref', () => { let containerEl: HTMLElement | null = null; beforeEach(() => (containerEl = null)); /** * Creates a new test component renderer instance that wraps the root element * in another element. This allows us to test if elements have been inserted into * the parent element of the root component. */ function createTestComponentRenderer(document: any): TestComponentRenderer { return { insertRootElement(rootElementId: string) { const rootEl = document.createElement('div'); rootEl.id = rootElementId; containerEl = document.createElement('div'); document.body.appendChild(containerEl); containerEl!.appendChild(rootEl); }, removeAllRootElements() { containerEl?.remove(); }, }; } const TEST_COMPONENT_RENDERER = { provide: TestComponentRenderer, useFactory: createTestComponentRenderer, deps: [DOCUMENT], }; it('should check bindings for components dynamically created by root component', () => { @Component({ selector: 'dynamic-cmpt-with-bindings', template: `check count: {{checkCount}}`, standalone: false, }) class DynamicCompWithBindings implements DoCheck { checkCount = 0; ngDoCheck() { this.checkCount++; } } @Component({ template: ``, standalone: false, }) class TestComp { constructor(public vcRef: ViewContainerRef) {} } TestBed.configureTestingModule({ declarations: [TestComp, DynamicCompWithBindings], providers: [TEST_COMPONENT_RENDERER], }); const fixture = TestBed.createComponent(TestComp); const {vcRef} = fixture.componentInstance; fixture.detectChanges(); expect(containerEl!.childNodes.length).toBe(2); expect(containerEl!.childNodes[1].nodeType).toBe(Node.COMMENT_NODE); expect((containerEl!.childNodes[0] as Element).tagName).toBe('DIV'); vcRef.createComponent(DynamicCompWithBindings); fixture.detectChanges(); expect(containerEl!.childNodes.length).toBe(3); expect(containerEl!.childNodes[1].textContent).toBe('check count: 1'); fixture.detectChanges(); expect(containerEl!.childNodes.length).toBe(3); expect(containerEl!.childNodes[1].textContent).toBe('check count: 2'); }); it('should create deep DOM tree immediately for dynamically created components', () => { @Component({ template: ``, standalone: false, }) class TestComp { constructor(public vcRef: ViewContainerRef) {} } @Component({ selector: 'child', template: `<div>{{name}}</div>`, standalone: false, }) class Child { name = 'text'; } @Component({ selector: 'dynamic-cmpt-with-children', template: `<child></child>`, standalone: false, }) class DynamicCompWithChildren {} TestBed.configureTestingModule({ declarations: [TestComp, DynamicCompWithChildren, Child], providers: [TEST_COMPONENT_RENDERER], }); const fixture = TestBed.createComponent(TestComp); const {vcRef} = fixture.componentInstance; fixture.detectChanges(); expect(containerEl!.childNodes.length).toBe(2); expect(containerEl!.childNodes[1].nodeType).toBe(Node.COMMENT_NODE); expect((containerEl!.childNodes[0] as Element).tagName).toBe('DIV'); vcRef.createComponent(DynamicCompWithChildren); expect(containerEl!.childNodes.length).toBe(3); expect(getElementHtml(containerEl!.childNodes[1] as Element)).toBe( '<child><div></div></child>', ); fixture.detectChanges(); expect(containerEl!.childNodes.length).toBe(3); expect(getElementHtml(containerEl!.childNodes[1] as Element)).toBe( `<child><div>text</div></child>`, ); }); }); }); @Component({ template: ` <ng-template #tplRef let-name>{{name}}</ng-template> <p vcref [tplRef]="tplRef"></p> `, standalone: false, }) class EmbeddedViewInsertionComp {} @Directive({ selector: '[vcref]', standalone: false, }) class VCRefDirective { @Input() tplRef: TemplateRef<any> | undefined; @Input() name: string = ''; // Injecting the ViewContainerRef to create a dynamic container in which // embedded views will be created constructor( public vcref: ViewContainerRef, public elementRef: ElementRef, ) {} createView(s: string, index?: number): EmbeddedViewRef<any> { if (!this.tplRef) { throw new Error('No template reference passed to directive.'); } return this.vcref.createEmbeddedView(this.tplRef, {$implicit: s}, index); } } @Component({ selector: `embedded-cmp-with-ngcontent`, template: `<ng-content></ng-content><hr><ng-content></ng-content>`, standalone: false, }) class EmbeddedComponentWithNgContent {} @Component({ selector: 'view-container-ref-comp', template: ` <ng-template #ref0>0</ng-template> <ng-template #ref1>1</ng-template> <ng-template #ref2>2</ng-template> `, standalone: false, }) class ViewContainerRefComp { @ViewChildren(TemplateRef) templates!: QueryList<TemplateRef<any>>; constructor(public vcr: ViewContainerRef) {} } @Component({ selector: 'view-container-ref-app', template: ` <view-container-ref-comp></view-container-ref-comp> `, standalone: false, }) class ViewContainerRefApp { @ViewChild(ViewContainerRefComp) vcrComp!: ViewContainerRefComp; } @Directive({ selector: '[structDir]', standalone: false, }) export class StructDir { constructor( private vcref: ViewContainerRef, private tplRef: TemplateRef<any>, ) {} create() { this.vcref.createEmbeddedView(this.tplRef); } destroy() { this.vcref.clear(); } } @Component({ selector: 'destroy-cases', template: ` `, standalone: false, }) class DestroyCasesComp { @ViewChildren(StructDir) structDirs!: QueryList<StructDir>; } @Directive({ selector: '[constructorDir]', standalone: false, }) class ConstructorDir { constructor(vcref: ViewContainerRef, tplRef: TemplateRef<any>) { vcref.createEmbeddedView(tplRef); } } @Component({ selector: 'constructor-app', template: ` <div *constructorDir> <span *constructorDir #foo></span> </div> `, standalone: false, }) class ConstructorApp { @ViewChild('foo', {static: true}) foo!: ElementRef; } @Component({ selector: 'constructor-app-with-queries', template: ` <ng-template constructorDir #foo> <div #foo></div> </ng-template> `, standalone: false, }) class ConstructorAppWithQueries { @ViewChild('foo', {static: true}) foo!: TemplateRef<any>; }
{ "end_byte": 97875, "start_byte": 91027, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_container_ref_spec.ts" }
angular/packages/core/test/acceptance/listener_spec.ts_0_8709
/** * @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} from '@angular/common'; import { Component, Directive, ErrorHandler, EventEmitter, HostListener, Input, OnInit, Output, QueryList, TemplateRef, ViewChild, ViewChildren, ViewContainerRef, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; function getNoOfNativeListeners(): number { return ngDevMode ? ngDevMode.rendererAddEventListener : 0; } describe('event listeners', () => { describe('even handling statements', () => { it('should call function on event emit', () => { @Component({ template: `<button (click)="onClick()">Click me</button>`, standalone: false, }) class MyComp { counter = 0; onClick() { this.counter++; } } const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(fixture.componentInstance.counter).toEqual(0); const button = fixture.nativeElement.querySelector('button'); button.click(); expect(fixture.componentInstance.counter).toEqual(1); }); it('should call function chain on event emit', () => { @Component({ template: `<button (click)="onClick(); onClick2(); "> Click me </button>`, standalone: false, }) class MyComp { counter = 0; counter2 = 0; onClick() { this.counter++; } onClick2() { this.counter2++; } } const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(fixture.componentInstance.counter).toEqual(0); expect(fixture.componentInstance.counter2).toEqual(0); const button = fixture.nativeElement.querySelector('button'); button.click(); expect(fixture.componentInstance.counter).toEqual(1); expect(fixture.componentInstance.counter2).toEqual(1); }); it('should evaluate expression on event emit', () => { @Component({ template: `<button (click)="showing=!showing"> Click me </button>`, standalone: false, }) class MyComp { showing = false; } const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(fixture.componentInstance.showing).toBeFalse(); const button = fixture.nativeElement.querySelector('button'); button.click(); expect(fixture.componentInstance.showing).toBeTrue(); button.click(); expect(fixture.componentInstance.showing).toBeFalse(); }); it('should support listeners with specified set of args', () => { @Component({ template: `<button (click)="onClick(data.a, data.b)"> Click me </button>`, standalone: false, }) class MyComp { counter = 0; data = {a: 1, b: 2}; onClick(a: any, b: any) { this.counter += a + b; } } const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(fixture.componentInstance.counter).toBe(0); const button = fixture.nativeElement.querySelector('button'); button.click(); expect(fixture.componentInstance.counter).toBe(3); button.click(); expect(fixture.componentInstance.counter).toBe(6); }); it('should be able to access a property called $event using `this`', () => { let eventVariable: number | undefined; let eventObject: MouseEvent | undefined; @Component({ template: ` <button (click)="clicked(this.$event, $event)">Click me!</button> `, standalone: false, }) class MyComp { $event = 10; clicked(value: number, event: MouseEvent) { eventVariable = value; eventObject = event; } } TestBed.configureTestingModule({declarations: [MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); expect(eventVariable).toBe(10); expect(eventObject?.type).toBe('click'); }); it('should be able to use a keyed write on `this` from a listener inside an ng-template', () => { @Component({ template: ` <ng-template #template> <button (click)="this['mes' + 'sage'] = 'hello'">Click me</button> </ng-template> <ng-container [ngTemplateOutlet]="template"></ng-container> `, standalone: false, }) class MyComp { message = ''; } TestBed.configureTestingModule({declarations: [MyComp], imports: [CommonModule]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); button.click(); fixture.detectChanges(); expect(fixture.componentInstance.message).toBe('hello'); }); it('should reference the correct context object if it is swapped out', () => { @Component({ template: ` <ng-template let-obj #template> <button (click)="obj.value = obj.value + '!'">Change</button> </ng-template> <ng-container *ngTemplateOutlet="template; context: {$implicit: current}"></ng-container> `, standalone: false, }) class MyComp { one = {value: 'one'}; two = {value: 'two'}; current = this.one; } TestBed.configureTestingModule({declarations: [MyComp], imports: [CommonModule]}); const fixture = TestBed.createComponent(MyComp); const instance = fixture.componentInstance; fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); expect(instance.one.value).toBe('one'); expect(instance.two.value).toBe('two'); button.click(); fixture.detectChanges(); expect(instance.one.value).toBe('one!'); expect(instance.two.value).toBe('two'); instance.current = instance.two; fixture.detectChanges(); button.click(); fixture.detectChanges(); expect(instance.one.value).toBe('one!'); expect(instance.two.value).toBe('two!'); }); it('should support local refs in listeners', () => { @Component({ selector: 'my-comp', standalone: true, template: ``, }) class MyComp {} @Component({ standalone: true, imports: [MyComp], template: ` <my-comp #comp></my-comp> <button (click)="onClick(comp)"></button> `, }) class App { comp: MyComp | null = null; onClick(comp: MyComp) { this.comp = comp; } } const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.comp).toBeNull(); const button = fixture.nativeElement.querySelector('button'); button.click(); expect(fixture.componentInstance.comp).toBeInstanceOf(MyComp); }); }); describe('prevent default', () => { it('should call prevent default when a handler returns false', () => { @Component({ template: `<button (click)="onClick($event)">Click</button>`, standalone: false, }) class MyComp { handlerReturnValue: boolean | undefined; event: Event | undefined; onClick(e: any) { this.event = e; // stub preventDefault() to check whether it's called Object.defineProperty(this.event, 'preventDefault', { value: jasmine.createSpy('preventDefault'), writable: true, }); return this.handlerReturnValue; } } const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const myComp = fixture.componentInstance; const button = fixture.nativeElement.querySelector('button'); myComp.handlerReturnValue = undefined; button.click(); expect(myComp.event!.preventDefault).not.toHaveBeenCalled(); myComp.handlerReturnValue = true; button.click(); expect(myComp.event!.preventDefault).not.toHaveBeenCalled(); // Returning `false` is what causes the renderer to call `event.preventDefault`. myComp.handlerReturnValue = false; button.click(); expect(myComp.event!.preventDefault).toHaveBeenCalled(); }); });
{ "end_byte": 8709, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/listener_spec.ts" }
angular/packages/core/test/acceptance/listener_spec.ts_8713_17254
describe('coalescing', () => { @Component({ selector: 'with-clicks-cmpt', template: `<button likes-clicks (click)="count()" md-button>Click me!</button>`, standalone: false, }) class WithClicksCmpt { counter = 0; count() { this.counter++; } } @Directive({ selector: '[md-button]', standalone: false, }) class MdButton { counter = 0; @HostListener('click') count() { this.counter++; } } @Directive({ selector: '[likes-clicks]', standalone: false, }) class LikesClicks { counter = 0; @HostListener('click') count() { this.counter++; } } @Directive({ selector: '[returns-false]', standalone: false, }) class ReturnsFalse { counter = 0; event!: Event; handlerShouldReturn: boolean | undefined = undefined; @HostListener('click', ['$event']) count(e: Event) { this.counter++; this.event = e; // stub preventDefault() to check whether it's called Object.defineProperty(this.event, 'preventDefault', { value: jasmine.createSpy('preventDefault'), writable: true, }); return this.handlerShouldReturn; } } it('should coalesce multiple event listeners for the same event on the same element', () => { @Component({ selector: 'test-cmpt', template: `<with-clicks-cmpt></with-clicks-cmpt><with-clicks-cmpt></with-clicks-cmpt>`, standalone: false, }) class TestCmpt {} TestBed.configureTestingModule({ declarations: [TestCmpt, WithClicksCmpt, LikesClicks, MdButton], }); const noOfEventListenersRegisteredSoFar = getNoOfNativeListeners(); const fixture = TestBed.createComponent(TestCmpt); fixture.detectChanges(); const buttonDebugEls = fixture.debugElement.queryAll(By.css('button')); const withClicksEls = fixture.debugElement.queryAll(By.css('with-clicks-cmpt')); // We want to assert that only one native event handler was registered but still all // directives are notified when an event fires. This assertion can only be verified in // the ngDevMode (but the coalescing always happens!). ngDevMode && expect(getNoOfNativeListeners()).toBe(noOfEventListenersRegisteredSoFar + 2); buttonDebugEls[0].nativeElement.click(); expect(withClicksEls[0].injector.get(WithClicksCmpt).counter).toBe(1); expect(buttonDebugEls[0].injector.get(LikesClicks).counter).toBe(1); expect(buttonDebugEls[0].injector.get(MdButton).counter).toBe(1); expect(withClicksEls[1].injector.get(WithClicksCmpt).counter).toBe(0); expect(buttonDebugEls[1].injector.get(LikesClicks).counter).toBe(0); expect(buttonDebugEls[1].injector.get(MdButton).counter).toBe(0); buttonDebugEls[1].nativeElement.click(); expect(withClicksEls[0].injector.get(WithClicksCmpt).counter).toBe(1); expect(buttonDebugEls[0].injector.get(LikesClicks).counter).toBe(1); expect(buttonDebugEls[0].injector.get(MdButton).counter).toBe(1); expect(withClicksEls[1].injector.get(WithClicksCmpt).counter).toBe(1); expect(buttonDebugEls[1].injector.get(LikesClicks).counter).toBe(1); expect(buttonDebugEls[1].injector.get(MdButton).counter).toBe(1); }); it('should coalesce multiple event listeners in presence of queries', () => { @Component({ selector: 'test-cmpt', template: `<button likes-clicks (click)="counter = counter+1">Click me!</button>`, standalone: false, }) class TestCmpt { counter = 0; @ViewChildren('nothing') nothing!: QueryList<any>; } TestBed.configureTestingModule({declarations: [TestCmpt, LikesClicks]}); const noOfEventListenersRegisteredSoFar = getNoOfNativeListeners(); const fixture = TestBed.createComponent(TestCmpt); fixture.detectChanges(); const buttonDebugEl = fixture.debugElement.query(By.css('button')); // We want to assert that only one native event handler was registered but still all // directives are notified when an event fires. This assertion can only be verified in // the ngDevMode (but the coalescing always happens!). ngDevMode && expect(getNoOfNativeListeners()).toBe(noOfEventListenersRegisteredSoFar + 1); buttonDebugEl.nativeElement.click(); expect(buttonDebugEl.injector.get(LikesClicks).counter).toBe(1); expect(fixture.componentInstance.counter).toBe(1); }); it('should try to execute remaining coalesced listeners if one of the listeners throws', () => { @Directive({ selector: '[throws-on-clicks]', standalone: false, }) class ThrowsOnClicks { @HostListener('click') dontCount() { throw new Error("I was clicked and I don't like it!"); } } @Component({ selector: 'test-cmpt', template: `<button throws-on-clicks likes-clicks><button>`, standalone: false, }) class TestCmpt {} let noOfErrors = 0; class CountingErrorHandler extends ErrorHandler { override handleError(error: any): void { noOfErrors++; } } TestBed.configureTestingModule({ declarations: [TestCmpt, LikesClicks, ThrowsOnClicks], providers: [{provide: ErrorHandler, useClass: CountingErrorHandler}], }); const fixture = TestBed.createComponent(TestCmpt); fixture.detectChanges(); const buttonDebugEl = fixture.debugElement.query(By.css('button')); expect(buttonDebugEl.injector.get(LikesClicks).counter).toBe(0); buttonDebugEl.nativeElement.click(); expect(noOfErrors).toBe(1); expect(buttonDebugEl.injector.get(LikesClicks).counter).toBe(1); }); it('should prevent default if any of the listeners returns false', () => { @Component({ selector: 'test-cmpt', template: ` <button returns-false likes-clicks></button> `, standalone: false, }) class TestCmpt {} TestBed.configureTestingModule({declarations: [TestCmpt, ReturnsFalse, LikesClicks]}); const fixture = TestBed.createComponent(TestCmpt); fixture.detectChanges(); const buttonDebugEl = fixture.debugElement.query(By.css('button')); const likesClicksDir = buttonDebugEl.injector.get(LikesClicks); const returnsFalseDir = buttonDebugEl.injector.get(ReturnsFalse); expect(likesClicksDir.counter).toBe(0); expect(returnsFalseDir.counter).toBe(0); buttonDebugEl.nativeElement.click(); expect(likesClicksDir.counter).toBe(1); expect(returnsFalseDir.counter).toBe(1); expect(returnsFalseDir.event.preventDefault).not.toHaveBeenCalled(); returnsFalseDir.handlerShouldReturn = true; buttonDebugEl.nativeElement.click(); expect(returnsFalseDir.event.preventDefault).not.toHaveBeenCalled(); returnsFalseDir.handlerShouldReturn = false; buttonDebugEl.nativeElement.click(); expect(returnsFalseDir.event.preventDefault).toHaveBeenCalled(); }); it('should not subscribe twice to the output when there are 2 coalesced listeners', () => { @Directive({ selector: '[foo]', standalone: false, }) class FooDirective { @Input('foo') model: any; @Output('fooChange') update = new EventEmitter(); updateValue(value: any) { this.update.emit(value); } } @Component({ selector: 'test-component', template: `<div [(foo)]="someValue" (fooChange)="fooChange($event)"></div>`, standalone: false, }) class TestComponent { count = 0; someValue = -1; @ViewChild(FooDirective) fooDirective: FooDirective | null = null; fooChange() { this.count++; } triggerUpdate(value: any) { this.fooDirective!.updateValue(value); } } TestBed.configureTestingModule({declarations: [TestComponent, FooDirective]}); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); const componentInstance = fixture.componentInstance; componentInstance.triggerUpdate(42); fixture.detectChanges(); expect(componentInstance.count).toEqual(1); expect(componentInstance.someValue).toEqual(42); });
{ "end_byte": 17254, "start_byte": 8713, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/listener_spec.ts" }
angular/packages/core/test/acceptance/listener_spec.ts_17260_24223
it('should maintain the order in which listeners are registered', () => { const log: string[] = []; @Component({ selector: 'my-comp', template: '<button dirA dirB (click)="count()">Click me!</button>', standalone: false, }) class MyComp { counter = 0; count() { log.push('component.click'); } } @Directive({ selector: '[dirA]', standalone: false, }) class DirA { @HostListener('click') count() { log.push('dirA.click'); } } @Directive({ selector: '[dirB]', standalone: false, }) class DirB { @HostListener('click') count() { log.push('dirB.click'); } } TestBed.configureTestingModule({declarations: [MyComp, DirA, DirB]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const button = fixture.nativeElement.firstChild; button.click(); expect(log).toEqual(['dirA.click', 'dirB.click', 'component.click']); }); }); describe('destroy', () => { it('should destroy listeners when view is removed', () => { @Component({ selector: 'my-comp', template: ` <button *ngIf="visible" (click)="count()">Click me!</button> `, standalone: false, }) class MyComp { visible = true; counter = 0; count() { this.counter++; } } TestBed.configureTestingModule({declarations: [MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const comp = fixture.componentInstance; const button = fixture.nativeElement.querySelector('button'); button.click(); expect(comp.counter).toBe(1); comp.visible = false; fixture.detectChanges(); button.click(); expect(comp.counter).toBe(1); }); it('should destroy listeners when views generated using *ngFor are removed', () => { let counter = 0; @Component({ selector: 'my-comp', template: ` <button *ngFor="let button of buttons" (click)="count()">Click me!</button> `, standalone: false, }) class MyComp { buttons = [1, 2]; count() { counter++; } } TestBed.configureTestingModule({declarations: [MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const comp = fixture.componentInstance; const buttons = fixture.nativeElement.querySelectorAll('button'); buttons[0].click(); buttons[1].click(); expect(counter).toBe(2); comp.buttons = []; fixture.detectChanges(); buttons[0].click(); buttons[1].click(); expect(counter).toBe(2); }); it('should destroy listeners when nested view is removed', () => { @Component({ selector: 'my-comp', template: ` <ng-container *ngIf="isSectionVisible"> Click to submit a form: <button *ngIf="isButtonVisible" (click)="count()">Click me!</button> </ng-container> `, standalone: false, }) class MyComp { isSectionVisible = true; isButtonVisible = true; counter = 0; count() { this.counter++; } } TestBed.configureTestingModule({declarations: [MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const comp = fixture.componentInstance; const button = fixture.nativeElement.querySelector('button'); button.click(); expect(comp.counter).toBe(1); comp.isButtonVisible = false; fixture.detectChanges(); button.click(); expect(comp.counter).toBe(1); comp.isSectionVisible = false; fixture.detectChanges(); button.click(); expect(comp.counter).toBe(1); }); }); describe('host listeners', () => { it('should support host listeners on components', () => { const events: string[] = []; @Component({ template: ``, standalone: false, }) class MyComp { @HostListener('click') onClick() { events.push('click!'); } } const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const host = fixture.nativeElement; host.click(); expect(events).toEqual(['click!']); host.click(); expect(events).toEqual(['click!', 'click!']); }); it('should support global host listeners on components', () => { const events: string[] = []; @Component({ template: ``, standalone: false, }) class MyComp { @HostListener('document:click') onClick() { events.push('global click!'); } } const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const host = fixture.nativeElement; host.click(); expect(events).toEqual(['global click!']); host.click(); expect(events).toEqual(['global click!', 'global click!']); }); it('should support host listeners on directives', () => { const events: string[] = []; @Directive({ selector: '[hostListenerDir]', standalone: true, }) class HostListenerDir { @HostListener('click') onClick() { events.push('click!'); } } @Component({ standalone: true, imports: [HostListenerDir], template: `<button hostListenerDir>Click</button>`, }) class MyComp {} const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(events).toEqual([]); const button = fixture.nativeElement.querySelector('button'); button.click(); expect(events).toEqual(['click!']); button.click(); expect(events).toEqual(['click!', 'click!']); }); it('should support global host listeners on directives', () => { const events: string[] = []; @Directive({ selector: '[hostListenerDir]', standalone: true, }) class HostListenerDir { @HostListener('document:click') onClick() { events.push('click!'); } } @Component({ standalone: true, imports: [HostListenerDir], template: `<button hostListenerDir>Click</button>`, }) class MyComp {} const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(events).toEqual([]); const button = fixture.nativeElement.querySelector('button'); button.click(); expect(events).toEqual(['click!']); button.click(); expect(events).toEqual(['click!', 'click!']); }); });
{ "end_byte": 24223, "start_byte": 17260, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/listener_spec.ts" }
angular/packages/core/test/acceptance/listener_spec.ts_24227_27386
describe('global host listeners on special element as directive hosts', () => { it('should bind global event listeners on an ng-container directive host', () => { let clicks = 0; @Directive({ selector: '[add-global-listener]', standalone: false, }) class AddGlobalListener { @HostListener('document:click') handleClick() { clicks++; } } @Component({ template: ` <ng-container add-global-listener> <button>Click me!</button> </ng-container> `, standalone: false, }) class MyComp {} TestBed.configureTestingModule({declarations: [MyComp, AddGlobalListener]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); button.click(); fixture.detectChanges(); expect(clicks).toBe(1); }); it('should bind global event listeners on an ng-template directive host', () => { let clicks = 0; @Directive({ selector: '[add-global-listener]', standalone: false, }) class AddGlobalListener { @HostListener('document:click') handleClick() { clicks++; } } @Component({ template: ` <ng-template #template add-global-listener> <button>Click me!</button> </ng-template> <ng-container [ngTemplateOutlet]="template"></ng-container> `, standalone: false, }) class MyComp {} TestBed.configureTestingModule({ declarations: [MyComp, AddGlobalListener], imports: [CommonModule], }); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); button.click(); fixture.detectChanges(); expect(clicks).toBe(1); }); it('should bind global event listeners on a structural directive host', () => { let clicks = 0; @Directive({ selector: '[add-global-listener]', standalone: false, }) class AddGlobalListener implements OnInit { @HostListener('document:click') handleClick() { clicks++; } constructor( private _vcr: ViewContainerRef, private _templateRef: TemplateRef<any>, ) {} ngOnInit() { this._vcr.createEmbeddedView(this._templateRef); } } @Component({ template: ` <div *add-global-listener> <button>Click me!</button> </div> `, standalone: false, }) class MyComp {} TestBed.configureTestingModule({declarations: [MyComp, AddGlobalListener]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); button.click(); fixture.detectChanges(); expect(clicks).toBe(1); }); }); });
{ "end_byte": 27386, "start_byte": 24227, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/listener_spec.ts" }
angular/packages/core/test/acceptance/standalone_spec.ts_0_601
/** * @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, NgComponentOutlet} from '@angular/common'; import { Component, createEnvironmentInjector, Directive, EnvironmentInjector, forwardRef, inject, Injectable, Injector, Input, isStandalone, NgModule, NO_ERRORS_SCHEMA, OnInit, Pipe, PipeTransform, ViewChild, ViewContainerRef, } from '@angular/core'; import {TestBed} from '@angular/core/testing';
{ "end_byte": 601, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/standalone_spec.ts" }
angular/packages/core/test/acceptance/standalone_spec.ts_603_8877
describe('standalone components, directives, and pipes', () => { it('should render a standalone component', () => { @Component({ standalone: true, template: 'Look at me, no NgModule!', }) class StandaloneCmp {} const fixture = TestBed.createComponent(StandaloneCmp); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('Look at me, no NgModule!'); }); it('should render a recursive standalone component', () => { @Component({ selector: 'tree', standalone: true, template: `({{level}})<ng-template [ngIf]="level > 0"><tree [level]="level - 1"></tree></ng-template>`, imports: [CommonModule], }) class TreeCmp { @Input() level = 0; } @Component({standalone: true, template: '<tree [level]="3"></tree>', imports: [TreeCmp]}) class StandaloneCmp {} const fixture = TestBed.createComponent(StandaloneCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(3)(2)(1)(0)'); }); it('should render a standalone component with a standalone dependency', () => { @Component({ selector: 'inner-cmp', template: 'Look at me, no NgModule!', }) class InnerCmp {} @Component({ template: '<inner-cmp></inner-cmp>', imports: [InnerCmp], }) class StandaloneCmp {} const fixture = TestBed.createComponent(StandaloneCmp); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( '<inner-cmp>Look at me, no NgModule!</inner-cmp>', ); }); it('should render a standalone component (with standalone: true) with a standalone dependency', () => { @Component({ selector: 'inner-cmp', template: 'Look at me, no NgModule!', standalone: true, }) class InnerCmp {} @Component({ template: '<inner-cmp></inner-cmp>', imports: [InnerCmp], }) class StandaloneCmp {} const fixture = TestBed.createComponent(StandaloneCmp); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( '<inner-cmp>Look at me, no NgModule!</inner-cmp>', ); }); it('should render a standalone component with an NgModule-based dependency', () => { @Component({ selector: 'inner-cmp', template: 'Look at me, no NgModule (kinda)!', standalone: false, }) class InnerCmp {} @NgModule({ declarations: [InnerCmp], exports: [InnerCmp], }) class Module {} @Component({ standalone: true, template: '<inner-cmp></inner-cmp>', imports: [Module], }) class StandaloneCmp {} const fixture = TestBed.createComponent(StandaloneCmp); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( '<inner-cmp>Look at me, no NgModule (kinda)!</inner-cmp>', ); }); it('should allow exporting standalone components, directives, and pipes from NgModule', () => { @Component({ selector: 'standalone-cmp', standalone: true, template: `standalone`, }) class StandaloneCmp {} @Directive({ selector: '[standalone-dir]', host: { '[attr.id]': '"standalone"', }, standalone: true, }) class StandaloneDir {} @Pipe({name: 'standalonePipe', standalone: true}) class StandalonePipe implements PipeTransform { transform(value: any) { return `|${value}`; } } @NgModule({ imports: [StandaloneCmp, StandaloneDir, StandalonePipe], exports: [StandaloneCmp, StandaloneDir, StandalonePipe], }) class LibModule {} @Component({ selector: 'app-cmpt', template: `<standalone-cmp standalone-dir></standalone-cmp>{{'standalone' | standalonePipe}}`, standalone: false, }) class AppComponent {} TestBed.configureTestingModule({ imports: [LibModule], declarations: [AppComponent], }); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('standalone|standalone'); expect(fixture.nativeElement.querySelector('standalone-cmp').getAttribute('id')).toBe( 'standalone', ); }); it('should render a standalone component with dependencies and ambient providers', () => { @Component({ standalone: true, template: 'Inner', selector: 'inner-cmp', }) class InnerCmp {} class Service { value = 'Service'; } @NgModule({providers: [Service]}) class ModuleWithAProvider {} @Component({ standalone: true, template: 'Outer<inner-cmp></inner-cmp>{{service.value}}', imports: [InnerCmp, ModuleWithAProvider], }) class OuterCmp { constructor(readonly service: Service) {} } const fixture = TestBed.createComponent(OuterCmp); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('Outer<inner-cmp>Inner</inner-cmp>Service'); }); it('should discover ambient providers from a standalone component', () => { class Service { value = 'Service'; } @NgModule({providers: [Service]}) class ModuleWithAProvider {} @Component({ standalone: true, template: 'Inner({{service.value}})', selector: 'inner-cmp', imports: [ModuleWithAProvider], }) class InnerCmp { constructor(readonly service: Service) {} } @Component({ standalone: true, template: 'Outer<inner-cmp></inner-cmp>{{service.value}}', imports: [InnerCmp], }) class OuterCmp { constructor(readonly service: Service) {} } const fixture = TestBed.createComponent(OuterCmp); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( 'Outer<inner-cmp>Inner(Service)</inner-cmp>Service', ); }); it('should correctly associate an injector with a standalone component def', () => { @Injectable() class MyServiceA {} @Injectable() class MyServiceB {} @NgModule({ providers: [MyServiceA], }) class MyModuleA {} @NgModule({ providers: [MyServiceB], }) class MyModuleB {} @Component({ selector: 'duplicate-selector', template: `ComponentA: {{ service ? 'service found' : 'service not found' }}`, standalone: true, imports: [MyModuleA], }) class ComponentA { service = inject(MyServiceA, {optional: true}); } @Component({ selector: 'duplicate-selector', template: `ComponentB: {{ service ? 'service found' : 'service not found' }}`, standalone: true, imports: [MyModuleB], }) class ComponentB { service = inject(MyServiceB, {optional: true}); } @Component({ selector: 'app-cmp', template: ` <ng-container [ngComponentOutlet]="ComponentA" /> <ng-container [ngComponentOutlet]="ComponentB" /> `, standalone: true, imports: [NgComponentOutlet], }) class AppCmp { ComponentA = ComponentA; ComponentB = ComponentB; } const fixture = TestBed.createComponent(AppCmp); fixture.detectChanges(); const textContent = fixture.nativeElement.textContent; expect(textContent).toContain('ComponentA: service found'); expect(textContent).toContain('ComponentB: service found'); }); it('should dynamically insert a standalone component', () => { class Service { value = 'Service'; } @NgModule({providers: [Service]}) class Module {} @Component({ standalone: true, template: 'Inner({{service.value}})', selector: 'inner-cmp', imports: [Module], }) class InnerCmp { constructor(readonly service: Service) {} } @Component({ standalone: true, template: '<ng-template #insert></ng-template>', imports: [InnerCmp], }) class AppCmp implements OnInit { @ViewChild('insert', {read: ViewContainerRef, static: true}) vcRef!: ViewContainerRef; ngOnInit(): void { this.vcRef.createComponent(InnerCmp); } } const fixture = TestBed.createComponent(AppCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Inner(Service)'); });
{ "end_byte": 8877, "start_byte": 603, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/standalone_spec.ts" }
angular/packages/core/test/acceptance/standalone_spec.ts_8881_17135
it('should dynamically insert a standalone component with ambient providers override in the "left / node" injector', () => { class Service { constructor(readonly value = 'Service') {} } class NodeOverrideService extends Service { constructor() { super('NodeOverrideService'); } } class EnvOverrideService extends Service { constructor() { super('EnvOverrideService'); } } @NgModule({providers: [Service]}) class Module {} @Component({ standalone: true, template: 'Inner({{service.value}})', selector: 'inner-cmp', imports: [Module], }) class InnerCmp { constructor(readonly service: Service) {} } @Component({ standalone: true, template: '<ng-template #insert></ng-template>', imports: [InnerCmp], }) class AppCmp implements OnInit { @ViewChild('insert', {read: ViewContainerRef, static: true}) vcRef!: ViewContainerRef; constructor( readonly inj: Injector, readonly envInj: EnvironmentInjector, ) {} ngOnInit(): void { const lhsInj = Injector.create({ providers: [{provide: Service, useClass: NodeOverrideService}], parent: this.inj, }); const rhsInj = createEnvironmentInjector( [{provide: Service, useClass: EnvOverrideService}], this.envInj, ); this.vcRef.createComponent(InnerCmp, {injector: lhsInj, environmentInjector: rhsInj}); } } const fixture = TestBed.createComponent(AppCmp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Inner(NodeOverrideService)'); }); it('should consult ambient providers before environment injector when inserting a component dynamically', () => { class Service { constructor(readonly value = 'Service') {} } class EnvOverrideService extends Service { constructor() { super('EnvOverrideService'); } } @NgModule({providers: [Service]}) class Module {} @Component({ standalone: true, template: 'Inner({{service.value}})', selector: 'inner-cmp', imports: [Module], }) class InnerCmp { constructor(readonly service: Service) {} } @Component({ standalone: true, template: '<ng-template #insert></ng-template>', imports: [InnerCmp], }) class AppCmp implements OnInit { @ViewChild('insert', {read: ViewContainerRef, static: true}) vcRef!: ViewContainerRef; constructor(readonly envInj: EnvironmentInjector) {} ngOnInit(): void { const rhsInj = createEnvironmentInjector( [{provide: Service, useClass: EnvOverrideService}], this.envInj, ); this.vcRef.createComponent(InnerCmp, {environmentInjector: rhsInj}); } } const fixture = TestBed.createComponent(AppCmp); fixture.detectChanges(); // The Service (an ambient provider) gets injected here as the standalone injector is a child // of the user-created environment injector. expect(fixture.nativeElement.textContent).toBe('Inner(Service)'); }); it('should render a recursive cycle of standalone components', () => { @Component({ selector: 'cmp-a', standalone: true, template: '<ng-template [ngIf]="false"><cmp-c></cmp-c></ng-template>A', imports: [forwardRef(() => StandaloneCmpC)], }) class StandaloneCmpA {} @Component({ selector: 'cmp-b', standalone: true, template: '(<cmp-a></cmp-a>)B', imports: [StandaloneCmpA], }) class StandaloneCmpB {} @Component({ selector: 'cmp-c', standalone: true, template: '(<cmp-b></cmp-b>)C', imports: [StandaloneCmpB], }) class StandaloneCmpC {} const fixture = TestBed.createComponent(StandaloneCmpC); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('((A)B)C'); }); it('should collect ambient providers from exported NgModule', () => { class Service { value = 'service'; } @NgModule({providers: [Service]}) class ModuleWithAService {} @NgModule({exports: [ModuleWithAService]}) class ExportingModule {} @Component({ selector: 'standalone', standalone: true, imports: [ExportingModule], template: `({{service.value}})`, }) class TestComponent { constructor(readonly service: Service) {} } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(service)'); }); it('should support nested arrays in @Component.imports', () => { @Directive({selector: '[red]', standalone: true, host: {'[attr.red]': 'true'}}) class RedIdDirective {} @Pipe({name: 'blue', pure: true, standalone: true}) class BluePipe implements PipeTransform { transform() { return 'blue'; } } @Component({ selector: 'standalone', standalone: true, template: `<div red>{{'' | blue}}</div>`, imports: [[RedIdDirective, [BluePipe]]], }) class TestComponent {} const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe('<div red="true">blue</div>'); }); it('should support readonly arrays in @Component.imports', () => { @Directive({selector: '[red]', standalone: true, host: {'[attr.red]': 'true'}}) class RedIdDirective {} @Pipe({name: 'blue', pure: true, standalone: true}) class BluePipe implements PipeTransform { transform() { return 'blue'; } } const DirAndPipe = [RedIdDirective, BluePipe] as const; @Component({ selector: 'standalone', standalone: true, template: `<div red>{{'' | blue}}</div>`, imports: [DirAndPipe], }) class TestComponent {} const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe('<div red="true">blue</div>'); }); it('should deduplicate declarations', () => { @Component({selector: 'test-red', standalone: true, template: 'red(<ng-content></ng-content>)'}) class RedComponent {} @Component({ selector: 'test-blue', standalone: false, template: 'blue(<ng-content></ng-content>)', }) class BlueComponent {} @NgModule({declarations: [BlueComponent], exports: [BlueComponent]}) class BlueModule {} @NgModule({exports: [BlueModule]}) class BlueAModule {} @NgModule({exports: [BlueModule]}) class BlueBModule {} @Component({ selector: 'standalone', standalone: true, template: `<test-red><test-blue>orange</test-blue></test-red>`, imports: [RedComponent, RedComponent, BlueAModule, BlueBModule], }) class TestComponent {} const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe( '<test-red>red(<test-blue>blue(orange)</test-blue>)</test-red>', ); }); it('should error when forwardRef does not resolve to a truthy value', () => { @Component({ selector: 'test', standalone: true, imports: [forwardRef(() => null)], template: '', }) class TestComponent {} expect(() => { TestBed.createComponent(TestComponent); }).toThrowError( 'Expected forwardRef function, imported from "TestComponent", to return a standalone entity or NgModule but got "null".', ); }); it('should error when a non-standalone component is imported', () => { @Component({ selector: 'not-a-standalone', template: '', standalone: false, }) class NonStandaloneCmp {} @Component({ selector: 'standalone', standalone: true, template: '', imports: [NonStandaloneCmp], }) class StandaloneCmp {} expect(() => { TestBed.createComponent(StandaloneCmp); }).toThrowError( 'The "NonStandaloneCmp" component, imported from "StandaloneCmp", is not standalone. Did you forget to add the standalone: true flag?', ); });
{ "end_byte": 17135, "start_byte": 8881, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/standalone_spec.ts" }
angular/packages/core/test/acceptance/standalone_spec.ts_17139_24450
it('should error when a non-standalone directive is imported', () => { @Directive({ selector: '[not-a-standalone]', standalone: false, }) class NonStandaloneDirective {} @Component({ selector: 'standalone', standalone: true, template: '', imports: [NonStandaloneDirective], }) class StandaloneCmp {} expect(() => { TestBed.createComponent(StandaloneCmp); }).toThrowError( 'The "NonStandaloneDirective" directive, imported from "StandaloneCmp", is not standalone. Did you forget to add the standalone: true flag?', ); }); it('should error when a non-standalone pipe is imported', () => { @Pipe({ name: 'not-a-standalone', standalone: false, }) class NonStandalonePipe {} @Component({ selector: 'standalone', standalone: true, template: '', imports: [NonStandalonePipe], }) class StandaloneCmp {} expect(() => { TestBed.createComponent(StandaloneCmp); }).toThrowError( 'The "NonStandalonePipe" pipe, imported from "StandaloneCmp", is not standalone. Did you forget to add the standalone: true flag?', ); }); it('should error when an unknown type is imported', () => { class SthElse {} @Component({ selector: 'standalone', standalone: true, template: '', imports: [SthElse], }) class StandaloneCmp {} expect(() => { TestBed.createComponent(StandaloneCmp); }).toThrowError( 'The "SthElse" type, imported from "StandaloneCmp", must be a standalone component / directive / pipe or an NgModule. Did you forget to add the required @Component / @Directive / @Pipe or @NgModule annotation?', ); }); it('should error when a module with providers is imported', () => { @NgModule() class OtherModule {} @NgModule() class LibModule { static forComponent() { return {ngModule: OtherModule}; } } @Component({ standalone: true, template: '', // we need to import a module with a provider in a nested array since module with providers // are disallowed on the type level imports: [[LibModule.forComponent()]], }) class StandaloneCmp {} expect(() => { TestBed.createComponent(StandaloneCmp); }).toThrowError( 'A module with providers was imported from "StandaloneCmp". Modules with providers are not supported in standalone components imports.', ); }); it('should support forwardRef imports', () => { @Component({ selector: 'test', standalone: true, imports: [forwardRef(() => StandaloneComponent)], template: `(<other-standalone></other-standalone>)`, }) class TestComponent {} @Component({selector: 'other-standalone', standalone: true, template: `standalone component`}) class StandaloneComponent {} const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('(standalone component)'); }); describe('schemas', () => { it('should allow schemas in standalone component', () => { @Component({ standalone: true, template: '<maybe-custom-elm></maybe-custom-elm>', schemas: [NO_ERRORS_SCHEMA], }) class AppCmp {} const fixture = TestBed.createComponent(AppCmp); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe('<maybe-custom-elm></maybe-custom-elm>'); }); it('should error when schemas are specified for a non-standalone component', () => { @Component({ template: '', schemas: [NO_ERRORS_SCHEMA], standalone: false, }) class AppCmp {} expect(() => { TestBed.createComponent(AppCmp); }).toThrowError( `The 'schemas' was specified for the AppCmp but is only valid on a component that is standalone.`, ); }); }); describe('unknown template elements', () => { const unknownElErrorRegex = (tag: string) => { const prefix = `'${tag}' is not a known element \\(used in the 'AppCmp' component template\\):`; const message1 = `1. If '${tag}' is an Angular component, then verify that it is included in the '@Component.imports' of this component.`; const message2 = `2. If '${tag}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@Component.schemas' of this component to suppress this message.`; return new RegExp(`${prefix}s*\ns*${message1}s*\ns*${message2}`); }; it('should warn the user when an unknown element is present', () => { const spy = spyOn(console, 'error'); @Component({ standalone: true, template: '<unknown-tag></unknown-tag>', }) class AppCmp {} TestBed.createComponent(AppCmp); const errorRegex = unknownElErrorRegex('unknown-tag'); expect(spy).toHaveBeenCalledOnceWith(jasmine.stringMatching(errorRegex)); }); it('should warn the user when multiple unknown elements are present', () => { const spy = spyOn(console, 'error'); @Component({ standalone: true, template: '<unknown-tag-A></unknown-tag-A><unknown-tag-B></unknown-tag-B>', }) class AppCmp {} TestBed.createComponent(AppCmp); const errorRegexA = unknownElErrorRegex('unknown-tag-A'); const errorRegexB = unknownElErrorRegex('unknown-tag-B'); expect(spy).toHaveBeenCalledWith(jasmine.stringMatching(errorRegexA)); expect(spy).toHaveBeenCalledWith(jasmine.stringMatching(errorRegexB)); }); it('should not warn the user when an unknown element is present inside an ng-template', () => { const spy = spyOn(console, 'error'); @Component({ standalone: true, template: '<ng-template><unknown-tag></unknown-tag><ng-template>', }) class AppCmp {} TestBed.createComponent(AppCmp); expect(spy).not.toHaveBeenCalled(); }); it('should warn the user when an unknown element is present in an instantiated embedded view', () => { const spy = spyOn(console, 'error'); @Component({ standalone: true, template: '<ng-template [ngIf]="true"><unknown-tag></unknown-tag><ng-template>', imports: [CommonModule], }) class AppCmp {} const fixture = TestBed.createComponent(AppCmp); fixture.detectChanges(); const errorRegex = unknownElErrorRegex('unknown-tag'); expect(spy).toHaveBeenCalledOnceWith(jasmine.stringMatching(errorRegex)); }); }); /* The following test verify that we don't impose limits when it comes to extending components of various type (standalone vs. non-standalone). This is based on the reasoning that the "template" / "templateUrl", "imports", "schemas" and "standalone" properties are all related and they specify how to compile a template. As of today extending a component means providing a new template and this implies providing compiler configuration for a new template. In this sense neither a template nor its compiler configuration is carried over from a class being extended (we can think of each component being a "fresh copy" when it comes to a template and its compiler configuration). */
{ "end_byte": 24450, "start_byte": 17139, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/standalone_spec.ts" }
angular/packages/core/test/acceptance/standalone_spec.ts_24453_29593
describe('inheritance', () => { it('should allow extending a regular component and turn it into a standalone one', () => { @Component({ selector: 'regular', template: 'regular: {{in}}', standalone: false, }) class RegularCmp { @Input() in: string | undefined; } @Component({selector: 'standalone', template: 'standalone: {{in}}', standalone: true}) class StandaloneCmp extends RegularCmp {} const fixture = TestBed.createComponent(StandaloneCmp); fixture.componentInstance.in = 'input value'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('standalone: input value'); }); it('should allow extending a regular component and turn it into a standalone one', () => { @Component({selector: 'standalone', template: 'standalone: {{in}}', standalone: true}) class StandaloneCmp { @Input() in: string | undefined; } @Component({ selector: 'regular', template: 'regular: {{in}}', standalone: false, }) class RegularCmp extends StandaloneCmp {} const fixture = TestBed.createComponent(RegularCmp); fixture.componentInstance.in = 'input value'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('regular: input value'); }); it('should ?', () => { @Component({ selector: 'inner', template: 'inner', standalone: true, }) class InnerCmp {} @Component({ selector: 'standalone', standalone: true, template: 'standalone: {{in}}; (<inner></inner>)', imports: [InnerCmp], }) class StandaloneCmp { @Input() in: string | undefined; } @Component({ selector: 'regular', standalone: false, }) class RegularCmp extends StandaloneCmp {} const fixture = TestBed.createComponent(RegularCmp); fixture.componentInstance.in = 'input value'; fixture.detectChanges(); // the assumption here is that not providing a template is equivalent to providing an empty // one expect(fixture.nativeElement.textContent).toBe(''); }); }); describe('isStandalone()', () => { it('should return `true` if component is standalone', () => { @Component({selector: 'standalone-cmp'}) class StandaloneCmp {} expect(isStandalone(StandaloneCmp)).toBeTrue(); }); it('should return `true` if component is standalone (with `standalone:true`)', () => { @Component({selector: 'standalone-cmp', standalone: true}) class StandaloneCmp {} expect(isStandalone(StandaloneCmp)).toBeTrue(); }); it('should return `false` if component is not standalone', () => { @Component({selector: 'standalone-cmp', standalone: false}) class StandaloneCmp {} expect(isStandalone(StandaloneCmp)).toBeFalse(); }); it('should return `true` if directive is standalone', () => { @Directive({selector: '[standaloneDir]', standalone: true}) class StandAloneDirective {} expect(isStandalone(StandAloneDirective)).toBeTrue(); }); it('should return `false` if directive is standalone', () => { @Directive({selector: '[standaloneDir]', standalone: false}) class StandAloneDirective {} expect(isStandalone(StandAloneDirective)).toBeFalse(); }); it('should return `true` if pipe is standalone', () => { @Pipe({name: 'standalonePipe', standalone: true}) class StandAlonePipe {} expect(isStandalone(StandAlonePipe)).toBeTrue(); }); it('should return `false` if pipe is standalone', () => { @Pipe({name: 'standalonePipe', standalone: false}) class StandAlonePipe {} expect(isStandalone(StandAlonePipe)).toBeFalse(); }); it('should return `false` if the class is not annotated', () => { class NonAnnotatedClass {} expect(isStandalone(NonAnnotatedClass)).toBeFalse(); }); it('should return `false` if the class is an NgModule', () => { @NgModule({}) class Module {} expect(isStandalone(Module)).toBeFalse(); }); it('should render a recursive cycle of standalone components', () => { @Component({ selector: 'cmp-a', standalone: true, template: '<ng-template [ngIf]="false"><cmp-c></cmp-c></ng-template>A', imports: [forwardRef(() => StandaloneCmpC)], }) class StandaloneCmpA {} @Component({ selector: 'cmp-b', standalone: true, template: '(<cmp-a></cmp-a>)B', imports: [StandaloneCmpA], }) class StandaloneCmpB {} @Component({ selector: 'cmp-c', standalone: true, template: '(<cmp-b></cmp-b>)C', imports: [StandaloneCmpB], }) class StandaloneCmpC {} TestBed.configureTestingModule({imports: [StandaloneCmpC]}); const fixture = TestBed.createComponent(StandaloneCmpC); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('((A)B)C'); }); }); });
{ "end_byte": 29593, "start_byte": 24453, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/standalone_spec.ts" }
angular/packages/core/test/acceptance/hmr_spec.ts_0_7738
/*! * @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, Directive, DoCheck, ElementRef, EventEmitter, inject, InjectionToken, Input, OnChanges, OnDestroy, OnInit, Output, QueryList, SimpleChanges, Type, ViewChild, ViewChildren, ɵNG_COMP_DEF, ɵɵreplaceMetadata, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {compileComponent} from '@angular/core/src/render3/jit/directive'; import {clearTranslations, loadTranslations} from '@angular/localize'; import {computeMsgId} from '@angular/compiler'; describe('hot module replacement', () => { it('should recreate a single usage of a basic component', () => { let instance!: ChildCmp; const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: 'Hello <strong>{{state}}</strong>', }; @Component(initialMetadata) class ChildCmp { state = 0; constructor() { instance = this; } } @Component({ standalone: true, imports: [ChildCmp], template: '<child-cmp/>', }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); markNodesAsCreatedInitially(fixture.nativeElement); expectHTML( fixture.nativeElement, ` <child-cmp> Hello <strong>0</strong> </child-cmp> `, ); instance.state = 1; fixture.detectChanges(); expectHTML( fixture.nativeElement, ` <child-cmp> Hello <strong>1</strong> </child-cmp> `, ); replaceMetadata(ChildCmp, { ...initialMetadata, template: `Changed <strong>{{state}}</strong>!`, }); fixture.detectChanges(); const recreatedNodes = childrenOf(...fixture.nativeElement.querySelectorAll('child-cmp')); verifyNodesRemainUntouched(fixture.nativeElement, recreatedNodes); verifyNodesWereRecreated(recreatedNodes); expectHTML( fixture.nativeElement, ` <child-cmp> Changed <strong>1</strong>! </child-cmp> `, ); }); it('should recreate multiple usages of a complex component', () => { const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: '<span>ChildCmp (orig)</span><h1>{{ text }}</h1>', }; @Component(initialMetadata) class ChildCmp { @Input() text = '[empty]'; } @Component({ standalone: true, imports: [ChildCmp], template: ` <i>Unrelated node #1</i> <child-cmp text="A"/> <u>Unrelated node #2</u> <child-cmp text="B"/> <b>Unrelated node #3</b> <main> <child-cmp text="C"/> </main> `, }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); markNodesAsCreatedInitially(fixture.nativeElement); expectHTML( fixture.nativeElement, ` <i>Unrelated node #1</i> <child-cmp text="A"> <span>ChildCmp (orig)</span><h1>A</h1> </child-cmp> <u>Unrelated node #2</u> <child-cmp text="B"> <span>ChildCmp (orig)</span><h1>B</h1> </child-cmp> <b>Unrelated node #3</b> <main> <child-cmp text="C"> <span>ChildCmp (orig)</span><h1>C</h1> </child-cmp> </main> `, ); replaceMetadata(ChildCmp, { ...initialMetadata, template: ` <p title="extra attr">ChildCmp (hmr)</p> <h2>{{ text }}</h2> <div>Extra node!</div> `, }); fixture.detectChanges(); const recreatedNodes = childrenOf(...fixture.nativeElement.querySelectorAll('child-cmp')); verifyNodesRemainUntouched(fixture.nativeElement, recreatedNodes); verifyNodesWereRecreated(recreatedNodes); expectHTML( fixture.nativeElement, ` <i>Unrelated node #1</i> <child-cmp text="A"> <p title="extra attr">ChildCmp (hmr)</p> <h2>A</h2> <div>Extra node!</div> </child-cmp> <u>Unrelated node #2</u> <child-cmp text="B"> <p title="extra attr">ChildCmp (hmr)</p> <h2>B</h2> <div>Extra node!</div> </child-cmp> <b>Unrelated node #3</b> <main> <child-cmp text="C"> <p title="extra attr">ChildCmp (hmr)</p> <h2>C</h2> <div>Extra node!</div> </child-cmp> </main> `, ); }); it('should not recreate sub-classes of a component being replaced', () => { const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: 'Base class', }; @Component(initialMetadata) class ChildCmp {} @Component({ selector: 'child-sub-cmp', standalone: true, template: 'Sub class', }) class ChildSubCmp extends ChildCmp {} @Component({ standalone: true, imports: [ChildCmp, ChildSubCmp], template: `<child-cmp/>|<child-sub-cmp/>`, }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expectHTML( fixture.nativeElement, ` <child-cmp>Base class</child-cmp>| <child-sub-cmp>Sub class</child-sub-cmp> `, ); replaceMetadata(ChildCmp, { ...initialMetadata, template: `Replaced!`, }); fixture.detectChanges(); expectHTML( fixture.nativeElement, ` <child-cmp>Replaced!</child-cmp>| <child-sub-cmp>Sub class</child-sub-cmp> `, ); }); it('should continue binding inputs to a component that is replaced', () => { const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: '<span>{{staticValue}}</span><strong>{{dynamicValue}}</strong>', }; @Component(initialMetadata) class ChildCmp { @Input() staticValue = '0'; @Input() dynamicValue = '0'; } @Component({ standalone: true, imports: [ChildCmp], template: `<child-cmp staticValue="1" [dynamicValue]="dynamicValue"/>`, }) class RootCmp { dynamicValue = '1'; } const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expectHTML( fixture.nativeElement, ` <child-cmp staticvalue="1"> <span>1</span> <strong>1</strong> </child-cmp> `, ); fixture.componentInstance.dynamicValue = '2'; fixture.detectChanges(); expectHTML( fixture.nativeElement, ` <child-cmp staticvalue="1"> <span>1</span> <strong>2</strong> </child-cmp> `, ); replaceMetadata(ChildCmp, { ...initialMetadata, template: ` <main> <span>{{staticValue}}</span> <strong>{{dynamicValue}}</strong> </main> `, }); fixture.detectChanges(); expectHTML( fixture.nativeElement, ` <child-cmp staticvalue="1"> <main> <span>1</span> <strong>2</strong> </main> </child-cmp> `, ); fixture.componentInstance.dynamicValue = '3'; fixture.detectChanges(); expectHTML( fixture.nativeElement, ` <child-cmp staticvalue="1"> <main> <span>1</span> <strong>3</strong> </main> </child-cmp> `, ); });
{ "end_byte": 7738, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/hmr_spec.ts" }
angular/packages/core/test/acceptance/hmr_spec.ts_7742_15358
'should recreate a component used inside @for', () => { const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: 'Hello <strong>{{value}}</strong>', }; @Component(initialMetadata) class ChildCmp { @Input() value = '[empty]'; } @Component({ standalone: true, imports: [ChildCmp], template: ` @for (current of items; track current.id) { <child-cmp [value]="current.name"/> <hr> } `, }) class RootCmp { items = [ {name: 'A', id: 1}, {name: 'B', id: 2}, {name: 'C', id: 3}, ]; } const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); markNodesAsCreatedInitially(fixture.nativeElement); expectHTML( fixture.nativeElement, ` <child-cmp>Hello <strong>A</strong></child-cmp> <hr> <child-cmp>Hello <strong>B</strong></child-cmp> <hr> <child-cmp>Hello <strong>C</strong></child-cmp> <hr> `, ); replaceMetadata(ChildCmp, { ...initialMetadata, template: `Changed <strong>{{value}}</strong>!`, }); fixture.detectChanges(); let recreatedNodes = childrenOf(...fixture.nativeElement.querySelectorAll('child-cmp')); verifyNodesRemainUntouched(fixture.nativeElement, recreatedNodes); verifyNodesWereRecreated(recreatedNodes); expectHTML( fixture.nativeElement, ` <child-cmp>Changed <strong>A</strong>!</child-cmp> <hr> <child-cmp>Changed <strong>B</strong>!</child-cmp> <hr> <child-cmp>Changed <strong>C</strong>!</child-cmp> <hr> `, ); fixture.componentInstance.items.pop(); fixture.detectChanges(); expectHTML( fixture.nativeElement, ` <child-cmp>Changed <strong>A</strong>!</child-cmp> <hr> <child-cmp>Changed <strong>B</strong>!</child-cmp> <hr> `, ); recreatedNodes = childrenOf(...fixture.nativeElement.querySelectorAll('child-cmp')); verifyNodesRemainUntouched(fixture.nativeElement, recreatedNodes); verifyNodesWereRecreated(recreatedNodes); }); describe('queries', () => { it('should update ViewChildren query results', async () => { @Component({ selector: 'child-cmp', standalone: true, template: '<span>ChildCmp {{ text }}</span>', }) class ChildCmp { @Input() text = '[empty]'; } let instance!: ParentCmp; const initialMetadata: Component = { standalone: true, selector: 'parent-cmp', imports: [ChildCmp], template: ` <child-cmp text="A"/> <child-cmp text="B"/> `, }; @Component(initialMetadata) class ParentCmp { @ViewChildren(ChildCmp) childCmps!: QueryList<ChildCmp>; constructor() { instance = this; } } @Component({ standalone: true, imports: [ParentCmp], template: `<parent-cmp/>`, }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); const initialComps = instance.childCmps.toArray().slice(); expect(initialComps.length).toBe(2); replaceMetadata(ParentCmp, { ...initialMetadata, template: ` <child-cmp text="A"/> <child-cmp text="B"/> <child-cmp text="C"/> <child-cmp text="D"/> `, }); fixture.detectChanges(); expect(instance.childCmps.length).toBe(4); expect(instance.childCmps.toArray().every((c) => !initialComps.includes(c))).toBe(true); }); it('should update ViewChild when the string points to a different element', async () => { let instance!: ParentCmp; const initialMetadata: Component = { standalone: true, selector: 'parent-cmp', template: ` <div> <span> <strong #ref></strong> </span> </div> `, }; @Component(initialMetadata) class ParentCmp { @ViewChild('ref') ref!: ElementRef<HTMLElement>; constructor() { instance = this; } } @Component({ standalone: true, imports: [ParentCmp], template: `<parent-cmp/>`, }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(instance.ref.nativeElement.tagName).toBe('STRONG'); replaceMetadata(ParentCmp, { ...initialMetadata, template: ` <div> <span> <strong></strong> </span> </div> <main> <span #ref></span> </main> `, }); fixture.detectChanges(); expect(instance.ref.nativeElement.tagName).toBe('SPAN'); }); it('should update ViewChild when the injection token points to a different directive', async () => { const token = new InjectionToken<DirA | DirB>('token'); @Directive({ standalone: true, selector: '[dir-a]', providers: [{provide: token, useExisting: DirA}], }) class DirA {} @Directive({ standalone: true, selector: '[dir-b]', providers: [{provide: token, useExisting: DirB}], }) class DirB {} let instance!: ParentCmp; const initialMetadata: Component = { standalone: true, selector: 'parent-cmp', imports: [DirA, DirB], template: `<div #ref dir-a></div>`, }; @Component(initialMetadata) class ParentCmp { @ViewChild('ref', {read: token}) ref!: DirA | DirB; constructor() { instance = this; } } @Component({ standalone: true, imports: [ParentCmp], template: `<parent-cmp/>`, }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(instance.ref).toBeInstanceOf(DirA); replaceMetadata(ParentCmp, { ...initialMetadata, template: ` <section> <div #ref dir-b></div> </section> `, }); fixture.detectChanges(); expect(instance.ref).toBeInstanceOf(DirB); }); it('should update ViewChild when the injection token stops pointing to anything', async () => { const token = new InjectionToken<Dir>('token'); @Directive({ standalone: true, selector: '[dir]', providers: [{provide: token, useExisting: Dir}], }) class Dir {} let instance!: ParentCmp; const initialMetadata: Component = { standalone: true, selector: 'parent-cmp', imports: [Dir], template: `<div #ref dir></div>`, }; @Component(initialMetadata) class ParentCmp { @ViewChild('ref', {read: token}) ref!: Dir; constructor() { instance = this; } } @Component({ standalone: true, imports: [ParentCmp], template: `<parent-cmp/>`, }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(instance.ref).toBeInstanceOf(Dir); replaceMetadata(ParentCmp, { ...initialMetadata, template: `<div #ref></div>`, }); fixture.detectChanges(); expect(instance.ref).toBeFalsy(); }); });
{ "end_byte": 15358, "start_byte": 7742, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/hmr_spec.ts" }
angular/packages/core/test/acceptance/hmr_spec.ts_15362_21020
cribe('content projection', () => { it('should work with content projection', () => { const initialMetadata: Component = { standalone: true, selector: 'parent-cmp', template: `<ng-content/>`, }; @Component(initialMetadata) class ParentCmp {} @Component({ standalone: true, imports: [ParentCmp], template: ` <parent-cmp> <h1>Projected H1</h1> <h2>Projected H2</h2> </parent-cmp> `, }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); markNodesAsCreatedInitially(fixture.nativeElement); expectHTML( fixture.nativeElement, ` <parent-cmp> <h1>Projected H1</h1> <h2>Projected H2</h2> </parent-cmp> `, ); replaceMetadata(ParentCmp, { ...initialMetadata, template: ` <section> <ng-content/> </section> `, }); fixture.detectChanges(); // <h1> and <h2> nodes were not re-created, since they // belong to a parent component, which wasn't HMR'ed. verifyNodesRemainUntouched(fixture.nativeElement.querySelector('h1')); verifyNodesRemainUntouched(fixture.nativeElement.querySelector('h2')); verifyNodesWereRecreated(fixture.nativeElement.querySelectorAll('section')); expectHTML( fixture.nativeElement, ` <parent-cmp> <section> <h1>Projected H1</h1> <h2>Projected H2</h2> </section> </parent-cmp> `, ); }); it('should handle elements moving around into different slots', () => { // Start off with a single catch-all slot. const initialMetadata: Component = { standalone: true, selector: 'parent-cmp', template: `<ng-content/>`, }; @Component(initialMetadata) class ParentCmp {} @Component({ standalone: true, imports: [ParentCmp], template: ` <parent-cmp> <div one="1">one</div> <div two="2">two</div> </parent-cmp> `, }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); markNodesAsCreatedInitially(fixture.nativeElement); expectHTML( fixture.nativeElement, ` <parent-cmp> <div one="1">one</div> <div two="2">two</div> </parent-cmp> `, ); // Swap out the catch-all slot with two specific slots. // Note that we also changed the order of `one` and `two`. replaceMetadata(ParentCmp, { ...initialMetadata, template: ` <section><ng-content select="[two]"/></section> <main><ng-content select="[one]"/></main> `, }); fixture.detectChanges(); verifyNodesRemainUntouched(fixture.nativeElement.querySelector('[one]')); verifyNodesRemainUntouched(fixture.nativeElement.querySelector('[two]')); verifyNodesWereRecreated(fixture.nativeElement.querySelectorAll('section, main')); expectHTML( fixture.nativeElement, ` <parent-cmp> <section><div two="2">two</div></section> <main><div one="1">one</div></main> </parent-cmp> `, ); // Swap with a slot that matches nothing. replaceMetadata(ParentCmp, { ...initialMetadata, template: `<ng-content select="does-not-match"/>`, }); fixture.detectChanges(); expectHTML(fixture.nativeElement, '<parent-cmp></parent-cmp>'); // Swap with a slot that only one of the nodes matches. replaceMetadata(ParentCmp, { ...initialMetadata, template: `<span><ng-content select="[one]"/></span>`, }); fixture.detectChanges(); expectHTML( fixture.nativeElement, ` <parent-cmp> <span><div one="1">one</div></span> </parent-cmp> `, ); verifyNodesRemainUntouched(fixture.nativeElement.querySelector('[one]')); verifyNodesWereRecreated(fixture.nativeElement.querySelectorAll('span')); }); it('should handle default content for ng-content', () => { const initialMetadata: Component = { standalone: true, selector: 'parent-cmp', template: ` <ng-content select="will-not-match"> <div class="default-content">Default content</div> </ng-content> `, }; @Component(initialMetadata) class ParentCmp {} @Component({ standalone: true, imports: [ParentCmp], template: ` <parent-cmp> <span>Some content</span> </parent-cmp> `, }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expectHTML( fixture.nativeElement, ` <parent-cmp> <div class="default-content">Default content</div> </parent-cmp> `, ); replaceMetadata(ParentCmp, { ...initialMetadata, template: ` <ng-content> <div class="default-content">Default content</div> </ng-content> `, }); fixture.detectChanges(); expectHTML( fixture.nativeElement, ` <parent-cmp> <span>Some content</span> </parent-cmp> `, ); }); });
{ "end_byte": 21020, "start_byte": 15362, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/hmr_spec.ts" }
angular/packages/core/test/acceptance/hmr_spec.ts_21024_27927
cribe('lifecycle hooks', () => { it('should only invoke the init/destroy hooks inside the content when replacing the template', () => { @Component({ template: '', standalone: true, selector: 'child-cmp', }) class ChildCmp implements OnInit, OnDestroy { @Input() text = '[empty]'; ngOnInit() { logs.push(`ChildCmp ${this.text} init`); } ngOnDestroy() { logs.push(`ChildCmp ${this.text} destroy`); } } const initialMetadata: Component = { standalone: true, template: ` <child-cmp text="A"/> <child-cmp text="B"/> `, imports: [ChildCmp], selector: 'parent-cmp', }; let logs: string[] = []; @Component(initialMetadata) class ParentCmp implements OnInit, OnDestroy { @Input() text = '[empty]'; ngOnInit() { logs.push(`ParentCmp ${this.text} init`); } ngOnDestroy() { logs.push(`ParentCmp ${this.text} destroy`); } } @Component({ // Note that we test two of the same component one after the other // specifically because during testing it was a problematic pattern. template: ` <parent-cmp text="A"/> <parent-cmp text="B"/> `, standalone: true, imports: [ParentCmp], }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(logs).toEqual([ 'ParentCmp A init', 'ParentCmp B init', 'ChildCmp A init', 'ChildCmp B init', 'ChildCmp A init', 'ChildCmp B init', ]); logs = []; replaceMetadata(ParentCmp, { ...initialMetadata, template: ` <child-cmp text="C"/> <child-cmp text="D"/> <child-cmp text="E"/> `, }); fixture.detectChanges(); expect(logs).toEqual([ 'ChildCmp A destroy', 'ChildCmp B destroy', 'ChildCmp C init', 'ChildCmp D init', 'ChildCmp E init', 'ChildCmp A destroy', 'ChildCmp B destroy', 'ChildCmp C init', 'ChildCmp D init', 'ChildCmp E init', ]); logs = []; replaceMetadata(ParentCmp, { ...initialMetadata, template: '', }); fixture.detectChanges(); expect(logs).toEqual([ 'ChildCmp C destroy', 'ChildCmp D destroy', 'ChildCmp E destroy', 'ChildCmp C destroy', 'ChildCmp D destroy', 'ChildCmp E destroy', ]); }); it('should invoke checked hooks both on the host and the content being replaced', () => { @Component({ template: '', standalone: true, selector: 'child-cmp', }) class ChildCmp implements DoCheck { @Input() text = '[empty]'; ngDoCheck() { logs.push(`ChildCmp ${this.text} checked`); } } const initialMetadata: Component = { standalone: true, template: `<child-cmp text="A"/>`, imports: [ChildCmp], selector: 'parent-cmp', }; let logs: string[] = []; @Component(initialMetadata) class ParentCmp implements DoCheck { ngDoCheck() { logs.push(`ParentCmp checked`); } } @Component({ template: `<parent-cmp/>`, standalone: true, imports: [ParentCmp], }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(logs).toEqual(['ParentCmp checked', 'ChildCmp A checked']); fixture.detectChanges(); expect(logs).toEqual([ 'ParentCmp checked', 'ChildCmp A checked', 'ParentCmp checked', 'ChildCmp A checked', ]); logs = []; replaceMetadata(ParentCmp, { ...initialMetadata, template: '', }); fixture.detectChanges(); expect(logs).toEqual(['ParentCmp checked']); fixture.detectChanges(); expect(logs).toEqual(['ParentCmp checked', 'ParentCmp checked']); logs = []; replaceMetadata(ParentCmp, { ...initialMetadata, template: ` <child-cmp text="A"/> <child-cmp text="B"/> `, }); fixture.detectChanges(); expect(logs).toEqual([ 'ChildCmp A checked', 'ChildCmp B checked', 'ParentCmp checked', 'ChildCmp A checked', 'ChildCmp B checked', ]); fixture.detectChanges(); expect(logs).toEqual([ 'ChildCmp A checked', 'ChildCmp B checked', 'ParentCmp checked', 'ChildCmp A checked', 'ChildCmp B checked', 'ParentCmp checked', 'ChildCmp A checked', 'ChildCmp B checked', ]); }); it('should dispatch ngOnChanges on a replaced component', () => { const values: string[] = []; const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: '', }; @Component(initialMetadata) class ChildCmp implements OnChanges { @Input() value = 0; ngOnChanges(changes: SimpleChanges) { const change = changes['value']; values.push( `${change.previousValue} - ${change.currentValue} - ${change.isFirstChange()}`, ); } } @Component({ standalone: true, imports: [ChildCmp], template: `<child-cmp [value]="value"/>`, }) class RootCmp { value = 1; } const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(values).toEqual(['undefined - 1 - true']); fixture.componentInstance.value++; fixture.detectChanges(); expect(values).toEqual(['undefined - 1 - true', '1 - 2 - false']); replaceMetadata(ChildCmp, { ...initialMetadata, template: 'Changed', }); fixture.detectChanges(); fixture.componentInstance.value++; fixture.detectChanges(); expect(values).toEqual(['undefined - 1 - true', '1 - 2 - false', '2 - 3 - false']); fixture.componentInstance.value++; fixture.detectChanges(); expect(values).toEqual([ 'undefined - 1 - true', '1 - 2 - false', '2 - 3 - false', '3 - 4 - false', ]); replaceMetadata(ChildCmp, { ...initialMetadata, template: 'Changed!!!', }); fixture.detectChanges(); fixture.componentInstance.value++; fixture.detectChanges(); expect(values).toEqual([ 'undefined - 1 - true', '1 - 2 - false', '2 - 3 - false', '3 - 4 - false', '4 - 5 - false', ]); }); });
{ "end_byte": 27927, "start_byte": 21024, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/hmr_spec.ts" }
angular/packages/core/test/acceptance/hmr_spec.ts_27931_34351
cribe('event listeners', () => { it('should continue emitting to output after component has been replaced', () => { let count = 0; const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: '<button (click)="clicked()"></button>', }; @Component(initialMetadata) class ChildCmp { @Output() changed = new EventEmitter(); clicked() { this.changed.emit(); } } @Component({ standalone: true, imports: [ChildCmp], template: `<child-cmp (changed)="onChange()"/>`, }) class RootCmp { onChange() { count++; } } const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); markNodesAsCreatedInitially(fixture.nativeElement); expect(count).toBe(0); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); expect(count).toBe(1); replaceMetadata(ChildCmp, { ...initialMetadata, template: '<button class="replacement" (click)="clicked()"></button>', }); fixture.detectChanges(); const recreatedNodes = childrenOf(...fixture.nativeElement.querySelectorAll('child-cmp')); verifyNodesRemainUntouched(fixture.nativeElement, recreatedNodes); verifyNodesWereRecreated(recreatedNodes); fixture.nativeElement.querySelector('.replacement').click(); fixture.detectChanges(); expect(count).toBe(2); }); it('should stop emitting if replaced with an element that no longer has the listener', () => { let count = 0; const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: '<button (click)="clicked()"></button>', }; @Component(initialMetadata) class ChildCmp { @Output() changed = new EventEmitter(); clicked() { this.changed.emit(); } } @Component({ standalone: true, imports: [ChildCmp], template: `<child-cmp (changed)="onChange()"/>`, }) class RootCmp { onChange() { count++; } } const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); markNodesAsCreatedInitially(fixture.nativeElement); expect(count).toBe(0); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); expect(count).toBe(1); replaceMetadata(ChildCmp, { ...initialMetadata, template: '<button (click)="clicked()"></button>', }); fixture.detectChanges(); const recreatedNodes = childrenOf(...fixture.nativeElement.querySelectorAll('child-cmp')); verifyNodesRemainUntouched(fixture.nativeElement, recreatedNodes); verifyNodesWereRecreated(recreatedNodes); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); expect(count).toBe(2); }); }); describe('directives', () => { it('should not destroy template-matched directives on a component being replaced', () => { const initLog: string[] = []; let destroyCount = 0; const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: '', }; @Component(initialMetadata) class ChildCmp implements OnDestroy { constructor() { initLog.push('ChildCmp init'); } ngOnDestroy() { destroyCount++; } } @Directive({selector: '[dir-a]', standalone: true}) class DirA implements OnDestroy { constructor() { initLog.push('DirA init'); } ngOnDestroy() { destroyCount++; } } @Directive({selector: '[dir-b]', standalone: true}) class DirB implements OnDestroy { constructor() { initLog.push('DirB init'); } ngOnDestroy() { destroyCount++; } } @Component({ standalone: true, imports: [ChildCmp, DirA, DirB], template: `<child-cmp dir-a dir-b/>`, }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); markNodesAsCreatedInitially(fixture.nativeElement); expect(initLog).toEqual(['ChildCmp init', 'DirA init', 'DirB init']); expect(destroyCount).toBe(0); replaceMetadata(ChildCmp, { ...initialMetadata, template: 'Hello!', }); fixture.detectChanges(); expect(initLog).toEqual(['ChildCmp init', 'DirA init', 'DirB init']); expect(destroyCount).toBe(0); }); it('should not destroy host directives on a component being replaced', () => { const initLog: string[] = []; let destroyCount = 0; @Directive({selector: '[dir-a]', standalone: true}) class DirA implements OnDestroy { constructor() { initLog.push('DirA init'); } ngOnDestroy() { destroyCount++; } } @Directive({selector: '[dir-b]', standalone: true}) class DirB implements OnDestroy { constructor() { initLog.push('DirB init'); } ngOnDestroy() { destroyCount++; } } const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: '', hostDirectives: [DirA, DirB], }; @Component(initialMetadata) class ChildCmp implements OnDestroy { constructor() { initLog.push('ChildCmp init'); } ngOnDestroy() { destroyCount++; } } @Component({ standalone: true, imports: [ChildCmp], template: '<child-cmp/>', }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); markNodesAsCreatedInitially(fixture.nativeElement); expect(initLog).toEqual(['DirA init', 'DirB init', 'ChildCmp init']); expect(destroyCount).toBe(0); replaceMetadata(ChildCmp, { ...initialMetadata, template: 'Hello!', }); fixture.detectChanges(); expect(initLog).toEqual(['DirA init', 'DirB init', 'ChildCmp init']); expect(destroyCount).toBe(0); }); });
{ "end_byte": 34351, "start_byte": 27931, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/hmr_spec.ts" }
angular/packages/core/test/acceptance/hmr_spec.ts_34355_38807
cribe('dependency injection', () => { it('should be able to inject a component that is replaced', () => { let instance!: ChildCmp; const injectedInstances: [unknown, ChildCmp][] = []; @Directive({selector: '[dir-a]', standalone: true}) class DirA { constructor() { injectedInstances.push([this, inject(ChildCmp)]); } } @Directive({selector: '[dir-b]', standalone: true}) class DirB { constructor() { injectedInstances.push([this, inject(ChildCmp)]); } } const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: '<div dir-a></div>', imports: [DirA, DirB], }; @Component(initialMetadata) class ChildCmp { constructor() { instance = this; } } @Component({ standalone: true, imports: [ChildCmp], template: '<child-cmp/>', }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(instance).toBeInstanceOf(ChildCmp); expect(injectedInstances).toEqual([[jasmine.any(DirA), instance]]); replaceMetadata(ChildCmp, { ...initialMetadata, template: '<div dir-b></div>', }); fixture.detectChanges(); expect(injectedInstances).toEqual([ [jasmine.any(DirA), instance], [jasmine.any(DirB), instance], ]); }); it('should be able to inject a token coming from a component that is replaced', () => { const token = new InjectionToken<string>('TEST_TOKEN'); const injectedValues: [unknown, string][] = []; @Directive({selector: '[dir-a]', standalone: true}) class DirA { constructor() { injectedValues.push([this, inject(token)]); } } @Directive({selector: '[dir-b]', standalone: true}) class DirB { constructor() { injectedValues.push([this, inject(token)]); } } const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: '<div dir-a></div>', imports: [DirA, DirB], providers: [{provide: token, useValue: 'provided value'}], }; @Component(initialMetadata) class ChildCmp {} @Component({ standalone: true, imports: [ChildCmp], template: '<child-cmp/>', }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(injectedValues).toEqual([[jasmine.any(DirA), 'provided value']]); replaceMetadata(ChildCmp, { ...initialMetadata, template: '<div dir-b></div>', }); fixture.detectChanges(); expect(injectedValues).toEqual([ [jasmine.any(DirA), 'provided value'], [jasmine.any(DirB), 'provided value'], ]); }); it('should be able to access the viewProviders of a component that is being replaced', () => { const token = new InjectionToken<string>('TEST_TOKEN'); const injectedValues: [unknown, string][] = []; @Directive({selector: '[dir-a]', standalone: true}) class DirA { constructor() { injectedValues.push([this, inject(token)]); } } @Directive({selector: '[dir-b]', standalone: true}) class DirB { constructor() { injectedValues.push([this, inject(token)]); } } const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: '<div dir-a></div>', imports: [DirA, DirB], viewProviders: [{provide: token, useValue: 'provided value'}], }; @Component(initialMetadata) class ChildCmp {} @Component({ standalone: true, imports: [ChildCmp], template: '<child-cmp/>', }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expect(injectedValues).toEqual([[jasmine.any(DirA), 'provided value']]); replaceMetadata(ChildCmp, { ...initialMetadata, template: '<div dir-b></div>', }); fixture.detectChanges(); expect(injectedValues).toEqual([ [jasmine.any(DirA), 'provided value'], [jasmine.any(DirB), 'provided value'], ]); }); });
{ "end_byte": 38807, "start_byte": 34355, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/hmr_spec.ts" }
angular/packages/core/test/acceptance/hmr_spec.ts_38811_43229
cribe('host bindings', () => { it('should maintain attribute host bindings on a replaced component', () => { const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: 'Hello', host: { '[attr.bar]': 'state', }, }; @Component(initialMetadata) class ChildCmp { @Input() state = 0; } @Component({ standalone: true, imports: [ChildCmp], template: `<child-cmp [state]="state" [attr.foo]="'The state is ' + state"/>`, }) class RootCmp { state = 0; } const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expectHTML( fixture.nativeElement, `<child-cmp foo="The state is 0" bar="0">Hello</child-cmp>`, ); fixture.componentInstance.state = 1; fixture.detectChanges(); expectHTML( fixture.nativeElement, `<child-cmp foo="The state is 1" bar="1">Hello</child-cmp>`, ); replaceMetadata(ChildCmp, {...initialMetadata, template: `Changed`}); fixture.detectChanges(); expectHTML( fixture.nativeElement, `<child-cmp foo="The state is 1" bar="1">Changed</child-cmp>`, ); fixture.componentInstance.state = 2; fixture.detectChanges(); expectHTML( fixture.nativeElement, `<child-cmp foo="The state is 2" bar="2">Changed</child-cmp>`, ); }); it('should maintain class host bindings on a replaced component', () => { const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: 'Hello', host: { '[class.bar]': 'state', }, }; @Component(initialMetadata) class ChildCmp { @Input() state = false; } @Component({ standalone: true, imports: [ChildCmp], template: `<child-cmp class="static" [state]="state" [class.foo]="state"/>`, }) class RootCmp { state = false; } const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expectHTML(fixture.nativeElement, `<child-cmp class="static">Hello</child-cmp>`); fixture.componentInstance.state = true; fixture.detectChanges(); expectHTML(fixture.nativeElement, `<child-cmp class="static foo bar">Hello</child-cmp>`); replaceMetadata(ChildCmp, {...initialMetadata, template: `Changed`}); fixture.detectChanges(); expectHTML(fixture.nativeElement, `<child-cmp class="static foo bar">Changed</child-cmp>`); fixture.componentInstance.state = false; fixture.detectChanges(); expectHTML(fixture.nativeElement, `<child-cmp class="static">Changed</child-cmp>`); }); it('should maintain style host bindings on a replaced component', () => { const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: 'Hello', host: { '[style.height]': 'state ? "5px" : "20px"', }, }; @Component(initialMetadata) class ChildCmp { @Input() state = false; } @Component({ standalone: true, imports: [ChildCmp], template: `<child-cmp style="opacity: 0.5;" [state]="state" [style.width]="state ? '3px' : '12px'"/>`, }) class RootCmp { state = false; } const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expectHTML( fixture.nativeElement, `<child-cmp style="opacity: 0.5; width: 12px; height: 20px;">Hello</child-cmp>`, ); fixture.componentInstance.state = true; fixture.detectChanges(); expectHTML( fixture.nativeElement, `<child-cmp style="opacity: 0.5; width: 3px; height: 5px;">Hello</child-cmp>`, ); replaceMetadata(ChildCmp, {...initialMetadata, template: `Changed`}); fixture.detectChanges(); expectHTML( fixture.nativeElement, `<child-cmp style="opacity: 0.5; width: 3px; height: 5px;">Changed</child-cmp>`, ); fixture.componentInstance.state = false; fixture.detectChanges(); expectHTML( fixture.nativeElement, `<child-cmp style="opacity: 0.5; width: 12px; height: 20px;">Changed</child-cmp>`, ); }); });
{ "end_byte": 43229, "start_byte": 38811, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/hmr_spec.ts" }
angular/packages/core/test/acceptance/hmr_spec.ts_43233_50808
cribe('i18n', () => { afterEach(() => { clearTranslations(); }); it('should replace components that use i18n within their template', () => { loadTranslations({ [computeMsgId('hello')]: 'здравей', [computeMsgId('goodbye')]: 'довиждане', }); const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: '<span i18n>hello</span>', }; @Component(initialMetadata) class ChildCmp {} @Component({ standalone: true, imports: [ChildCmp], template: '<child-cmp/>', }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expectHTML(fixture.nativeElement, '<child-cmp><span>здравей</span></child-cmp>'); replaceMetadata(ChildCmp, {...initialMetadata, template: '<strong i18n>goodbye</strong>!'}); fixture.detectChanges(); expectHTML(fixture.nativeElement, '<child-cmp><strong>довиждане</strong>!</child-cmp>'); }); it('should replace components that use i18n in their projected content', () => { loadTranslations({[computeMsgId('hello')]: 'здравей'}); const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: '<ng-content/>', }; @Component(initialMetadata) class ChildCmp {} @Component({ standalone: true, imports: [ChildCmp], template: `<child-cmp i18n>hello</child-cmp>`, }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); markNodesAsCreatedInitially(fixture.nativeElement); expectHTML(fixture.nativeElement, '<child-cmp>здравей</child-cmp>'); replaceMetadata(ChildCmp, { ...initialMetadata, template: 'Hello translates to <strong><ng-content/></strong>!', }); fixture.detectChanges(); const recreatedNodes = childrenOf(...fixture.nativeElement.querySelectorAll('child-cmp')); verifyNodesRemainUntouched(fixture.nativeElement, recreatedNodes); verifyNodesWereRecreated(recreatedNodes); expectHTML( fixture.nativeElement, '<child-cmp>Hello translates to <strong>здравей</strong>!</child-cmp>', ); }); it('should replace components that use i18n with interpolations', () => { loadTranslations({ [computeMsgId('hello')]: 'здравей', [computeMsgId('Hello {$INTERPOLATION}!')]: 'Здравей {$INTERPOLATION}!', }); let instance!: ChildCmp; const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: '<span i18n>Hello {{name}}!</span>', }; @Component(initialMetadata) class ChildCmp { name = 'Frodo'; constructor() { instance = this; } } @Component({ standalone: true, imports: [ChildCmp], template: '<child-cmp/>', }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expectHTML(fixture.nativeElement, '<child-cmp><span>Здравей Frodo!</span></child-cmp>'); replaceMetadata(ChildCmp, {...initialMetadata, template: '<strong i18n>hello</strong>'}); fixture.detectChanges(); expectHTML(fixture.nativeElement, '<child-cmp><strong>здравей</strong></child-cmp>'); replaceMetadata(ChildCmp, { ...initialMetadata, template: '<main><section i18n>Hello {{name}}!</section></main>', }); fixture.detectChanges(); expectHTML( fixture.nativeElement, '<child-cmp><main><section>Здравей Frodo!</section></main></child-cmp>', ); instance.name = 'Bilbo'; fixture.detectChanges(); expectHTML( fixture.nativeElement, '<child-cmp><main><section>Здравей Bilbo!</section></main></child-cmp>', ); }); it('should replace components that use i18n with interpolations in their projected content', () => { loadTranslations({ [computeMsgId('Hello {$INTERPOLATION}!')]: 'Здравей {$INTERPOLATION}!', }); const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: '<ng-content/>', }; @Component(initialMetadata) class ChildCmp {} @Component({ standalone: true, imports: [ChildCmp], template: '<child-cmp i18n>Hello {{name}}!</child-cmp>', }) class RootCmp { name = 'Frodo'; } const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); markNodesAsCreatedInitially(fixture.nativeElement); expectHTML(fixture.nativeElement, '<child-cmp>Здравей Frodo!</child-cmp>'); replaceMetadata(ChildCmp, { ...initialMetadata, template: 'The text translates to <strong><ng-content/></strong>!', }); fixture.detectChanges(); expectHTML( fixture.nativeElement, '<child-cmp>The text translates to <strong>Здравей Frodo!</strong>!</child-cmp>', ); const recreatedNodes = childrenOf(...fixture.nativeElement.querySelectorAll('child-cmp')); verifyNodesRemainUntouched(fixture.nativeElement, recreatedNodes); verifyNodesWereRecreated(recreatedNodes); fixture.componentInstance.name = 'Bilbo'; fixture.detectChanges(); expectHTML( fixture.nativeElement, '<child-cmp>The text translates to <strong>Здравей Bilbo!</strong>!</child-cmp>', ); }); it('should replace components that use i18n with ICUs', () => { loadTranslations({ [computeMsgId('hello')]: 'здравей', [computeMsgId('{VAR_SELECT, select, 10 {ten} 20 {twenty} other {other}}')]: '{VAR_SELECT, select, 10 {десет} 20 {двадесет} other {друго}}', }); let instance!: ChildCmp; const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: '<span i18n>{count, select, 10 {ten} 20 {twenty} other {other}}</span>', }; @Component(initialMetadata) class ChildCmp { count = 10; constructor() { instance = this; } } @Component({ standalone: true, imports: [ChildCmp], template: '<child-cmp/>', }) class RootCmp {} const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); expectHTML(fixture.nativeElement, '<child-cmp><span>десет</span></child-cmp>'); replaceMetadata(ChildCmp, {...initialMetadata, template: '<strong i18n>hello</strong>'}); fixture.detectChanges(); expectHTML(fixture.nativeElement, '<child-cmp><strong>здравей</strong></child-cmp>'); replaceMetadata(ChildCmp, { ...initialMetadata, template: '<main><section i18n>{count, select, 10 {ten} 20 {twenty} other {other}}</section></main>', }); fixture.detectChanges(); expectHTML( fixture.nativeElement, '<child-cmp><main><section>десет</section></main></child-cmp>', ); instance.count = 20; fixture.detectChanges(); expectHTML( fixture.nativeElement, '<child-cmp><main><section>двадесет</section></main></child-cmp>', ); }); it('should replace components that use i18n with ICUs in their projected content', () => { loadTranslations({ [computeMsgId('{VAR_SELECT, select, 10 {ten} 2
{ "end_byte": 50808, "start_byte": 43233, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/hmr_spec.ts" }
angular/packages/core/test/acceptance/hmr_spec.ts_50814_55579
nty} other {other}}')]: '{VAR_SELECT, select, 10 {десет} 20 {двадесет} other {друго}}', }); const initialMetadata: Component = { selector: 'child-cmp', standalone: true, template: '<ng-content/>', }; @Component(initialMetadata) class ChildCmp {} @Component({ standalone: true, imports: [ChildCmp], template: '<child-cmp i18n>{count, select, 10 {ten} 20 {twenty} other {other}}</child-cmp>', }) class RootCmp { count = 10; } const fixture = TestBed.createComponent(RootCmp); fixture.detectChanges(); markNodesAsCreatedInitially(fixture.nativeElement); expectHTML(fixture.nativeElement, '<child-cmp>десет</child-cmp>'); replaceMetadata(ChildCmp, { ...initialMetadata, template: 'The text translates to <strong><ng-content/></strong>!', }); fixture.detectChanges(); const recreatedNodes = childrenOf(...fixture.nativeElement.querySelectorAll('child-cmp')); verifyNodesRemainUntouched(fixture.nativeElement, recreatedNodes); verifyNodesWereRecreated(recreatedNodes); expectHTML( fixture.nativeElement, '<child-cmp>The text translates to <strong>десет</strong>!</child-cmp>', ); fixture.componentInstance.count = 20; fixture.detectChanges(); expectHTML( fixture.nativeElement, '<child-cmp>The text translates to <strong>двадесет</strong>!</child-cmp>', ); }); }); // Testing utilities // Field that we'll monkey-patch onto DOM elements that were created // initially, so that we can verify that some nodes were *not* re-created // during HMR operation. We do it for *testing* purposes only. const CREATED_INITIALLY_MARKER = '__ngCreatedInitially__'; function replaceMetadata(type: Type<unknown>, metadata: Component) { ɵɵreplaceMetadata(type, () => { // TODO: the content of this callback is a hacky workaround to invoke the compiler in a test. // in reality the callback will be generated by the compiler to be something along the lines // of `MyComp[ɵcmp] = /* metadata */`. // TODO: in reality this callback should also include `setClassMetadata` and // `setClassDebugInfo`. (type as any)[ɵNG_COMP_DEF] = null; compileComponent(type, metadata); }, []); } function expectHTML(element: HTMLElement, expectation: string) { const actual = element.innerHTML .replace(/<!--(\W|\w)*?-->/g, '') .replace(/\sng-reflect-\S*="[^"]*"/g, ''); expect(actual.replace(/\s/g, '') === expectation.replace(/\s/g, '')) .withContext(`HTML does not match expectation. Actual HTML:\n${actual}`) .toBe(true); } function setMarker(node: Node) { (node as any)[CREATED_INITIALLY_MARKER] = true; } function hasMarker(node: Node): boolean { return !!(node as any)[CREATED_INITIALLY_MARKER]; } function markNodesAsCreatedInitially(root: HTMLElement) { let current: Node | null = root; while (current) { setMarker(current); if (current.firstChild) { markNodesAsCreatedInitially(current.firstChild as HTMLElement); } current = current.nextSibling; } } function childrenOf(...nodes: Node[]): Node[] { const result: Node[] = []; for (const node of nodes) { let current: Node | null = node.firstChild; while (current) { result.push(current); current = current.nextSibling; } } return result; } function verifyNodesRemainUntouched(root: HTMLElement, exceptions: Node[] = []) { if (!root) { throw new Error('Root node must be provided'); } let current: Node | null = root; while (current) { if (!hasMarker(current)) { if (exceptions.includes(current)) { // This node was re-created intentionally, // do not inspect child nodes. break; } else { throw new Error(`Unexpected state: node was re-created: ${(current as any).innerHTML}`); } } if (current.firstChild) { verifyNodesRemainUntouched(current.firstChild as HTMLElement, exceptions); } current = current.nextSibling; } } function verifyNodesWereRecreated(nodes: Iterable<Node>) { nodes = Array.from(nodes); for (const node of nodes) { if (hasMarker(node)) { throw new Error(`Unexpected state: node was *not* re-created: ${(node as any).innerHTML}`); } } } });
{ "end_byte": 55579, "start_byte": 50814, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/hmr_spec.ts" }
angular/packages/core/test/acceptance/local_compilation_spec.ts_0_7378
/** * @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, forwardRef, ɵɵdefineNgModule, ɵɵgetComponentDepsFactory, ɵɵsetNgModuleScope, } from '@angular/core'; import {ComponentType} from '@angular/core/src/render3'; import {getNgModuleDef} from '@angular/core/src/render3/def_getters'; describe('component dependencies in local compilation', () => { it('should compute correct set of dependencies when importing ng-modules directly', () => { @Component({ selector: 'sub', standalone: false, }) class SubComponent {} class SubModule { static ɵmod = ɵɵdefineNgModule({type: SubModule}); } ɵɵsetNgModuleScope(SubModule, {exports: [SubComponent]}); @Component({ standalone: false, }) class MainComponent {} class MainModule { static ɵmod = ɵɵdefineNgModule({type: MainModule}); } ɵɵsetNgModuleScope(MainModule, {imports: [SubModule], declarations: [MainComponent]}); const deps = ɵɵgetComponentDepsFactory(MainComponent as ComponentType<any>)(); expect(deps).toEqual(jasmine.arrayWithExactContents([SubComponent, MainComponent])); }); it('should compute correct set of dependencies when importing ng-modules - nested array case', () => { @Component({ selector: 'sub', standalone: false, }) class SubComponent {} class SubModule { static ɵmod = ɵɵdefineNgModule({type: SubModule}); } ɵɵsetNgModuleScope(SubModule, {exports: [[[SubComponent]]]}); @Component({ standalone: false, }) class MainComponent {} class MainModule { static ɵmod = ɵɵdefineNgModule({type: MainModule}); } ɵɵsetNgModuleScope(MainModule, {imports: [[SubModule]], declarations: [[MainComponent]]}); const deps = ɵɵgetComponentDepsFactory(MainComponent as ComponentType<any>)(); expect(deps).toEqual(jasmine.arrayWithExactContents([SubComponent, MainComponent])); }); it('should compute correct set of dependencies when importing ng-modules with providers', () => { @Component({ selector: 'sub', standalone: false, }) class SubComponent {} class SubModule { static ɵmod = ɵɵdefineNgModule({type: SubModule}); } ɵɵsetNgModuleScope(SubModule, {exports: [SubComponent]}); @Component({ standalone: false, }) class MainComponent {} class MainModule { static ɵmod = ɵɵdefineNgModule({type: MainModule}); } ɵɵsetNgModuleScope(MainModule, { imports: [{ngModule: SubModule, providers: []}], declarations: [MainComponent], }); const deps = ɵɵgetComponentDepsFactory(MainComponent as ComponentType<any>)(); expect(deps).toEqual(jasmine.arrayWithExactContents([SubComponent, MainComponent])); }); it('should compute correct set of dependencies when importing ng-modules with providers - nested array case', () => { @Component({ selector: 'sub', standalone: false, }) class SubComponent {} class SubModule { static ɵmod = ɵɵdefineNgModule({type: SubModule}); } ɵɵsetNgModuleScope(SubModule, {exports: [[[SubComponent]]]}); @Component({ standalone: false, }) class MainComponent {} class MainModule { static ɵmod = ɵɵdefineNgModule({type: MainModule}); } ɵɵsetNgModuleScope(MainModule, { imports: [[{ngModule: SubModule, providers: []}]], declarations: [[MainComponent]], }); const deps = ɵɵgetComponentDepsFactory(MainComponent as ComponentType<any>)(); expect(deps).toEqual(jasmine.arrayWithExactContents([SubComponent, MainComponent])); }); it('should compute correct set of dependencies when importing ng-modules using forward ref', () => { @Component({ selector: 'sub', standalone: false, }) class SubComponent {} class SubModule { static ɵmod = ɵɵdefineNgModule({type: SubModule}); } ɵɵsetNgModuleScope(SubModule, {exports: [forwardRef(() => SubComponent)]}); @Component({ standalone: false, }) class MainComponent {} class MainModule { static ɵmod = ɵɵdefineNgModule({type: MainModule}); } ɵɵsetNgModuleScope(MainModule, { imports: [forwardRef(() => SubModule)], declarations: [forwardRef(() => MainComponent)], }); const deps = ɵɵgetComponentDepsFactory(MainComponent as ComponentType<any>)(); expect(deps).toEqual(jasmine.arrayWithExactContents([SubComponent, MainComponent])); }); it('should compute correct set of dependencies when importing ng-modules using forward ref - nested array case', () => { @Component({ selector: 'sub', standalone: false, }) class SubComponent {} class SubModule { static ɵmod = ɵɵdefineNgModule({type: SubModule}); } ɵɵsetNgModuleScope(SubModule, {exports: [[[forwardRef(() => SubComponent)]]]}); @Component({ standalone: false, }) class MainComponent {} class MainModule { static ɵmod = ɵɵdefineNgModule({type: MainModule}); } ɵɵsetNgModuleScope(MainModule, { imports: [[forwardRef(() => SubModule)]], declarations: [[forwardRef(() => MainComponent)]], }); const deps = ɵɵgetComponentDepsFactory(MainComponent as ComponentType<any>)(); expect(deps).toEqual(jasmine.arrayWithExactContents([SubComponent, MainComponent])); }); it('should compute correct set of dependencies when importing ng-modules with providers using forward ref', () => { @Component({ selector: 'sub', standalone: false, }) class SubComponent {} class SubModule { static ɵmod = ɵɵdefineNgModule({type: SubModule}); } ɵɵsetNgModuleScope(SubModule, {exports: [SubComponent]}); @Component({ standalone: false, }) class MainComponent {} class MainModule { static ɵmod = ɵɵdefineNgModule({type: MainModule}); } ɵɵsetNgModuleScope(MainModule, { imports: [forwardRef(() => ({ngModule: SubModule, providers: []}))], declarations: [MainComponent], }); const deps = ɵɵgetComponentDepsFactory(MainComponent as ComponentType<any>)(); expect(deps).toEqual(jasmine.arrayWithExactContents([SubComponent, MainComponent])); }); it('should compute correct set of dependencies when importing ng-modules with providers using forward ref', () => { @Component({ selector: 'sub', standalone: false, }) class SubComponent {} class SubModule { static ɵmod = ɵɵdefineNgModule({type: SubModule}); } ɵɵsetNgModuleScope(SubModule, {exports: [[[SubComponent]]]}); @Component({ standalone: false, }) class MainComponent {} class MainModule { static ɵmod = ɵɵdefineNgModule({type: MainModule}); } ɵɵsetNgModuleScope(MainModule, { imports: [[forwardRef(() => ({ngModule: SubModule, providers: []}))]], declarations: [[MainComponent]], }); const deps = ɵɵgetComponentDepsFactory(MainComponent as ComponentType<any>)(); expect(deps).toEqual(jasmine.arrayWithExactContents([SubComponent, MainComponent])); }); }); describe('component bootstrap info', () => { it('should include the bootstrap info in local compil
{ "end_byte": 7378, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/local_compilation_spec.ts" }
angular/packages/core/test/acceptance/local_compilation_spec.ts_7380_8771
ion mode', () => { @Component({ standalone: false, }) class MainComponent {} class MainModule { static ɵmod = ɵɵdefineNgModule({type: MainModule}); } ɵɵsetNgModuleScope(MainModule, {declarations: [MainComponent], bootstrap: [MainComponent]}); const def = getNgModuleDef(MainModule); expect(def?.bootstrap).toEqual([MainComponent]); }); it('should flatten the bootstrap info in local compilation mode', () => { @Component({ standalone: false, }) class MainComponent {} class MainModule { static ɵmod = ɵɵdefineNgModule({type: MainModule}); } ɵɵsetNgModuleScope(MainModule, {declarations: [MainComponent], bootstrap: [[[MainComponent]]]}); const def = getNgModuleDef(MainModule); expect(def?.bootstrap).toEqual([MainComponent]); }); it('should include the bootstrap info in full compilation mode', () => { @Component({ standalone: false, }) class MainComponent {} class MainModule { static ɵmod = ɵɵdefineNgModule({type: MainModule, bootstrap: [MainComponent]}); } ɵɵsetNgModuleScope(MainModule, {declarations: [MainComponent]}); const def = getNgModuleDef(MainModule); expect(def?.bootstrap).toEqual([MainComponent]); }); });
{ "end_byte": 8771, "start_byte": 7380, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/local_compilation_spec.ts" }
angular/packages/core/test/acceptance/env_injector_standalone_spec.ts_0_3433
/** * @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, createEnvironmentInjector, EnvironmentInjector, importProvidersFrom, InjectionToken, NgModule, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {internalImportProvidersFrom} from '../../src/di/provider_collection'; describe('environment injector and standalone components', () => { it('should see providers from modules imported by standalone components', () => { class ModuleService {} @NgModule({providers: [ModuleService]}) class Module {} @Component({standalone: true, imports: [Module]}) class StandaloneComponent {} const parentEnvInjector = TestBed.inject(EnvironmentInjector); const envInjector = createEnvironmentInjector( internalImportProvidersFrom(false, StandaloneComponent), parentEnvInjector, ); expect(envInjector.get(ModuleService)).toBeInstanceOf(ModuleService); }); it('should see providers when exporting a standalone components', () => { class ModuleService {} @NgModule({providers: [ModuleService]}) class Module {} @Component({standalone: true, imports: [Module]}) class StandaloneComponent {} @NgModule({imports: [StandaloneComponent], exports: [StandaloneComponent]}) class AppModule {} const parentEnvInjector = TestBed.inject(EnvironmentInjector); const envInjector = createEnvironmentInjector( [importProvidersFrom(AppModule)], parentEnvInjector, ); expect(envInjector.get(ModuleService)).toBeInstanceOf(ModuleService); }); it('should not collect duplicate providers', () => { class ModuleService {} @NgModule({providers: [{provide: ModuleService, useClass: ModuleService, multi: true}]}) class Module {} @Component({standalone: true, imports: [Module]}) class StandaloneComponent1 {} @Component({standalone: true, imports: [Module]}) class StandaloneComponent2 {} @NgModule({ imports: [StandaloneComponent1, StandaloneComponent2], exports: [StandaloneComponent1, StandaloneComponent2], }) class AppModule {} const parentEnvInjector = TestBed.inject(EnvironmentInjector); const envInjector = createEnvironmentInjector( [importProvidersFrom(AppModule)], parentEnvInjector, ); const services = envInjector.get(ModuleService) as ModuleService[]; expect(services.length).toBe(1); }); it('should support nested arrays of providers', () => { const A = new InjectionToken('A'); const B = new InjectionToken('B'); const C = new InjectionToken('C'); const MULTI = new InjectionToken('D'); const providers = [ {provide: MULTI, useValue: 1, multi: true}, {provide: A, useValue: 'A'}, // [ {provide: B, useValue: 'B'}, [ {provide: C, useValue: 'C'}, {provide: MULTI, useValue: 2, multi: true}, ], ], ]; const parentEnvInjector = TestBed.inject(EnvironmentInjector); const envInjector = createEnvironmentInjector(providers, parentEnvInjector); expect(envInjector.get(A)).toBe('A'); expect(envInjector.get(B)).toBe('B'); expect(envInjector.get(C)).toBe('C'); expect(envInjector.get(MULTI)).toEqual([1, 2]); }); });
{ "end_byte": 3433, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/env_injector_standalone_spec.ts" }
angular/packages/core/test/acceptance/renderer_factory_spec.ts_0_7643
/** * @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 {AnimationEvent} from '@angular/animations'; import { ɵAnimationEngine, ɵAnimationRendererFactory, ɵNoopAnimationStyleNormalizer, } from '@angular/animations/browser'; import {MockAnimationDriver, MockAnimationPlayer} from '@angular/animations/browser/testing'; import {CommonModule, DOCUMENT} from '@angular/common'; import {PLATFORM_BROWSER_ID, PLATFORM_SERVER_ID} from '@angular/common/src/platform_id'; import { Component, DoCheck, NgZone, Renderer2, RendererFactory2, RendererStyleFlags2, RendererType2, ViewEncapsulation, } from '@angular/core'; import {RElement} from '@angular/core/src/render3/interfaces/renderer_dom'; import {ngDevModeResetPerfCounters} from '@angular/core/src/util/ng_dev_mode'; import {NoopNgZone} from '@angular/core/src/zone/ng_zone'; import {TestBed} from '@angular/core/testing'; import {EventManager, ɵSharedStylesHost} from '@angular/platform-browser'; import {DomRendererFactory2} from '@angular/platform-browser/src/dom/dom_renderer'; import {expect} from '@angular/platform-browser/testing/src/matchers'; describe('renderer factory lifecycle', () => { let logs: string[] = []; let lastCapturedType: RendererType2 | null = null; @Component({ selector: 'some-component', template: `foo`, standalone: false, }) class SomeComponent implements DoCheck { ngOnInit() { logs.push('some_component create'); } ngDoCheck() { logs.push('some_component update'); } } @Component({ selector: 'some-component-with-error', template: `With error`, standalone: false, }) class SomeComponentWhichThrows { ngOnInit() { throw new Error('SomeComponentWhichThrows threw'); } } @Component({ selector: 'lol', template: `<some-component></some-component>`, standalone: false, }) class TestComponent implements DoCheck { ngOnInit() { logs.push('test_component create'); } ngDoCheck() { logs.push('test_component update'); } } /** Creates a patched renderer factory that pushes entries to the test log */ function createPatchedRendererFactory(document: any) { let rendererFactory = getRendererFactory2(document); const createRender = rendererFactory.createRenderer; rendererFactory.createRenderer = (hostElement: any, type: RendererType2 | null) => { logs.push('create'); lastCapturedType = type; return createRender.apply(rendererFactory, [hostElement, type]); }; rendererFactory.begin = () => logs.push('begin'); rendererFactory.end = () => logs.push('end'); return rendererFactory; } beforeEach(() => { logs = []; TestBed.configureTestingModule({ declarations: [SomeComponent, SomeComponentWhichThrows, TestComponent], providers: [ { provide: RendererFactory2, useFactory: (document: any) => createPatchedRendererFactory(document), deps: [DOCUMENT], }, ], }); }); it('should work with a component', () => { const fixture = TestBed.createComponent(SomeComponent); fixture.componentRef.changeDetectorRef.detectChanges(); expect(logs).toEqual([ 'create', 'create', 'begin', 'some_component create', 'some_component update', 'end', ]); logs = []; fixture.componentRef.changeDetectorRef.detectChanges(); expect(logs).toEqual(['begin', 'some_component update', 'end']); }); it('should work with a component which throws', () => { expect(() => { const fixture = TestBed.createComponent(SomeComponentWhichThrows); fixture.componentRef.changeDetectorRef.detectChanges(); }).toThrow(); expect(logs).toEqual(['create', 'create', 'begin', 'end']); }); it('should pass in the component styles directly into the underlying renderer', () => { @Component({ standalone: true, styles: ['.some-css-class { color: red; }'], template: '...', encapsulation: ViewEncapsulation.ShadowDom, }) class StyledComp {} TestBed.createComponent(StyledComp); expect(lastCapturedType!.styles).toEqual(['.some-css-class { color: red; }']); expect(lastCapturedType!.encapsulation).toEqual(ViewEncapsulation.ShadowDom); }); describe('component animations', () => { it('should pass in the component styles directly into the underlying renderer', () => { const animA = {name: 'a'}; const animB = {name: 'b'}; @Component({ standalone: true, template: '', animations: [animA, animB], }) class AnimComp {} TestBed.createComponent(AnimComp); const capturedAnimations = lastCapturedType!.data!['animation']; expect(Array.isArray(capturedAnimations)).toBeTruthy(); expect(capturedAnimations.length).toEqual(2); expect(capturedAnimations).toContain(animA); expect(capturedAnimations).toContain(animB); }); it('should include animations in the renderType data array even if the array is empty', () => { @Component({ standalone: true, template: '...', animations: [], }) class AnimComp {} TestBed.createComponent(AnimComp); const data = lastCapturedType!.data; expect(data['animation']).toEqual([]); }); it('should allow [@trigger] bindings to be picked up by the underlying renderer', () => { @Component({ standalone: true, template: '<div @fooAnimation></div>', animations: [], }) class AnimComp {} const rendererFactory = new MockRendererFactory(['setProperty']); TestBed.configureTestingModule({ providers: [ { provide: RendererFactory2, useValue: rendererFactory, deps: [DOCUMENT], }, ], }); const fixture = TestBed.createComponent(AnimComp); fixture.detectChanges(); const renderer = rendererFactory.lastRenderer!; const spy = renderer.spies['setProperty']; const [_, prop, __] = spy.calls.mostRecent().args; expect(prop).toEqual('@fooAnimation'); }); }); it('should not invoke renderer destroy method for embedded views', () => { @Component({ selector: 'comp', standalone: true, imports: [CommonModule], template: ` <div>Root view</div> <div *ngIf="visible">Child view</div> `, }) class Comp { visible = true; } const rendererFactory = new MockRendererFactory(['destroy', 'createElement']); TestBed.configureTestingModule({ providers: [ { provide: RendererFactory2, useValue: rendererFactory, deps: [DOCUMENT], }, ], }); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); const comp = fixture.componentInstance; comp!.visible = false; fixture.detectChanges(); comp!.visible = true; fixture.detectChanges(); const renderer = rendererFactory.lastRenderer!; const destroySpy = renderer.spies['destroy']; const createElementSpy = renderer.spies['createElement']; // we should never see `destroy` method being called // in case child views are created/removed. expect(destroySpy.calls.count()).toBe(0); // Make sure other methods on the renderer were invoked. expect(createElementSpy.calls.count() > 0).toBe(true); }); }); de
{ "end_byte": 7643, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/renderer_factory_spec.ts" }
angular/packages/core/test/acceptance/renderer_factory_spec.ts_7645_15631
ribe('animation renderer factory', () => { let eventLogs: string[] = []; let rendererFactory: RendererFactory2 | null = null; function getAnimationLog(): MockAnimationPlayer[] { return MockAnimationDriver.log as MockAnimationPlayer[]; } beforeEach(() => { eventLogs = []; rendererFactory = null; MockAnimationDriver.log = []; TestBed.configureTestingModule({ declarations: [SomeComponentWithAnimation, SomeComponent], providers: [ { provide: RendererFactory2, useFactory: (d: Document) => (rendererFactory = getAnimationRendererFactory2(d)), deps: [DOCUMENT], }, ], }); }); @Component({ selector: 'some-component', template: ` <div [@myAnimation]="exp" (@myAnimation.start)="callback($event)" (@myAnimation.done)="callback($event)"> foo </div> `, animations: [ { type: 7, name: 'myAnimation', definitions: [ { type: 1, expr: '* => on', animation: [ {type: 4, styles: {type: 6, styles: {opacity: 1}, offset: null}, timings: 10}, ], options: null, }, ], options: {}, }, ], standalone: false, }) class SomeComponentWithAnimation { exp: string | undefined; callback(event: AnimationEvent) { eventLogs.push(`${event.fromState ? event.fromState : event.toState} - ${event.phaseName}`); } } @Component({ selector: 'some-component', template: 'foo', standalone: false, }) class SomeComponent {} it('should work with components without animations', () => { const fixture = TestBed.createComponent(SomeComponent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('foo'); }); isBrowser && it('should work with animated components', (done) => { const fixture = TestBed.createComponent(SomeComponentWithAnimation); fixture.detectChanges(); expect(rendererFactory).toBeTruthy(); expect(fixture.nativeElement.innerHTML).toMatch( /<div class="ng-tns-c\d+-0 ng-trigger ng-trigger-myAnimation">\s+foo\s+<\/div>/, ); fixture.componentInstance.exp = 'on'; fixture.detectChanges(); const [player] = getAnimationLog(); expect(player.keyframes).toEqual([ new Map<string, string | number>([ ['opacity', '*'], ['offset', 0], ]), new Map<string, string | number>([ ['opacity', 1], ['offset', 1], ]), ]); player.finish(); rendererFactory!.whenRenderingDone!().then(() => { expect(eventLogs).toEqual(['void - start', 'void - done', 'on - start', 'on - done']); done(); }); }); }); function getRendererFactory2(document: Document): RendererFactory2 { const fakeNgZone: NgZone = new NoopNgZone(); const eventManager = new EventManager([], fakeNgZone); const appId = 'app-id'; const rendererFactory = new DomRendererFactory2( eventManager, new ɵSharedStylesHost(document, appId), appId, true, document, isNode ? PLATFORM_SERVER_ID : PLATFORM_BROWSER_ID, fakeNgZone, ); const origCreateRenderer = rendererFactory.createRenderer; rendererFactory.createRenderer = function (element: any, type: RendererType2 | null) { const renderer = origCreateRenderer.call(this, element, type); renderer.destroyNode = () => {}; return renderer; }; return rendererFactory; } function getAnimationRendererFactory2(document: Document): RendererFactory2 { const fakeNgZone: NgZone = new NoopNgZone(); return new ɵAnimationRendererFactory( getRendererFactory2(document), new ɵAnimationEngine(document, new MockAnimationDriver(), new ɵNoopAnimationStyleNormalizer()), fakeNgZone, ); } describe('custom renderer', () => { @Component({ selector: 'some-component', template: `<div><span></span></div>`, standalone: false, }) class SomeComponent {} /** * Creates a patched renderer factory that creates elements with a shape different than DOM node */ function createPatchedRendererFactory(document: Document) { let rendererFactory = getRendererFactory2(document); const origCreateRenderer = rendererFactory.createRenderer; rendererFactory.createRenderer = function (element: any, type: RendererType2 | null) { const renderer = origCreateRenderer.call(this, element, type); renderer.appendChild = () => {}; renderer.createElement = (name: string) => ({ name, el: document.createElement(name), }); return renderer; }; return rendererFactory; } beforeEach(() => { TestBed.configureTestingModule({ declarations: [SomeComponent], providers: [ { provide: RendererFactory2, useFactory: (document: Document) => createPatchedRendererFactory(document), deps: [DOCUMENT], }, ], }); }); it('should not trigger errors', () => { expect(() => { const fixture = TestBed.createComponent(SomeComponent); fixture.detectChanges(); }).not.toThrow(); }); }); describe('Renderer2 destruction hooks', () => { @Component({ selector: 'some-component', template: ` <span *ngIf="isContentVisible">A</span> <span *ngIf="isContentVisible">B</span> <span *ngIf="isContentVisible">C</span> `, standalone: false, }) class SimpleApp { isContentVisible = true; } @Component({ selector: 'basic-comp', template: 'comp(<ng-content></ng-content>)', standalone: false, }) class BasicComponent {} @Component({ selector: 'some-component', template: ` <basic-comp *ngIf="isContentVisible">A</basic-comp> <basic-comp *ngIf="isContentVisible">B</basic-comp> <basic-comp *ngIf="isContentVisible">C</basic-comp> `, standalone: false, }) class AppWithComponents { isContentVisible = true; } beforeEach(() => { // Tests below depend on perf counters when running with Ivy. In order to have // clean perf counters at the beginning of a test, we reset those here. ngDevModeResetPerfCounters(); TestBed.configureTestingModule({ declarations: [SimpleApp, AppWithComponents, BasicComponent], providers: [ { provide: RendererFactory2, useFactory: (document: Document) => getRendererFactory2(document), deps: [DOCUMENT], }, ], }); }); it('should call renderer.destroyNode for each node destroyed', () => { const fixture = TestBed.createComponent(SimpleApp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('ABC'); fixture.componentInstance.isContentVisible = false; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe(''); expect(ngDevMode!.rendererDestroy).toBe(0); expect(ngDevMode!.rendererDestroyNode).toBe(3); }); it('should call renderer.destroy for each component destroyed', () => { const fixture = TestBed.createComponent(AppWithComponents); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('comp(A)comp(B)comp(C)'); fixture.componentInstance.isContentVisible = false; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe(''); expect(ngDevMode!.rendererDestroy).toBe(3); expect(ngDevMode!.rendererDestroyNode).toBe(3); }); }); export class MockRendererFactory implements RendererFactory2 { lastRenderer: any; private _spyOnMethods: string[]; constructor(spyOnMethods?: string[]) { this._spyOnMethods = spyOnMethods || []; } createRenderer(hostElement: RElement | null, rendererType: RendererType2 | null): Renderer2 { const renderer = (this.lastRenderer = new MockRenderer(this._spyOnMethods)); return renderer; } } class
{ "end_byte": 15631, "start_byte": 7645, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/renderer_factory_spec.ts" }
angular/packages/core/test/acceptance/renderer_factory_spec.ts_15633_17972
ckRenderer implements Renderer2 { public spies: {[methodName: string]: any} = {}; data = {}; destroyNode: ((node: any) => void) | null = null; constructor(spyOnMethods: string[]) { spyOnMethods.forEach((methodName) => { this.spies[methodName] = spyOn(this as any, methodName).and.callThrough(); }); } destroy(): void {} createComment(value: string): Comment { return document.createComment(value); } createElement(name: string, namespace?: string | null): Element { return namespace ? document.createElementNS(namespace, name) : document.createElement(name); } createText(value: string): Text { return document.createTextNode(value); } appendChild(parent: RElement, newChild: Node): void { parent.appendChild(newChild); } insertBefore(parent: Node, newChild: Node, refChild: Node | null): void { parent.insertBefore(newChild, refChild); } removeChild(parent: RElement, oldChild: Element): void { oldChild.remove(); } selectRootElement(selectorOrNode: string | any): RElement { return typeof selectorOrNode === 'string' ? document.querySelector(selectorOrNode) : selectorOrNode; } parentNode(node: Node): Element | null { return node.parentNode as Element; } nextSibling(node: Node): Node | null { return node.nextSibling; } setAttribute(el: RElement, name: string, value: string, namespace?: string | null): void { // set all synthetic attributes as properties if (name[0] === '@') { this.setProperty(el, name, value); } else { el.setAttribute(name, value); } } removeAttribute(el: RElement, name: string, namespace?: string | null): void {} addClass(el: RElement, name: string): void {} removeClass(el: RElement, name: string): void {} setStyle(el: RElement, style: string, value: any, flags?: RendererStyleFlags2): void {} removeStyle(el: RElement, style: string, flags?: RendererStyleFlags2): void {} setProperty(el: RElement, name: string, value: any): void { (el as any)[name] = value; } setValue(node: Text, value: string): void { node.textContent = value; } // TODO: Deprecate in favor of addEventListener/removeEventListener listen(target: Node, eventName: string, callback: (event: any) => boolean | void): () => void { return () => {}; } }
{ "end_byte": 17972, "start_byte": 15633, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/renderer_factory_spec.ts" }
angular/packages/core/test/acceptance/outputs_spec.ts_0_9270
/** * @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} from '@angular/common'; import { Component, Directive, EventEmitter, Input, OnDestroy, Output, ViewChild, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; describe('outputs', () => { @Component({ selector: 'button-toggle', template: '', standalone: false, }) class ButtonToggle { @Output('change') change = new EventEmitter<void>(); @Output('reset') resetStream = new EventEmitter<void>(); } @Directive({ selector: '[otherDir]', standalone: false, }) class OtherDir { @Output('change') changeStream = new EventEmitter<void>(); } @Component({ selector: 'destroy-comp', template: '', standalone: false, }) class DestroyComp implements OnDestroy { events: string[] = []; ngOnDestroy() { this.events.push('destroy'); } } @Directive({ selector: '[myButton]', standalone: false, }) class MyButton { @Output() click = new EventEmitter<void>(); } it('should call component output function when event is emitted', () => { let counter = 0; @Component({ template: '<button-toggle (change)="onChange()"></button-toggle>', standalone: false, }) class App { @ViewChild(ButtonToggle) buttonToggle!: ButtonToggle; onChange() { counter++; } } TestBed.configureTestingModule({declarations: [App, ButtonToggle]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.componentInstance.buttonToggle.change.next(); expect(counter).toBe(1); fixture.componentInstance.buttonToggle.change.next(); expect(counter).toBe(2); }); it('should support more than 1 output function on the same node', () => { let counter = 0; let resetCounter = 0; @Component({ template: '<button-toggle (change)="onChange()" (reset)="onReset()"></button-toggle>', standalone: false, }) class App { @ViewChild(ButtonToggle) buttonToggle!: ButtonToggle; onChange() { counter++; } onReset() { resetCounter++; } } TestBed.configureTestingModule({declarations: [App, ButtonToggle]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.componentInstance.buttonToggle.change.next(); expect(counter).toBe(1); fixture.componentInstance.buttonToggle.resetStream.next(); expect(resetCounter).toBe(1); }); it('should eval component output expression when event is emitted', () => { @Component({ template: '<button-toggle (change)="counter = counter + 1"></button-toggle>', standalone: false, }) class App { @ViewChild(ButtonToggle) buttonToggle!: ButtonToggle; counter = 0; } TestBed.configureTestingModule({declarations: [App, ButtonToggle]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.componentInstance.buttonToggle.change.next(); expect(fixture.componentInstance.counter).toBe(1); fixture.componentInstance.buttonToggle.change.next(); expect(fixture.componentInstance.counter).toBe(2); }); it('should unsubscribe from output when view is destroyed', () => { let counter = 0; @Component({ template: '<button-toggle *ngIf="condition" (change)="onChange()"></button-toggle>', standalone: false, }) class App { @ViewChild(ButtonToggle) buttonToggle!: ButtonToggle; condition = true; onChange() { counter++; } } TestBed.configureTestingModule({imports: [CommonModule], declarations: [App, ButtonToggle]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const buttonToggle = fixture.componentInstance.buttonToggle; buttonToggle.change.next(); expect(counter).toBe(1); fixture.componentInstance.condition = false; fixture.detectChanges(); buttonToggle.change.next(); expect(counter).toBe(1); }); it('should unsubscribe from output in nested view', () => { let counter = 0; @Component({ template: ` <div *ngIf="condition"> <button-toggle *ngIf="condition2" (change)="onChange()"></button-toggle> </div> `, standalone: false, }) class App { @ViewChild(ButtonToggle) buttonToggle!: ButtonToggle; condition = true; condition2 = true; onChange() { counter++; } } TestBed.configureTestingModule({imports: [CommonModule], declarations: [App, ButtonToggle]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const buttonToggle = fixture.componentInstance.buttonToggle; buttonToggle.change.next(); expect(counter).toBe(1); fixture.componentInstance.condition = false; fixture.detectChanges(); buttonToggle.change.next(); expect(counter).toBe(1); }); it('should work properly when view also has listeners and destroys', () => { let clickCounter = 0; let changeCounter = 0; @Component({ template: ` <div *ngIf="condition"> <button (click)="onClick()">Click me</button> <button-toggle (change)="onChange()"></button-toggle> <destroy-comp></destroy-comp> </div> `, standalone: false, }) class App { @ViewChild(ButtonToggle) buttonToggle!: ButtonToggle; @ViewChild(DestroyComp) destroyComp!: DestroyComp; condition = true; onClick() { clickCounter++; } onChange() { changeCounter++; } } TestBed.configureTestingModule({ imports: [CommonModule], declarations: [App, ButtonToggle, DestroyComp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const {buttonToggle, destroyComp} = fixture.componentInstance; const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); buttonToggle.change.next(); expect(changeCounter).toBe(1); expect(clickCounter).toBe(0); button.click(); expect(changeCounter).toBe(1); expect(clickCounter).toBe(1); fixture.componentInstance.condition = false; fixture.detectChanges(); expect(destroyComp.events).toEqual(['destroy']); buttonToggle.change.next(); button.click(); expect(changeCounter).toBe(1); expect(clickCounter).toBe(1); }); it('should fire event listeners along with outputs if they match', () => { let counter = 0; @Component({ template: '<button myButton (click)="onClick()">Click me</button>', standalone: false, }) class App { @ViewChild(MyButton) buttonDir!: MyButton; onClick() { counter++; } } TestBed.configureTestingModule({declarations: [App, MyButton]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); // To match current Angular behavior, the click listener is still // set up in addition to any matching outputs. const button = fixture.nativeElement.querySelector('button'); button.click(); expect(counter).toBe(1); fixture.componentInstance.buttonDir.click.next(); expect(counter).toBe(2); }); it('should work with two outputs of the same name', () => { let counter = 0; @Component({ template: '<button-toggle (change)="onChange()" otherDir></button-toggle>', standalone: false, }) class App { @ViewChild(ButtonToggle) buttonToggle!: ButtonToggle; @ViewChild(OtherDir) otherDir!: OtherDir; onChange() { counter++; } } TestBed.configureTestingModule({declarations: [App, ButtonToggle, OtherDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.componentInstance.buttonToggle.change.next(); expect(counter).toBe(1); fixture.componentInstance.otherDir.changeStream.next(); expect(counter).toBe(2); }); it('should work with an input and output of the same name', () => { let counter = 0; @Directive({ selector: '[otherChangeDir]', standalone: false, }) class OtherChangeDir { @Input() change!: boolean; } @Component({ template: '<button-toggle (change)="onChange()" otherChangeDir [change]="change"></button-toggle>', standalone: false, }) class App { @ViewChild(ButtonToggle) buttonToggle!: ButtonToggle; @ViewChild(OtherChangeDir) otherDir!: OtherChangeDir; change = true; onChange() { counter++; } } TestBed.configureTestingModule({declarations: [App, ButtonToggle, OtherChangeDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const {buttonToggle, otherDir} = fixture.componentInstance; expect(otherDir.change).toBe(true); fixture.componentInstance.change = false; fixture.detectChanges(); expect(otherDir.change).toBe(false); buttonToggle.change.next(); expect(counter).toBe(1); }); });
{ "end_byte": 9270, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/outputs_spec.ts" }
angular/packages/core/test/acceptance/environment_injector_spec.ts_0_677
/** * @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, createComponent, createEnvironmentInjector, DestroyRef, ENVIRONMENT_INITIALIZER, EnvironmentInjector, inject, InjectFlags, InjectionToken, INJECTOR, Injector, NgModuleRef, provideEnvironmentInitializer, ViewContainerRef, } from '@angular/core'; import {R3Injector} from '@angular/core/src/di/r3_injector'; import {RuntimeError, RuntimeErrorCode} from '@angular/core/src/errors'; import {TestBed} from '@angular/core/testing';
{ "end_byte": 677, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/environment_injector_spec.ts" }
angular/packages/core/test/acceptance/environment_injector_spec.ts_679_10044
describe('environment injector', () => { it('should create and destroy an environment injector', () => { class Service {} let destroyed = false; const parentEnvInjector = TestBed.inject(EnvironmentInjector); const envInjector = createEnvironmentInjector([Service], parentEnvInjector) as R3Injector; envInjector.onDestroy(() => (destroyed = true)); const service = envInjector.get(Service); expect(service).toBeInstanceOf(Service); envInjector.destroy(); expect(destroyed).toBeTrue(); }); it('should allow unregistration while destroying', () => { const destroyedLog: string[] = []; const parentEnvInjector = TestBed.inject(EnvironmentInjector); const envInjector = createEnvironmentInjector([], parentEnvInjector); const destroyRef = envInjector.get(DestroyRef); const unregister = destroyRef.onDestroy(() => { destroyedLog.push('first'); unregister(); }); destroyRef.onDestroy(() => { destroyedLog.push('second'); }); expect(destroyedLog).toEqual([]); envInjector.destroy(); expect(destroyedLog).toEqual(['first', 'second']); }); it('should see providers from a parent EnvInjector', () => { class Service {} const parentEnvInjector = TestBed.inject(EnvironmentInjector); const envInjector = createEnvironmentInjector( [], createEnvironmentInjector([Service], parentEnvInjector), ); expect(envInjector.get(Service)).toBeInstanceOf(Service); }); it('should shadow providers from the parent EnvInjector', () => { const token = new InjectionToken('token'); const parentEnvInjector = TestBed.inject(EnvironmentInjector); const envInjector = createEnvironmentInjector( [{provide: token, useValue: 'child'}], createEnvironmentInjector([{provide: token, useValue: 'parent'}], parentEnvInjector), ); expect(envInjector.get(token)).toBe('child'); }); it('should expose the Injector token', () => { const parentEnvInjector = TestBed.inject(EnvironmentInjector); const envInjector = createEnvironmentInjector([], parentEnvInjector); expect(envInjector.get(Injector)).toBe(envInjector); expect(envInjector.get(INJECTOR)).toBe(envInjector); }); it('should expose the EnvInjector token', () => { const parentEnvInjector = TestBed.inject(EnvironmentInjector); const envInjector = createEnvironmentInjector([], parentEnvInjector); expect(envInjector.get(EnvironmentInjector)).toBe(envInjector); }); it('should expose the same object as both the Injector and EnvInjector token', () => { const parentEnvInjector = TestBed.inject(EnvironmentInjector); const envInjector = createEnvironmentInjector([], parentEnvInjector); expect(envInjector.get(Injector)).toBe(envInjector.get(EnvironmentInjector)); }); it('should expose the NgModuleRef token', () => { class Service {} const parentEnvInjector = TestBed.inject(EnvironmentInjector); const envInjector = createEnvironmentInjector([Service], parentEnvInjector); const ngModuleRef = envInjector.get(NgModuleRef); expect(ngModuleRef).toBeInstanceOf(NgModuleRef); // NgModuleRef proxies to an Injector holding supplied providers expect(ngModuleRef.injector.get(Service)).toBeInstanceOf(Service); // There is no actual instance of @NgModule-annotated class expect(ngModuleRef.instance).toBeNull(); }); it('should expose the ComponentFactoryResolver token bound to env injector with specified providers', () => { class Service {} @Component({ selector: 'test-cmp', standalone: false, }) class TestComponent { constructor(readonly service: Service) {} } const parentEnvInjector = TestBed.inject(EnvironmentInjector); const environmentInjector = createEnvironmentInjector([Service], parentEnvInjector); const cRef = createComponent(TestComponent, {environmentInjector}); expect(cRef.instance.service).toBeInstanceOf(Service); }); it('should support the ENVIRONMENT_INITIALIZER multi-token', () => { let initialized = false; const parentEnvInjector = TestBed.inject(EnvironmentInjector); createEnvironmentInjector( [ { provide: ENVIRONMENT_INITIALIZER, useValue: () => (initialized = true), multi: true, }, ], parentEnvInjector, ); expect(initialized).toBeTrue(); }); it('should throw when the ENVIRONMENT_INITIALIZER is not a multi-token', () => { const parentEnvInjector = TestBed.inject(EnvironmentInjector); const providers = [ { provide: ENVIRONMENT_INITIALIZER, useValue: () => {}, }, ]; expect(() => createEnvironmentInjector(providers, parentEnvInjector)).toThrowMatching( (e: RuntimeError) => e.code === RuntimeErrorCode.INVALID_MULTI_PROVIDER, ); }); it('should adopt environment-scoped providers', () => { const parentEnvInjector = TestBed.inject(EnvironmentInjector); const injector = createEnvironmentInjector([], parentEnvInjector); const EnvScopedToken = new InjectionToken('env-scoped token', { providedIn: 'environment' as any, factory: () => true, }); expect(injector.get(EnvScopedToken, false)).toBeTrue(); }); describe('runInContext()', () => { it("should return the function's return value", () => { const injector = TestBed.inject(EnvironmentInjector); const returnValue = injector.runInContext(() => 3); expect(returnValue).toBe(3); }); it('should work with an NgModuleRef injector', () => { const ref = TestBed.inject(NgModuleRef); const returnValue = ref.injector.runInContext(() => 3); expect(returnValue).toBe(3); }); it('should return correct injector reference', () => { const ngModuleRef = TestBed.inject(NgModuleRef); const ref1 = ngModuleRef.injector.runInContext(() => inject(Injector)); const ref2 = ngModuleRef.injector.get(Injector); expect(ref1).toBe(ref2); }); it('should make inject() available', () => { const TOKEN = new InjectionToken<string>('TOKEN'); const injector = createEnvironmentInjector( [{provide: TOKEN, useValue: 'from injector'}], TestBed.inject(EnvironmentInjector), ); const result = injector.runInContext(() => inject(TOKEN)); expect(result).toEqual('from injector'); }); it('should properly clean up after the function returns', () => { const TOKEN = new InjectionToken<string>('TOKEN'); const injector = TestBed.inject(EnvironmentInjector); injector.runInContext(() => {}); expect(() => inject(TOKEN, InjectFlags.Optional)).toThrow(); }); it('should properly clean up after the function throws', () => { const TOKEN = new InjectionToken<string>('TOKEN'); const injector = TestBed.inject(EnvironmentInjector); expect(() => injector.runInContext(() => { throw new Error('crashes!'); }), ).toThrow(); expect(() => inject(TOKEN, InjectFlags.Optional)).toThrow(); }); it('should set the correct inject implementation', () => { const TOKEN = new InjectionToken<string>('TOKEN', { providedIn: 'root', factory: () => 'from root', }); @Component({ standalone: true, template: '', providers: [{provide: TOKEN, useValue: 'from component'}], }) class TestCmp { envInjector = inject(EnvironmentInjector); tokenFromComponent = inject(TOKEN); tokenFromEnvContext = this.envInjector.runInContext(() => inject(TOKEN)); // Attempt to inject ViewContainerRef within the environment injector's context. This should // not be available, so the result should be `null`. vcrFromEnvContext = this.envInjector.runInContext(() => inject(ViewContainerRef, InjectFlags.Optional), ); } const instance = TestBed.createComponent(TestCmp).componentInstance; expect(instance.tokenFromComponent).toEqual('from component'); expect(instance.tokenFromEnvContext).toEqual('from root'); expect(instance.vcrFromEnvContext).toBeNull(); }); it('should be reentrant', () => { const TOKEN = new InjectionToken<string>('TOKEN', { providedIn: 'root', factory: () => 'from root', }); const parentInjector = TestBed.inject(EnvironmentInjector); const childInjector = createEnvironmentInjector( [{provide: TOKEN, useValue: 'from child'}], parentInjector, ); const results = parentInjector.runInContext(() => { const fromParentBefore = inject(TOKEN); const fromChild = childInjector.runInContext(() => inject(TOKEN)); const fromParentAfter = inject(TOKEN); return {fromParentBefore, fromChild, fromParentAfter}; }); expect(results.fromParentBefore).toEqual('from root'); expect(results.fromChild).toEqual('from child'); expect(results.fromParentAfter).toEqual('from root'); }); it('should not function on a destroyed injector', () => { const injector = createEnvironmentInjector([], TestBed.inject(EnvironmentInjector)); injector.destroy(); expect(() => injector.runInContext(() => {})).toThrow(); }); }); });
{ "end_byte": 10044, "start_byte": 679, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/environment_injector_spec.ts" }
angular/packages/core/test/acceptance/environment_injector_spec.ts_10046_11514
describe(provideEnvironmentInitializer.name, () => { it('should not call the provided function before environment is initialized', () => { let initialized = false; provideEnvironmentInitializer(() => { initialized = true; }); expect(initialized).toBe(false); }); it('should call the provided function when environment is initialized', () => { let initialized = false; const parentEnvInjector = TestBed.inject(EnvironmentInjector); createEnvironmentInjector( [ provideEnvironmentInitializer(() => { initialized = true; }), ], parentEnvInjector, ); expect(initialized).toBe(true); }); it('should be able to inject dependencies', () => { const TEST_TOKEN = new InjectionToken<string>('TEST_TOKEN', { providedIn: 'root', factory: () => 'test', }); let injectedValue!: string; const parentEnvInjector = TestBed.inject(EnvironmentInjector); createEnvironmentInjector( [ provideEnvironmentInitializer(() => { injectedValue = inject(TEST_TOKEN); }), ], parentEnvInjector, ); expect(injectedValue).toBe('test'); }); }); /** * Typing tests. */ @Component({ template: '', // @ts-expect-error: `provideEnvironmentInitializer()` should not work with Component.providers, // as it wouldn't be executed anyway. providers: [provideEnvironmentInitializer(() => {})], }) class Test {}
{ "end_byte": 11514, "start_byte": 10046, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/environment_injector_spec.ts" }
angular/packages/core/test/acceptance/after_render_hook_spec.ts_0_1202
/** * @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 {PLATFORM_BROWSER_ID, PLATFORM_SERVER_ID} from '@angular/common/src/platform_id'; import { AfterRenderRef, ApplicationRef, ChangeDetectorRef, Component, ErrorHandler, Injector, NgZone, PLATFORM_ID, Type, ViewContainerRef, afterNextRender, afterRender, computed, createComponent, effect, inject, signal, AfterRenderPhase, } from '@angular/core'; import {NoopNgZone} from '@angular/core/src/zone/ng_zone'; import {TestBed} from '@angular/core/testing'; import {firstValueFrom} from 'rxjs'; import {filter} from 'rxjs/operators'; import {EnvironmentInjector, Injectable} from '../../src/di'; import {setUseMicrotaskEffectsByDefault} from '@angular/core/src/render3/reactivity/effect'; function createAndAttachComponent<T>(component: Type<T>) { const componentRef = createComponent(component, { environmentInjector: TestBed.inject(EnvironmentInjector), }); TestBed.inject(ApplicationRef).attachView(componentRef.hostView); return componentRef; }
{ "end_byte": 1202, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/after_render_hook_spec.ts" }
angular/packages/core/test/acceptance/after_render_hook_spec.ts_1204_11347
describe('after render hooks', () => { let prev: boolean; beforeEach(() => { prev = setUseMicrotaskEffectsByDefault(false); }); afterEach(() => setUseMicrotaskEffectsByDefault(prev)); describe('browser', () => { const COMMON_PROVIDERS = [{provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID}]; const COMMON_CONFIGURATION = { providers: [COMMON_PROVIDERS], }; describe('afterRender', () => { it('should run with the correct timing', () => { @Component({ selector: 'dynamic-comp', standalone: false, }) class DynamicComp { afterRenderCount = 0; constructor() { afterRender(() => { this.afterRenderCount++; }); } } @Component({ selector: 'comp', standalone: false, }) class Comp { afterRenderCount = 0; changeDetectorRef = inject(ChangeDetectorRef); viewContainerRef = inject(ViewContainerRef); constructor() { afterRender(() => { this.afterRenderCount++; }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); const component = createAndAttachComponent(Comp); const compInstance = component.instance; const viewContainerRef = compInstance.viewContainerRef; const dynamicCompRef = viewContainerRef.createComponent(DynamicComp); // It hasn't run at all expect(dynamicCompRef.instance.afterRenderCount).toBe(0); expect(compInstance.afterRenderCount).toBe(0); // Running change detection at the dynamicCompRef level dynamicCompRef.changeDetectorRef.detectChanges(); expect(dynamicCompRef.instance.afterRenderCount).toBe(0); expect(compInstance.afterRenderCount).toBe(0); // Running change detection at the compInstance level compInstance.changeDetectorRef.detectChanges(); expect(dynamicCompRef.instance.afterRenderCount).toBe(0); expect(compInstance.afterRenderCount).toBe(0); // Running change detection at the Application level TestBed.inject(ApplicationRef).tick(); expect(dynamicCompRef.instance.afterRenderCount).toBe(1); expect(compInstance.afterRenderCount).toBe(1); // Running change detection after removing view. viewContainerRef.remove(); TestBed.inject(ApplicationRef).tick(); expect(dynamicCompRef.instance.afterRenderCount).toBe(1); expect(compInstance.afterRenderCount).toBe(2); }); it('should run with ComponentFixture.detectChanges', () => { @Component({ selector: 'dynamic-comp', standalone: false, }) class DynamicComp { afterRenderCount = 0; constructor() { afterRender(() => { this.afterRenderCount++; }); } } @Component({ selector: 'comp', standalone: false, }) class Comp { afterRenderCount = 0; changeDetectorRef = inject(ChangeDetectorRef); viewContainerRef = inject(ViewContainerRef); constructor() { afterRender(() => { this.afterRenderCount++; }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); const fixture = TestBed.createComponent(Comp); const compInstance = fixture.componentInstance; const viewContainerRef = compInstance.viewContainerRef; const dynamicCompRef = viewContainerRef.createComponent(DynamicComp); expect(dynamicCompRef.instance.afterRenderCount).toBe(0); expect(compInstance.afterRenderCount).toBe(1); // Running change detection at the dynamicCompRef level dynamicCompRef.changeDetectorRef.detectChanges(); expect(dynamicCompRef.instance.afterRenderCount).toBe(0); expect(compInstance.afterRenderCount).toBe(1); // Running change detection at the compInstance level compInstance.changeDetectorRef.detectChanges(); expect(dynamicCompRef.instance.afterRenderCount).toBe(0); expect(compInstance.afterRenderCount).toBe(1); // Running change detection at the Application level fixture.detectChanges(); expect(dynamicCompRef.instance.afterRenderCount).toBe(1); expect(compInstance.afterRenderCount).toBe(2); // Running change detection after removing view. viewContainerRef.remove(); fixture.detectChanges(); expect(dynamicCompRef.instance.afterRenderCount).toBe(1); expect(compInstance.afterRenderCount).toBe(3); }); it('should run all hooks after outer change detection', () => { let log: string[] = []; @Component({ selector: 'child-comp', standalone: false, }) class ChildComp { constructor() { afterRender(() => { log.push('child-comp'); }); } } @Component({ selector: 'parent', template: `<child-comp></child-comp>`, standalone: false, }) class ParentComp { changeDetectorRef = inject(ChangeDetectorRef); constructor() { afterRender(() => { log.push('parent-comp'); }); } ngOnInit() { log.push('pre-cd'); this.changeDetectorRef.detectChanges(); log.push('post-cd'); } } TestBed.configureTestingModule({ declarations: [ChildComp, ParentComp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(ParentComp); expect(log).toEqual([]); TestBed.inject(ApplicationRef).tick(); expect(log).toEqual(['pre-cd', 'post-cd', 'parent-comp', 'child-comp']); }); it('should run hooks once after tick even if there are multiple root views', () => { let log: string[] = []; @Component({ standalone: true, template: ``, }) class MyComp { constructor() { afterRender(() => { log.push('render'); }); } } TestBed.configureTestingModule({ // NgZone can make counting hard because it runs ApplicationRef.tick automatically. providers: [{provide: NgZone, useClass: NoopNgZone}, ...COMMON_CONFIGURATION.providers], }); expect(log).toEqual([]); const appRef = TestBed.inject(ApplicationRef); appRef.attachView(TestBed.createComponent(MyComp).componentRef.hostView); appRef.attachView(TestBed.createComponent(MyComp).componentRef.hostView); appRef.attachView(TestBed.createComponent(MyComp).componentRef.hostView); appRef.tick(); expect(log.length).toEqual(3); }); it('should unsubscribe when calling destroy', () => { let hookRef: AfterRenderRef | null = null; let afterRenderCount = 0; @Component({ selector: 'comp', standalone: false, }) class Comp { constructor() { hookRef = afterRender(() => { afterRenderCount++; }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); expect(afterRenderCount).toBe(0); TestBed.inject(ApplicationRef).tick(); expect(afterRenderCount).toBe(1); TestBed.inject(ApplicationRef).tick(); expect(afterRenderCount).toBe(2); hookRef!.destroy(); TestBed.inject(ApplicationRef).tick(); expect(afterRenderCount).toBe(2); }); it('should defer nested hooks to the next cycle', () => { let outerHookCount = 0; let innerHookCount = 0; @Component({ selector: 'comp', standalone: false, }) class Comp { injector = inject(Injector); constructor() { afterRender(() => { outerHookCount++; afterNextRender( () => { innerHookCount++; }, {injector: this.injector}, ); }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); // It hasn't run at all expect(outerHookCount).toBe(0); expect(innerHookCount).toBe(0); // Running change detection (first time) TestBed.inject(ApplicationRef).tick(); expect(outerHookCount).toBe(1); expect(innerHookCount).toBe(0); // Running change detection (second time) TestBed.inject(ApplicationRef).tick(); expect(outerHookCount).toBe(2); expect(innerHookCount).toBe(1); // Running change detection (third time) TestBed.inject(ApplicationRef).tick(); expect(outerHookCount).toBe(3); expect(innerHookCount).toBe(2); }); it('should run outside of the Angular zone', () => { const zoneLog: boolean[] = []; @Component({ selector: 'comp', standalone: false, }) class Comp { constructor() { afterRender(() => { zoneLog.push(NgZone.isInAngularZone()); }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); expect(zoneLog).toEqual([]); TestBed.inject(NgZone).run(() => { TestBed.inject(ApplicationRef).tick(); expect(zoneLog).toEqual([false]); }); });
{ "end_byte": 11347, "start_byte": 1204, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/after_render_hook_spec.ts" }
angular/packages/core/test/acceptance/after_render_hook_spec.ts_11355_21668
it('should propagate errors to the ErrorHandler', () => { const log: string[] = []; @Injectable() class FakeErrorHandler extends ErrorHandler { override handleError(error: any): void { log.push((error as Error).message); } } @Component({ template: '', standalone: false, }) class Comp { constructor() { afterRender(() => { log.push('pass 1'); }); afterRender(() => { throw new Error('fail 1'); }); afterRender(() => { log.push('pass 2'); }); afterRender(() => { throw new Error('fail 2'); }); } } TestBed.configureTestingModule({ declarations: [Comp], providers: [COMMON_PROVIDERS, {provide: ErrorHandler, useClass: FakeErrorHandler}], }); createAndAttachComponent(Comp); expect(log).toEqual([]); TestBed.inject(ApplicationRef).tick(); expect(log).toEqual(['pass 1', 'fail 1', 'pass 2', 'fail 2']); }); it('should run callbacks in the correct phase and order', () => { const log: string[] = []; @Component({ selector: 'root', template: `<comp-a></comp-a><comp-b></comp-b>`, standalone: false, }) class Root {} @Component({ selector: 'comp-a', standalone: false, }) class CompA { constructor() { afterRender({ earlyRead: () => { log.push('early-read-1'); }, }); afterRender({ write: () => { log.push('write-1'); }, }); afterRender({ mixedReadWrite: () => { log.push('mixed-read-write-1'); }, }); afterRender({ read: () => { log.push('read-1'); }, }); } } @Component({ selector: 'comp-b', standalone: false, }) class CompB { constructor() { afterRender({ read: () => { log.push('read-2'); }, }); afterRender({ mixedReadWrite: () => { log.push('mixed-read-write-2'); }, }); afterRender({ write: () => { log.push('write-2'); }, }); afterRender({ earlyRead: () => { log.push('early-read-2'); }, }); } } TestBed.configureTestingModule({ declarations: [Root, CompA, CompB], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Root); expect(log).toEqual([]); TestBed.inject(ApplicationRef).tick(); expect(log).toEqual([ 'early-read-1', 'early-read-2', 'write-1', 'write-2', 'mixed-read-write-1', 'mixed-read-write-2', 'read-1', 'read-2', ]); }); it('should run callbacks in the correct phase and order when using deprecated phase flag', () => { const log: string[] = []; @Component({ selector: 'root', template: `<comp-a></comp-a><comp-b></comp-b>`, standalone: false, }) class Root {} @Component({ selector: 'comp-a', standalone: false, }) class CompA { constructor() { afterRender( () => { log.push('early-read-1'); }, {phase: AfterRenderPhase.EarlyRead}, ); afterRender( () => { log.push('write-1'); }, {phase: AfterRenderPhase.Write}, ); afterRender( () => { log.push('mixed-read-write-1'); }, {phase: AfterRenderPhase.MixedReadWrite}, ); afterRender( () => { log.push('read-1'); }, {phase: AfterRenderPhase.Read}, ); } } @Component({ selector: 'comp-b', standalone: false, }) class CompB { constructor() { afterRender( () => { log.push('read-2'); }, {phase: AfterRenderPhase.Read}, ); afterRender( () => { log.push('mixed-read-write-2'); }, {phase: AfterRenderPhase.MixedReadWrite}, ); afterRender( () => { log.push('write-2'); }, {phase: AfterRenderPhase.Write}, ); afterRender( () => { log.push('early-read-2'); }, {phase: AfterRenderPhase.EarlyRead}, ); } } TestBed.configureTestingModule({ declarations: [Root, CompA, CompB], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Root); expect(log).toEqual([]); TestBed.inject(ApplicationRef).tick(); expect(log).toEqual([ 'early-read-1', 'early-read-2', 'write-1', 'write-2', 'mixed-read-write-1', 'mixed-read-write-2', 'read-1', 'read-2', ]); }); it('should schedule callbacks for multiple phases at once', () => { const log: string[] = []; @Component({ selector: 'comp', standalone: false, }) class Comp { constructor() { afterRender({ earlyRead: () => { log.push('early-read-1'); }, write: () => { log.push('write-1'); }, mixedReadWrite: () => { log.push('mixed-read-write-1'); }, read: () => { log.push('read-1'); }, }); afterRender(() => { log.push('mixed-read-write-2'); }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); expect(log).toEqual([]); TestBed.inject(ApplicationRef).tick(); expect(log).toEqual([ 'early-read-1', 'write-1', 'mixed-read-write-1', 'mixed-read-write-2', 'read-1', ]); }); it('should pass data between phases', () => { const log: string[] = []; @Component({ selector: 'comp', standalone: false, }) class Comp { constructor() { afterRender({ earlyRead: () => 'earlyRead result', write: (results) => { log.push(`results for write: ${results}`); return 5; }, mixedReadWrite: (results) => { log.push(`results for mixedReadWrite: ${results}`); return undefined; }, read: (results) => { log.push(`results for read: ${results}`); }, }); afterRender({ earlyRead: () => 'earlyRead 2 result', read: (results) => { log.push(`results for read 2: ${results}`); }, }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); expect(log).toEqual([]); TestBed.inject(ApplicationRef).tick(); expect(log).toEqual([ 'results for write: earlyRead result', 'results for mixedReadWrite: 5', 'results for read: undefined', 'results for read 2: earlyRead 2 result', ]); }); describe('throw error inside reactive context', () => { it('inside template effect', () => { @Component({ template: `{{someFn()}}`, standalone: false, }) class TestCmp { someFn() { afterRender(() => {}); } } const fixture = TestBed.createComponent(TestCmp); expect(() => fixture.detectChanges()).toThrowError( /afterRender\(\) cannot be called from within a reactive context/, ); }); it('inside computed', () => { const testComputed = computed(() => { afterRender(() => {}); }); expect(() => testComputed()).toThrowError( /afterRender\(\) cannot be called from within a reactive context/, ); }); it('inside effect', () => { @Component({ template: ``, standalone: false, }) class TestCmp { constructor() { effect(() => { this.someFnThatWillScheduleAfterRender(); }); } someFnThatWillScheduleAfterRender() { afterRender(() => {}); } } TestBed.configureTestingModule({ providers: [ { provide: ErrorHandler, useClass: class extends ErrorHandler { override handleError(e: Error) { throw e; } }, }, ], }); const fixture = TestBed.createComponent(TestCmp); expect(() => fixture.detectChanges()).toThrowError( /afterRender\(\) cannot be called from within a reactive context/, ); }); });
{ "end_byte": 21668, "start_byte": 11355, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/after_render_hook_spec.ts" }
angular/packages/core/test/acceptance/after_render_hook_spec.ts_21676_22995
it('should not destroy automatically if manualCleanup is set', () => { let afterRenderRef: AfterRenderRef | null = null; let count = 0; @Component({selector: 'comp', template: '', standalone: false}) class Comp { constructor() { afterRenderRef = afterRender(() => count++, {manualCleanup: true}); } } @Component({ imports: [Comp], standalone: false, template: ` @if (shouldShow) { <comp/> } `, }) class App { shouldShow = true; } TestBed.configureTestingModule({ declarations: [App, Comp], ...COMMON_CONFIGURATION, }); const component = createAndAttachComponent(App); const appRef = TestBed.inject(ApplicationRef); expect(count).toBe(0); appRef.tick(); expect(count).toBe(1); component.instance.shouldShow = false; component.changeDetectorRef.detectChanges(); appRef.tick(); expect(count).toBe(2); appRef.tick(); expect(count).toBe(3); // Ensure that manual destruction still works. afterRenderRef!.destroy(); appRef.tick(); expect(count).toBe(3); }); });
{ "end_byte": 22995, "start_byte": 21676, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/after_render_hook_spec.ts" }
angular/packages/core/test/acceptance/after_render_hook_spec.ts_23001_32906
describe('afterNextRender', () => { it('should run with the correct timing', () => { @Component({ selector: 'dynamic-comp', standalone: false, }) class DynamicComp { afterRenderCount = 0; constructor() { afterNextRender(() => { this.afterRenderCount++; }); } } @Component({ selector: 'comp', standalone: false, }) class Comp { afterRenderCount = 0; changeDetectorRef = inject(ChangeDetectorRef); viewContainerRef = inject(ViewContainerRef); constructor() { afterNextRender(() => { this.afterRenderCount++; }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); const component = createAndAttachComponent(Comp); const compInstance = component.instance; const viewContainerRef = compInstance.viewContainerRef; const dynamicCompRef = viewContainerRef.createComponent(DynamicComp); // It hasn't run at all expect(dynamicCompRef.instance.afterRenderCount).toBe(0); expect(compInstance.afterRenderCount).toBe(0); // Running change detection at the dynamicCompRef level dynamicCompRef.changeDetectorRef.detectChanges(); expect(dynamicCompRef.instance.afterRenderCount).toBe(0); expect(compInstance.afterRenderCount).toBe(0); // Running change detection at the compInstance level compInstance.changeDetectorRef.detectChanges(); expect(dynamicCompRef.instance.afterRenderCount).toBe(0); expect(compInstance.afterRenderCount).toBe(0); // Running change detection at the Application level TestBed.inject(ApplicationRef).tick(); expect(dynamicCompRef.instance.afterRenderCount).toBe(1); expect(compInstance.afterRenderCount).toBe(1); // Running change detection after removing view. viewContainerRef.remove(); TestBed.inject(ApplicationRef).tick(); expect(dynamicCompRef.instance.afterRenderCount).toBe(1); expect(compInstance.afterRenderCount).toBe(1); }); it('should not run until views have stabilized', async () => { // This test uses two components, a Reader and Writer, and arranges CD so that Reader // is checked, and then Writer makes Reader dirty again. An `afterNextRender` should not run // until Reader has been fully refreshed. TestBed.configureTestingModule(COMMON_CONFIGURATION); const appRef = TestBed.inject(ApplicationRef); const counter = signal(0); @Component({standalone: true, template: '{{counter()}}'}) class Reader { counter = counter; } @Component({standalone: true, template: ''}) class Writer { ngAfterViewInit(): void { counter.set(1); } } const ref = createAndAttachComponent(Reader); createAndAttachComponent(Writer); let textAtAfterRender: string = ''; afterNextRender( () => { // Reader should've been fully refreshed, so capture its template state at this moment. textAtAfterRender = ref.location.nativeElement.innerHTML; }, {injector: appRef.injector}, ); await appRef.whenStable(); expect(textAtAfterRender).toBe('1'); }); it('should run all hooks after outer change detection', () => { let log: string[] = []; @Component({ selector: 'child-comp', standalone: false, }) class ChildComp { constructor() { afterNextRender(() => { log.push('child-comp'); }); } } @Component({ selector: 'parent', template: `<child-comp></child-comp>`, standalone: false, }) class ParentComp { changeDetectorRef = inject(ChangeDetectorRef); constructor() { afterNextRender(() => { log.push('parent-comp'); }); } ngOnInit() { log.push('pre-cd'); this.changeDetectorRef.detectChanges(); log.push('post-cd'); } } TestBed.configureTestingModule({ declarations: [ChildComp, ParentComp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(ParentComp); expect(log).toEqual([]); TestBed.inject(ApplicationRef).tick(); expect(log).toEqual(['pre-cd', 'post-cd', 'parent-comp', 'child-comp']); }); it('should unsubscribe when calling destroy', () => { let hookRef: AfterRenderRef | null = null; let afterRenderCount = 0; @Component({ selector: 'comp', standalone: false, }) class Comp { constructor() { hookRef = afterNextRender(() => { afterRenderCount++; }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); expect(afterRenderCount).toBe(0); hookRef!.destroy(); TestBed.inject(ApplicationRef).tick(); expect(afterRenderCount).toBe(0); }); it('should throw if called recursively', () => { class RethrowErrorHandler extends ErrorHandler { override handleError(error: any): void { throw error; } } @Component({ selector: 'comp', standalone: false, }) class Comp { appRef = inject(ApplicationRef); injector = inject(EnvironmentInjector); ngOnInit() { afterNextRender( () => { this.appRef.tick(); }, {injector: this.injector}, ); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, providers: [ {provide: ErrorHandler, useClass: RethrowErrorHandler}, ...COMMON_CONFIGURATION.providers, ], }); createAndAttachComponent(Comp); expect(() => TestBed.inject(ApplicationRef).tick()).toThrowError( /ApplicationRef.tick is called recursively/, ); }); it('should defer nested hooks to the next cycle', () => { let outerHookCount = 0; let innerHookCount = 0; @Component({ selector: 'comp', standalone: false, }) class Comp { injector = inject(Injector); constructor() { afterNextRender(() => { outerHookCount++; afterNextRender( () => { innerHookCount++; }, {injector: this.injector}, ); }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); // It hasn't run at all expect(outerHookCount).toBe(0); expect(innerHookCount).toBe(0); // Running change detection (first time) TestBed.inject(ApplicationRef).tick(); expect(outerHookCount).toBe(1); expect(innerHookCount).toBe(0); // Running change detection (second time) TestBed.inject(ApplicationRef).tick(); expect(outerHookCount).toBe(1); expect(innerHookCount).toBe(1); // Running change detection (third time) TestBed.inject(ApplicationRef).tick(); expect(outerHookCount).toBe(1); expect(innerHookCount).toBe(1); }); it('should run outside of the Angular zone', () => { const zoneLog: boolean[] = []; @Component({ selector: 'comp', standalone: false, }) class Comp { constructor() { afterNextRender(() => { zoneLog.push(NgZone.isInAngularZone()); }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); expect(zoneLog).toEqual([]); TestBed.inject(NgZone).run(() => { TestBed.inject(ApplicationRef).tick(); expect(zoneLog).toEqual([false]); }); }); it('should propagate errors to the ErrorHandler', () => { const log: string[] = []; class FakeErrorHandler extends ErrorHandler { override handleError(error: any): void { log.push((error as Error).message); } } @Component({ template: '', standalone: false, }) class Comp { constructor() { afterNextRender(() => { log.push('pass 1'); }); afterNextRender(() => { throw new Error('fail 1'); }); afterNextRender(() => { log.push('pass 2'); }); afterNextRender(() => { throw new Error('fail 2'); }); } } TestBed.configureTestingModule({ declarations: [Comp], providers: [COMMON_PROVIDERS, {provide: ErrorHandler, useClass: FakeErrorHandler}], }); createAndAttachComponent(Comp); expect(log).toEqual([]); TestBed.inject(ApplicationRef).tick(); expect(log).toEqual(['pass 1', 'fail 1', 'pass 2', 'fail 2']); });
{ "end_byte": 32906, "start_byte": 23001, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/after_render_hook_spec.ts" }
angular/packages/core/test/acceptance/after_render_hook_spec.ts_32914_42511
it('should run callbacks in the correct phase and order', () => { const log: string[] = []; @Component({ selector: 'root', template: `<comp-a></comp-a><comp-b></comp-b>`, standalone: false, }) class Root {} @Component({ selector: 'comp-a', standalone: false, }) class CompA { constructor() { afterNextRender({ earlyRead: () => { log.push('early-read-1'); }, }); afterNextRender({ write: () => { log.push('write-1'); }, }); afterNextRender({ mixedReadWrite: () => { log.push('mixed-read-write-1'); }, }); afterNextRender({ read: () => { log.push('read-1'); }, }); } } @Component({ selector: 'comp-b', standalone: false, }) class CompB { constructor() { afterNextRender({ read: () => { log.push('read-2'); }, }); afterNextRender({ mixedReadWrite: () => { log.push('mixed-read-write-2'); }, }); afterNextRender({ write: () => { log.push('write-2'); }, }); afterNextRender({ earlyRead: () => { log.push('early-read-2'); }, }); } } TestBed.configureTestingModule({ declarations: [Root, CompA, CompB], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Root); expect(log).toEqual([]); TestBed.inject(ApplicationRef).tick(); expect(log).toEqual([ 'early-read-1', 'early-read-2', 'write-1', 'write-2', 'mixed-read-write-1', 'mixed-read-write-2', 'read-1', 'read-2', ]); }); it('should invoke all the callbacks once when they are registered at the same time', () => { const log: string[] = []; @Component({ template: '', standalone: false, }) class Comp { constructor() { afterNextRender({ earlyRead: () => { log.push('early-read'); }, write: () => { log.push('write'); }, mixedReadWrite: () => { log.push('mixed-read-write'); }, read: () => { log.push('read'); }, }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); expect(log).toEqual([]); TestBed.inject(ApplicationRef).tick(); expect(log).toEqual(['early-read', 'write', 'mixed-read-write', 'read']); TestBed.inject(ApplicationRef).tick(); expect(log).toEqual(['early-read', 'write', 'mixed-read-write', 'read']); }); it('should invoke all the callbacks each time when they are registered at the same time', () => { const log: string[] = []; @Component({ template: '', standalone: false, }) class Comp { constructor() { afterRender({ earlyRead: () => { log.push('early-read'); return 'early'; }, write: (previous) => { log.push(`previous was ${previous}, this is write`); return 'write'; }, mixedReadWrite: (previous) => { log.push(`previous was ${previous}, this is mixed-read-write`); return 'mixed'; }, read: (previous) => { log.push(`previous was ${previous}, this is read`); return 'read'; }, }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); expect(log).toEqual([]); TestBed.inject(ApplicationRef).tick(); expect(log).toEqual([ 'early-read', 'previous was early, this is write', 'previous was write, this is mixed-read-write', 'previous was mixed, this is read', ]); TestBed.inject(ApplicationRef).tick(); expect(log).toEqual([ 'early-read', 'previous was early, this is write', 'previous was write, this is mixed-read-write', 'previous was mixed, this is read', 'early-read', 'previous was early, this is write', 'previous was write, this is mixed-read-write', 'previous was mixed, this is read', ]); }); }); it('allows writing to a signal in afterRender', () => { const counter = signal(0); @Component({ selector: 'test-component', standalone: true, template: ` {{counter()}} `, }) class TestCmp { counter = counter; injector = inject(EnvironmentInjector); ngOnInit() { afterNextRender( () => { this.counter.set(1); }, {injector: this.injector}, ); } } TestBed.configureTestingModule({ providers: [{provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID}], }); const fixture = TestBed.createComponent(TestCmp); const appRef = TestBed.inject(ApplicationRef); appRef.attachView(fixture.componentRef.hostView); appRef.tick(); expect(fixture.nativeElement.innerText).toBe('1'); }); it('allows updating state and calling markForCheck in afterRender', async () => { @Component({ selector: 'test-component', standalone: true, template: ` {{counter}} `, }) class TestCmp { counter = 0; injector = inject(EnvironmentInjector); cdr = inject(ChangeDetectorRef); ngOnInit() { afterNextRender( () => { this.counter = 1; this.cdr.markForCheck(); }, {injector: this.injector}, ); } } TestBed.configureTestingModule({ providers: [{provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID}], }); const fixture = TestBed.createComponent(TestCmp); const appRef = TestBed.inject(ApplicationRef); appRef.attachView(fixture.componentRef.hostView); await appRef.whenStable(); expect(fixture.nativeElement.innerText).toBe('1'); }); it('allows updating state and calling markForCheck in afterRender, outside of change detection', async () => { const counter = signal(0); @Component({ selector: 'test-component', standalone: true, template: `{{counter()}}`, }) class TestCmp { injector = inject(EnvironmentInjector); counter = counter; async ngOnInit() { // push the render hook to a time outside of change detection await new Promise<void>((resolve) => setTimeout(resolve)); afterNextRender( () => { counter.set(1); }, {injector: this.injector}, ); } } TestBed.configureTestingModule({ providers: [{provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID}], }); const fixture = TestBed.createComponent(TestCmp); const appRef = TestBed.inject(ApplicationRef); appRef.attachView(fixture.componentRef.hostView); await new Promise<void>((resolve) => { TestBed.runInInjectionContext(() => { effect(() => { if (counter() === 1) { resolve(); } }); }); }); await firstValueFrom(appRef.isStable.pipe(filter((stable) => stable))); expect(fixture.nativeElement.innerText).toBe('1'); }); it('throws error when causing infinite updates', () => { const counter = signal(0); @Component({ selector: 'test-component', standalone: true, template: ` {{counter()}} `, }) class TestCmp { counter = counter; injector = inject(EnvironmentInjector); ngOnInit() { afterRender( () => { this.counter.update((v) => v + 1); }, {injector: this.injector}, ); } } TestBed.configureTestingModule({ providers: [ {provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID}, { provide: ErrorHandler, useClass: class extends ErrorHandler { override handleError(error: any) { throw error; } }, }, ], }); const fixture = TestBed.createComponent(TestCmp); const appRef = TestBed.inject(ApplicationRef); appRef.attachView(fixture.componentRef.hostView); expect(() => { appRef.tick(); }).toThrowError(/NG0103.*(Infinite change detection while refreshing application views)/); });
{ "end_byte": 42511, "start_byte": 32914, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/after_render_hook_spec.ts" }
angular/packages/core/test/acceptance/after_render_hook_spec.ts_42517_44966
it('should destroy after the hook has run', () => { let hookRef: AfterRenderRef | null = null; let afterRenderCount = 0; @Component({selector: 'comp', standalone: false}) class Comp { constructor() { hookRef = afterNextRender(() => { afterRenderCount++; }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); const appRef = TestBed.inject(ApplicationRef); const destroySpy = spyOn(hookRef!, 'destroy').and.callThrough(); expect(afterRenderCount).toBe(0); expect(destroySpy).not.toHaveBeenCalled(); // Run once and ensure that it was called and then cleaned up. appRef.tick(); expect(afterRenderCount).toBe(1); expect(destroySpy).toHaveBeenCalledTimes(1); // Make sure we're not retaining it. appRef.tick(); expect(afterRenderCount).toBe(1); expect(destroySpy).toHaveBeenCalledTimes(1); }); }); describe('server', () => { const COMMON_CONFIGURATION = { providers: [{provide: PLATFORM_ID, useValue: PLATFORM_SERVER_ID}], }; describe('afterRender', () => { it('should not run', () => { let afterRenderCount = 0; @Component({ selector: 'comp', standalone: false, }) class Comp { constructor() { afterRender(() => { afterRenderCount++; }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); TestBed.inject(ApplicationRef).tick(); expect(afterRenderCount).toBe(0); }); }); describe('afterNextRender', () => { it('should not run', () => { let afterRenderCount = 0; @Component({ selector: 'comp', standalone: false, }) class Comp { constructor() { afterNextRender(() => { afterRenderCount++; }); } } TestBed.configureTestingModule({ declarations: [Comp], ...COMMON_CONFIGURATION, }); createAndAttachComponent(Comp); TestBed.inject(ApplicationRef).tick(); expect(afterRenderCount).toBe(0); }); }); }); });
{ "end_byte": 44966, "start_byte": 42517, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/after_render_hook_spec.ts" }
angular/packages/core/test/acceptance/text_spec.ts_0_5783
/** * @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 {TestBed} from '@angular/core/testing'; import {of} from 'rxjs'; describe('text instructions', () => { it('should handle all flavors of interpolated text', () => { @Component({ template: ` <div>a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h{{eight}}i{{nine}}j</div> <div>a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h{{eight}}i</div> <div>a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g{{seven}}h</div> <div>a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f{{six}}g</div> <div>a{{one}}b{{two}}c{{three}}d{{four}}e{{five}}f</div> <div>a{{one}}b{{two}}c{{three}}d{{four}}e</div> <div>a{{one}}b{{two}}c{{three}}d</div> <div>a{{one}}b{{two}}c</div> <div>a{{one}}b</div> <div>{{one}}</div> `, standalone: false, }) class App { one = 1; two = 2; three = 3; four = 4; five = 5; six = 6; seven = 7; eight = 8; nine = 9; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const allTextContent = Array.from( (fixture.nativeElement as HTMLElement).querySelectorAll('div'), ).map((div: HTMLDivElement) => div.textContent); expect(allTextContent).toEqual([ 'a1b2c3d4e5f6g7h8i9j', 'a1b2c3d4e5f6g7h8i', 'a1b2c3d4e5f6g7h', 'a1b2c3d4e5f6g', 'a1b2c3d4e5f', 'a1b2c3d4e', 'a1b2c3d', 'a1b2c', 'a1b', '1', ]); }); it('should handle piped values in interpolated text', () => { @Component({ template: ` <p>{{who | async}} sells {{(item | async)?.what}} down by the {{(item | async)?.where}}.</p> `, standalone: false, }) class App { who = of('Sally'); item = of({ what: 'seashells', where: 'seashore', }); } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const p = fixture.nativeElement.querySelector('p') as HTMLDivElement; expect(p.textContent).toBe('Sally sells seashells down by the seashore.'); }); it('should not sanitize urls in interpolated text', () => { @Component({ template: '<p>{{thisisfine}}</p>', standalone: false, }) class App { thisisfine = 'javascript:alert("image_of_dog_with_coffee_in_burning_building.gif")'; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const p = fixture.nativeElement.querySelector('p'); expect(p.textContent).toBe( 'javascript:alert("image_of_dog_with_coffee_in_burning_building.gif")', ); }); it('should not allow writing HTML in interpolated text', () => { @Component({ template: '<div>{{test}}</div>', standalone: false, }) class App { test = '<h1>LOL, big text</h1>'; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.innerHTML).toBe('&lt;h1&gt;LOL, big text&lt;/h1&gt;'); }); it('should stringify functions used in bindings', () => { @Component({ template: '<div>{{test}}</div>', standalone: false, }) class App { test = function foo() {}; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div'); expect(div.innerHTML).toBe(fixture.componentInstance.test.toString()); expect(div.innerHTML).toContain('foo'); }); it('should stringify an object using its toString method', () => { class TestObject { toString() { return 'toString'; } valueOf() { return 'valueOf'; } } @Component({ template: '{{object}}', standalone: false, }) class App { object = new TestObject(); } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('toString'); }); it('should stringify a symbol', () => { // This test is only valid on browsers that support Symbol. if (typeof Symbol === 'undefined') { return; } @Component({ template: '{{symbol}}', standalone: false, }) class App { symbol = Symbol('hello'); } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); // Note that this uses `toContain`, because a polyfilled `Symbol` produces something like // `Symbol(hello)_p.sc8s398cplk`, whereas the native one is `Symbol(hello)`. expect(fixture.nativeElement.textContent).toContain('Symbol(hello)'); }); it('should handle binding syntax used inside quoted text', () => { @Component({ template: `{{'Interpolations look like {{this}}'}}`, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Interpolations look like {{this}}'); }); });
{ "end_byte": 5783, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/text_spec.ts" }
angular/packages/core/test/acceptance/BUILD.bazel_0_2373
load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ng_module", "ts_library") package(default_visibility = ["//visibility:private"]) SPEC_FILES_WITH_FORWARD_REFS = [ "di_forward_ref_spec.ts", ] ts_library( name = "acceptance_lib", testonly = True, srcs = glob( ["**/*.ts"], exclude = SPEC_FILES_WITH_FORWARD_REFS, ), # Visible to //:saucelabs_unit_tests visibility = ["//:__pkg__"], deps = [ "//packages/animations", "//packages/animations/browser", "//packages/animations/browser/testing", "//packages/common", "//packages/common/locales", "//packages/compiler", "//packages/core", "//packages/core/primitives/signals", "//packages/core/src/util", "//packages/core/test/render3:matchers", "//packages/core/testing", "//packages/localize", "//packages/localize/init", "//packages/platform-browser", "//packages/platform-browser-dynamic", "//packages/platform-browser/animations", "//packages/platform-browser/testing", "//packages/platform-server", "//packages/private/testing", "//packages/router", "//packages/zone.js/lib:zone_d_ts", "@npm//rxjs", ], ) # Note: The `forward_ref` example tests are built through this `ng_module` sub-target. # This is done so that DI decorator/type metadata is processed manually by the compiler # ahead of time. We cannot rely on the official TypeScript decorator downlevel emit (for JIT), # as the output is not compatible with `forwardRef` and ES2015+. More details here: # https://github.com/angular/angular/commit/323651bd38909b0f4226bcb6c8f5abafa91cf9d9. # https://github.com/microsoft/TypeScript/issues/27519. ng_module( name = "forward_ref_test_lib", testonly = True, srcs = SPEC_FILES_WITH_FORWARD_REFS, deps = [ "//packages/core", "//packages/core/testing", ], ) jasmine_node_test( name = "acceptance", bootstrap = ["//tools/testing:node"], deps = [ ":acceptance_lib", ":forward_ref_test_lib", "//packages/zone.js/lib:zone_d_ts", "@npm//source-map", ], ) karma_web_test_suite( name = "acceptance_web", deps = [ ":acceptance_lib", ":forward_ref_test_lib", ], )
{ "end_byte": 2373, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/BUILD.bazel" }
angular/packages/core/test/acceptance/security_spec.ts_0_3886
/** * @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 {NgIf} from '@angular/common'; import { Component, Directive, inject, TemplateRef, Type, ViewChild, ViewContainerRef, } from '@angular/core'; import {RuntimeErrorCode} from '@angular/core/src/errors'; import {global} from '@angular/core/src/util/global'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {DomSanitizer} from '@angular/platform-browser'; describe('comment node text escaping', () => { // see: https://html.spec.whatwg.org/multipage/syntax.html#comments [ '>', // self closing '-->', // standard closing '--!>', // alternate closing '<!-- -->', // embedded comment. ].forEach((xssValue) => { it( 'should not be possible to do XSS through comment reflect data when writing: ' + xssValue, () => { @Component({ template: `<div><span *ngIf="xssValue"></span><div>`, standalone: false, }) class XSSComp { // ngIf serializes the `xssValue` into a comment for debugging purposes. xssValue: string = xssValue + '<script>"evil"</script>'; } TestBed.configureTestingModule({declarations: [XSSComp]}); const fixture = TestBed.createComponent(XSSComp); fixture.detectChanges(); const div = fixture.nativeElement.querySelector('div') as HTMLElement; // Serialize into a string to mimic SSR serialization. const html = div.innerHTML; // This must be escaped or we have XSS. expect(html).not.toContain('--><script'); // Now parse it back into DOM (from string) div.innerHTML = html; // Verify that we did not accidentally deserialize the `<script>` const script = div.querySelector('script'); expect(script).toBeFalsy(); }, ); }); }); describe('iframe processing', () => { function getErrorMessageRegexp() { const errorMessagePart = 'NG0' + Math.abs(RuntimeErrorCode.UNSAFE_IFRAME_ATTRS).toString(); return new RegExp(errorMessagePart); } function ensureNoIframePresent(fixture?: ComponentFixture<unknown>) { // Note: a `fixture` may not exist in case an error was thrown at creation time. const iframe = fixture?.nativeElement.querySelector('iframe'); expect(!!iframe).toBeFalse(); } function expectIframeCreationToFail<T>(component: Type<T>): ComponentFixture<T> { let fixture: ComponentFixture<T> | undefined; expect(() => { fixture = TestBed.createComponent(component); fixture.detectChanges(); }).toThrowError(getErrorMessageRegexp()); ensureNoIframePresent(fixture); return fixture!; } function expectIframeToBeCreated<T>( component: Type<T>, attrsToCheck: {[key: string]: string}, ): ComponentFixture<T> { let fixture: ComponentFixture<T>; expect(() => { fixture = TestBed.createComponent(component); fixture.detectChanges(); }).not.toThrow(); const iframe = fixture!.nativeElement.querySelector('iframe'); for (const [attrName, attrValue] of Object.entries(attrsToCheck)) { expect(iframe[attrName]).toEqual(attrValue); } return fixture!; } // *Must* be in sync with the `SECURITY_SENSITIVE_ATTRS` list // from the `packages/compiler/src/schema/dom_security_schema.ts`. const SECURITY_SENSITIVE_ATTRS = [ 'sandbox', 'allow', 'allowFullscreen', 'referrerPolicy', 'csp', 'fetchPriority', ]; const TEST_IFRAME_URL = 'https://angular.io/assets/images/logos/angular/angular.png'; let oldNgDevMode!: typeof ngDevMode; beforeAll(() => { oldNgDevMode = ngDevMode; }); afterAll(() => { global['ngDevMode'] = oldNgDevMode; });
{ "end_byte": 3886, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/security_spec.ts" }
angular/packages/core/test/acceptance/security_spec.ts_3890_13584
[true, false].forEach((devModeFlag) => { beforeAll(() => { global['ngDevMode'] = devModeFlag; // TestBed and JIT compilation have some dependencies on the ngDevMode state, so we need to // reset TestBed to ensure we get a 'clean' JIT compilation under the new rules. TestBed.resetTestingModule(); }); describe(`with ngDevMode = ${devModeFlag}`, () => { SECURITY_SENSITIVE_ATTRS.forEach((securityAttr: string) => { ['src', 'srcdoc'].forEach((srcAttr: string) => { it( `should work when a security-sensitive attribute is set ` + `as a static attribute (checking \`${securityAttr}\`)`, () => { @Component({ standalone: true, selector: 'my-comp', template: ` <iframe ${srcAttr}="${TEST_IFRAME_URL}" ${securityAttr}=""> </iframe>`, }) class IframeComp {} expectIframeToBeCreated(IframeComp, {[srcAttr]: TEST_IFRAME_URL}); }, ); it( `should work when a security-sensitive attribute is set ` + `as a static attribute (checking \`${securityAttr}\` and ` + `making sure it's case-insensitive)`, () => { @Component({ standalone: true, selector: 'my-comp', template: ` <iframe ${srcAttr}="${TEST_IFRAME_URL}" ${securityAttr.toUpperCase()}=""> </iframe>`, }) class IframeComp {} expectIframeToBeCreated(IframeComp, {[srcAttr]: TEST_IFRAME_URL}); }, ); it( `should error when a security-sensitive attribute is applied ` + `using a property binding (checking \`${securityAttr}\`)`, () => { @Component({ standalone: true, selector: 'my-comp', template: `<iframe ${srcAttr}="${TEST_IFRAME_URL}" [${securityAttr}]="''"></iframe>`, }) class IframeComp {} expectIframeCreationToFail(IframeComp); }, ); it( `should error when a security-sensitive attribute is applied ` + `using a property interpolation (checking \`${securityAttr}\`)`, () => { @Component({ standalone: true, selector: 'my-comp', template: `<iframe ${srcAttr}="${TEST_IFRAME_URL}" ${securityAttr}="{{''}}"></iframe>`, }) class IframeComp {} expectIframeCreationToFail(IframeComp); }, ); it( `should error when a security-sensitive attribute is applied ` + `using a property binding (checking \`${securityAttr}\`, making ` + `sure it's case-insensitive)`, () => { @Component({ standalone: true, selector: 'my-comp', template: ` <iframe ${srcAttr}="${TEST_IFRAME_URL}" [${securityAttr.toUpperCase()}]="''" ></iframe> `, }) class IframeComp {} expectIframeCreationToFail(IframeComp); }, ); it( `should error when a security-sensitive attribute is applied ` + `using a property binding (checking \`${securityAttr}\`)`, () => { @Component({ standalone: true, selector: 'my-comp', template: ` <iframe ${srcAttr}="${TEST_IFRAME_URL}" [attr.${securityAttr}]="''" ></iframe> `, }) class IframeComp {} expectIframeCreationToFail(IframeComp); }, ); it( `should error when a security-sensitive attribute is applied ` + `using a property binding (checking \`${securityAttr}\`, making ` + `sure it's case-insensitive)`, () => { @Component({ standalone: true, selector: 'my-comp', template: ` <iframe ${srcAttr}="${TEST_IFRAME_URL}" [attr.${securityAttr.toUpperCase()}]="''" ></iframe> `, }) class IframeComp {} expectIframeCreationToFail(IframeComp); }, ); it(`should allow changing \`${srcAttr}\` after initial render`, () => { @Component({ standalone: true, selector: 'my-comp', template: ` <iframe ${securityAttr}="allow-forms" [${srcAttr}]="src"> </iframe> `, }) class IframeComp { private sanitizer = inject(DomSanitizer); src = this.sanitizeFn(TEST_IFRAME_URL); get sanitizeFn() { return srcAttr === 'src' ? this.sanitizer.bypassSecurityTrustResourceUrl : this.sanitizer.bypassSecurityTrustHtml; } } const fixture = expectIframeToBeCreated(IframeComp, {[srcAttr]: TEST_IFRAME_URL}); const component = fixture.componentInstance; // Changing `src` or `srcdoc` is allowed. const newUrl = 'https://angular.io/about?group=Angular'; component.src = component.sanitizeFn(newUrl); expect(() => fixture.detectChanges()).not.toThrow(); expect(fixture.nativeElement.querySelector('iframe')[srcAttr]).toEqual(newUrl); }); }); }); it('should work when a directive sets a security-sensitive attribute as a static attribute', () => { @Directive({ standalone: true, selector: '[dir]', host: { 'src': TEST_IFRAME_URL, 'sandbox': '', }, }) class IframeDir {} @Component({ standalone: true, imports: [IframeDir], selector: 'my-comp', template: '<iframe dir></iframe>', }) class IframeComp {} expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}); }); it('should work when a directive sets a security-sensitive host attribute on a non-iframe element', () => { @Directive({ standalone: true, selector: '[dir]', host: { 'src': TEST_IFRAME_URL, 'sandbox': '', }, }) class Dir {} @Component({ standalone: true, imports: [Dir], selector: 'my-comp', template: '<img dir>', }) class NonIframeComp {} const fixture = TestBed.createComponent(NonIframeComp); fixture.detectChanges(); expect(fixture.nativeElement.firstChild.src).toEqual(TEST_IFRAME_URL); }); it( 'should work when a security-sensitive attribute on an <iframe> ' + 'which also has a structural directive (*ngIf)', () => { @Component({ standalone: true, imports: [NgIf], selector: 'my-comp', template: `<iframe *ngIf="visible" src="${TEST_IFRAME_URL}" sandbox=""></iframe>`, }) class IframeComp { visible = true; } expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}); }, ); it('should work when a security-sensitive attribute is set between `src` and `srcdoc`', () => { @Component({ standalone: true, selector: 'my-comp', template: `<iframe src="${TEST_IFRAME_URL}" sandbox srcdoc="Hi!"></iframe>`, }) class IframeComp {} expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}); }); it('should work when a directive sets a security-sensitive attribute before setting `src`', () => { @Directive({ standalone: true, selector: '[dir]', host: { 'sandbox': '', 'src': TEST_IFRAME_URL, }, }) class IframeDir {} @Component({ standalone: true, imports: [IframeDir], selector: 'my-comp', template: '<iframe dir></iframe>', }) class IframeComp {} expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}); }); it( 'should work when a directive sets an `src` and ' + 'there was a security-sensitive attribute set in a template' + '(directive attribute after `sandbox`)', () => { @Directive({ standalone: true, selector: '[dir]', host: { 'src': TEST_IFRAME_URL, }, }) class IframeDir {} @Component({ standalone: true, imports: [IframeDir], selector: 'my-comp', template: '<iframe sandbox dir></iframe>', }) class IframeComp {} expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}); }, );
{ "end_byte": 13584, "start_byte": 3890, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/security_spec.ts" }
angular/packages/core/test/acceptance/security_spec.ts_13592_21826
it( 'should error when a directive sets a security-sensitive attribute ' + "as an attribute binding (checking that it's case-insensitive)", () => { @Directive({ standalone: true, selector: '[dir]', host: { '[attr.SANDBOX]': "''", }, }) class IframeDir {} @Component({ standalone: true, imports: [IframeDir], selector: 'my-comp', template: `<IFRAME dir src="${TEST_IFRAME_URL}"></IFRAME>`, }) class IframeComp {} expectIframeCreationToFail(IframeComp); }, ); it( 'should work when a directive sets an `src` and ' + 'there was a security-sensitive attribute set in a template' + '(directive attribute before `sandbox`)', () => { @Directive({ standalone: true, selector: '[dir]', host: { 'src': TEST_IFRAME_URL, }, }) class IframeDir {} @Component({ standalone: true, imports: [IframeDir], selector: 'my-comp', template: '<iframe dir sandbox></iframe>', }) class IframeComp {} expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}); }, ); it( 'should work when a directive sets a security-sensitive attribute and ' + 'there was an `src` attribute set in a template' + '(directive attribute after `src`)', () => { @Directive({ standalone: true, selector: '[dir]', host: { 'sandbox': '', }, }) class IframeDir {} @Component({ standalone: true, imports: [IframeDir], selector: 'my-comp', template: `<iframe src="${TEST_IFRAME_URL}" dir></iframe>`, }) class IframeComp {} expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}); }, ); it('should work when a security-sensitive attribute is set as a static attribute', () => { @Component({ standalone: true, selector: 'my-comp', template: ` <iframe referrerPolicy="no-referrer" src="${TEST_IFRAME_URL}"></iframe> `, }) class IframeComp {} expectIframeToBeCreated(IframeComp, { src: TEST_IFRAME_URL, referrerPolicy: 'no-referrer', }); }); it( 'should error when a security-sensitive attribute is set ' + 'as a property binding and an <iframe> is wrapped into another element', () => { @Component({ standalone: true, selector: 'my-comp', template: ` <section> <iframe src="${TEST_IFRAME_URL}" [referrerPolicy]="'no-referrer'" ></iframe> </section>`, }) class IframeComp {} expectIframeCreationToFail(IframeComp); }, ); it( 'should work when a directive sets a security-sensitive attribute and ' + 'there was an `src` attribute set in a template' + '(directive attribute before `src`)', () => { @Directive({ standalone: true, selector: '[dir]', host: { 'sandbox': '', }, }) class IframeDir {} @Component({ standalone: true, imports: [IframeDir], selector: 'my-comp', template: `<iframe dir src="${TEST_IFRAME_URL}"></iframe>`, }) class IframeComp {} expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}); }, ); it( 'should work when a directive that sets a security-sensitive attribute goes ' + 'before the directive that sets an `src` attribute value', () => { @Directive({ standalone: true, selector: '[set-src]', host: { 'src': TEST_IFRAME_URL, }, }) class DirThatSetsSrc {} @Directive({ standalone: true, selector: '[set-sandbox]', host: { 'sandbox': '', }, }) class DirThatSetsSandbox {} @Component({ standalone: true, imports: [DirThatSetsSandbox, DirThatSetsSrc], selector: 'my-comp', // Important note: even though the `set-sandbox` goes after the `set-src`, // the directive matching order (thus the order of host attributes) is // based on the imports order, so the `sandbox` gets set first and the `src` second. template: '<iframe set-src set-sandbox></iframe>', }) class IframeComp {} expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}); }, ); it( 'should work when a directive that sets a security-sensitive attribute has ' + 'a host directive that sets an `src` attribute value', () => { @Directive({ standalone: true, selector: '[set-src-dir]', host: { 'src': TEST_IFRAME_URL, }, }) class DirThatSetsSrc {} @Directive({ standalone: true, selector: '[dir]', hostDirectives: [DirThatSetsSrc], host: { 'sandbox': '', }, }) class DirThatSetsSandbox {} @Component({ standalone: true, imports: [DirThatSetsSandbox], selector: 'my-comp', template: '<iframe dir></iframe>', }) class IframeComp {} expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}); }, ); it( 'should work when a directive that sets an `src` has ' + 'a host directive that sets a security-sensitive attribute value', () => { @Directive({ standalone: true, selector: '[set-sandbox-dir]', host: { 'sandbox': '', }, }) class DirThatSetsSandbox {} @Directive({ standalone: true, selector: '[dir]', hostDirectives: [DirThatSetsSandbox], host: { 'src': TEST_IFRAME_URL, }, }) class DirThatSetsSrc {} @Component({ standalone: true, imports: [DirThatSetsSrc], selector: 'my-comp', template: '<iframe dir></iframe>', }) class IframeComp {} expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}); }, ); it( 'should error when creating a view that contains an <iframe> ' + 'with security-sensitive attributes set via property bindings', () => { @Component({ standalone: true, selector: 'my-comp', template: ` <ng-container #container></ng-container> <ng-template #template> <iframe src="${TEST_IFRAME_URL}" [sandbox]="''"></iframe> </ng-template> `, }) class IframeComp { @ViewChild('container', {read: ViewContainerRef}) container!: ViewContainerRef; @ViewChild('template') template!: TemplateRef<unknown>; createEmbeddedView() { this.container.createEmbeddedView(this.template); } } const fixture = TestBed.createComponent(IframeComp); fixture.detectChanges(); expect(() => { fixture.componentInstance.createEmbeddedView(); fixture.detectChanges(); }).toThrowError(getErrorMessageRegexp()); ensureNoIframePresent(fixture); }, );
{ "end_byte": 21826, "start_byte": 13592, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/security_spec.ts" }
angular/packages/core/test/acceptance/security_spec.ts_21834_23471
describe('i18n', () => { it( 'should error when a security-sensitive attribute is set as ' + 'a property binding on an <iframe> inside i18n block', () => { @Component({ standalone: true, selector: 'my-comp', template: ` <section i18n> <iframe src="${TEST_IFRAME_URL}" [sandbox]="''"> </iframe> </section> `, }) class IframeComp {} expectIframeCreationToFail(IframeComp); }, ); it( 'should error when a security-sensitive attribute is set as ' + 'a property binding on an <iframe> annotated with i18n attribute', () => { @Component({ standalone: true, selector: 'my-comp', template: ` <iframe i18n src="${TEST_IFRAME_URL}" [sandbox]="''"> </iframe> `, }) class IframeComp {} expectIframeCreationToFail(IframeComp); }, ); it('should work when a security-sensitive attributes are marked for translation', () => { @Component({ standalone: true, selector: 'my-comp', template: ` <iframe src="${TEST_IFRAME_URL}" i18n-sandbox sandbox=""> </iframe> `, }) class IframeComp {} expectIframeToBeCreated(IframeComp, {src: TEST_IFRAME_URL}); }); }); }); }); });
{ "end_byte": 23471, "start_byte": 21834, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/security_spec.ts" }
angular/packages/core/test/acceptance/view_ref_spec.ts_0_5088
/** * @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 { ApplicationRef, ChangeDetectorRef, Component, ComponentRef, createComponent, ElementRef, EmbeddedViewRef, EnvironmentInjector, Injector, TemplateRef, ViewChild, ViewContainerRef, } from '@angular/core'; import {ViewRef as InternalViewRef} from '@angular/core/src/render3/view_ref'; import {TestBed} from '@angular/core/testing'; describe('ViewRef', () => { it('should remove nodes from DOM when the view is detached from app ref', () => { @Component({ selector: 'dynamic-cpt', template: '<div></div>', standalone: false, }) class DynamicComponent { constructor(public elRef: ElementRef) {} } @Component({ template: `<span></span>`, standalone: false, }) class App { componentRef!: ComponentRef<DynamicComponent>; constructor( public appRef: ApplicationRef, private injector: EnvironmentInjector, ) {} create() { this.componentRef = createComponent(DynamicComponent, {environmentInjector: this.injector}); (this.componentRef.hostView as InternalViewRef<unknown>).attachToAppRef(this.appRef); document.body.appendChild(this.componentRef.instance.elRef.nativeElement); } destroy() { (this.componentRef.hostView as InternalViewRef<unknown>).detachFromAppRef(); } } TestBed.configureTestingModule({declarations: [App, DynamicComponent]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const appComponent = fixture.componentInstance; appComponent.create(); fixture.detectChanges(); expect(document.body.querySelector('dynamic-cpt')).not.toBeFalsy(); appComponent.destroy(); fixture.detectChanges(); expect(document.body.querySelector('dynamic-cpt')).toBeFalsy(); }); it('should invoke the onDestroy callback of a view ref', () => { let called = false; @Component({ template: '', standalone: false, }) class App { constructor(changeDetectorRef: ChangeDetectorRef) { (changeDetectorRef as InternalViewRef<unknown>).onDestroy(() => (called = true)); } } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(called).toBe(true); }); it('should remove view ref from view container when destroyed', () => { @Component({ template: '', standalone: false, }) class DynamicComponent { constructor(public viewContainerRef: ViewContainerRef) {} } @Component({ template: `<ng-template>Hello</ng-template>`, standalone: false, }) class App { @ViewChild(TemplateRef) templateRef!: TemplateRef<any>; componentRef!: ComponentRef<DynamicComponent>; viewRef!: EmbeddedViewRef<any>; constructor(private _viewContainerRef: ViewContainerRef) {} create() { this.viewRef = this.templateRef.createEmbeddedView(null); this.componentRef = this._viewContainerRef.createComponent(DynamicComponent); this.componentRef.instance.viewContainerRef.insert(this.viewRef); } } TestBed.configureTestingModule({declarations: [App, DynamicComponent]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.componentInstance.create(); const viewContainerRef = fixture.componentInstance.componentRef.instance.viewContainerRef; expect(viewContainerRef.length).toBe(1); fixture.componentInstance.viewRef.destroy(); expect(viewContainerRef.length).toBe(0); }); it('should mark a ViewRef as destroyed when the host view is destroyed', () => { @Component({ template: '', standalone: false, }) class DynamicComponent { constructor(public viewContainerRef: ViewContainerRef) {} } @Component({ template: `<ng-template>Hello</ng-template>`, standalone: false, }) class App { @ViewChild(TemplateRef) templateRef!: TemplateRef<any>; componentRef!: ComponentRef<DynamicComponent>; viewRef!: EmbeddedViewRef<any>; constructor(private _viewContainerRef: ViewContainerRef) {} create() { this.viewRef = this.templateRef.createEmbeddedView(null); this.componentRef = this._viewContainerRef.createComponent(DynamicComponent); this.componentRef.instance.viewContainerRef.insert(this.viewRef); } } TestBed.configureTestingModule({declarations: [App, DynamicComponent]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.componentInstance.create(); const {componentRef, viewRef} = fixture.componentInstance; expect(viewRef.destroyed).toBe(false); componentRef.hostView.destroy(); expect(viewRef.destroyed).toBe(true); }); });
{ "end_byte": 5088, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_ref_spec.ts" }
angular/packages/core/test/acceptance/content_spec.ts_0_639
/** * @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} from '@angular/common'; import { ChangeDetectorRef, Component, createComponent, Directive, EnvironmentInjector, inject, Input, OnDestroy, TemplateRef, ViewChild, ViewContainerRef, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {expect} from '@angular/platform-browser/testing/src/matchers'; describe('projection',
{ "end_byte": 639, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/content_spec.ts" }
angular/packages/core/test/acceptance/content_spec.ts_640_9141
() => { function getElementHtml(element: HTMLElement) { return element.innerHTML .replace(/<!--(\W|\w)*?-->/g, '') .replace(/\sng-reflect-\S*="[^"]*"/g, ''); } it('should project content', () => { @Component({ selector: 'child', template: `<div><ng-content></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: '<child>content</child>', standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe(`<child><div>content</div></child>`); }); it('should project content when <ng-content> is at a template root', () => { @Component({ selector: 'child', template: '<ng-content></ng-content>', standalone: false, }) class Child {} @Component({ selector: 'parent', template: '<child>content</child>', standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe(`<child>content</child>`); }); it('should project content with siblings', () => { @Component({ selector: 'child', template: '<ng-content></ng-content>', standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child>before<div>content</div>after</child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe(`<child>before<div>content</div>after</child>`); }); it('should be able to re-project content', () => { @Component({ selector: 'grand-child', template: `<div><ng-content></ng-content></div>`, standalone: false, }) class GrandChild {} @Component({ selector: 'child', template: `<grand-child><ng-content></ng-content></grand-child>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><b>Hello</b>World!</child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child, GrandChild]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe( '<child><grand-child><div><b>Hello</b>World!</div></grand-child></child>', ); }); it('should project components', () => { @Component({ selector: 'child', template: `<div><ng-content></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'projected-comp', template: 'content', standalone: false, }) class ProjectedComp {} @Component({ selector: 'parent', template: `<child><projected-comp></projected-comp></child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child, ProjectedComp]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe( '<child><div><projected-comp>content</projected-comp></div></child>', ); }); it('should project components that have their own projection', () => { @Component({ selector: 'child', template: `<div><ng-content></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'projected-comp', template: `<p><ng-content></ng-content></p>`, standalone: false, }) class ProjectedComp {} @Component({ selector: 'parent', template: ` <child> <projected-comp><div>Some content</div>Other content</projected-comp> </child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child, ProjectedComp]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe( `<child><div><projected-comp><p><div>Some content</div>Other content</p></projected-comp></div></child>`, ); }); it('should project with multiple instances of a component with projection', () => { @Component({ selector: 'child', template: `<div><ng-content></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'projected-comp', template: `Before<ng-content></ng-content>After`, standalone: false, }) class ProjectedComp {} @Component({ selector: 'parent', template: ` <child> <projected-comp><div>A</div><p>123</p></projected-comp> <projected-comp><div>B</div><p>456</p></projected-comp> </child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child, ProjectedComp]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe( '<child><div>' + '<projected-comp>Before<div>A</div><p>123</p>After</projected-comp>' + '<projected-comp>Before<div>B</div><p>456</p>After</projected-comp>' + '</div></child>', ); }); it('should re-project with multiple instances of a component with projection', () => { @Component({ selector: 'child', template: `<div><ng-content></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'projected-comp', template: `Before<ng-content></ng-content>After`, standalone: false, }) class ProjectedComp {} @Component({ selector: 'parent', template: ` <child> <projected-comp><div>A</div><ng-content></ng-content><p>123</p></projected-comp> <projected-comp><div>B</div><p>456</p></projected-comp> </child>`, standalone: false, }) class Parent {} @Component({ selector: 'app', template: ` <parent>**ABC**</parent> <parent>**DEF**</parent> `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Parent, Child, ProjectedComp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toBe( '<parent><child><div>' + '<projected-comp>Before<div>A</div>**ABC**<p>123</p>After</projected-comp>' + '<projected-comp>Before<div>B</div><p>456</p>After</projected-comp>' + '</div></child></parent>' + '<parent><child><div>' + '<projected-comp>Before<div>A</div>**DEF**<p>123</p>After</projected-comp>' + '<projected-comp>Before<div>B</div><p>456</p>After</projected-comp>' + '</div></child></parent>', ); }); it('should project into dynamic views (with createEmbeddedView)', () => { @Component({ selector: 'child', template: `Before-<ng-template [ngIf]="showing"><ng-content></ng-content></ng-template>-After`, standalone: false, }) class Child { showing = false; } @Component({ selector: 'parent', template: `<child><div>A</div>Some text</child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child], imports: [CommonModule]}); const fixture = TestBed.createComponent(Parent); const childDebugEl = fixture.debugElement.query(By.directive(Child)); const childInstance = childDebugEl.injector.get(Child); const childElement = childDebugEl.nativeElement as HTMLElement; childInstance.showing = true; fixture.detectChanges(); expect(getElementHtml(childElement)).toBe(`Before-<div>A</div>Some text-After`); childInstance.showing = false; fixture.detectChanges(); expect(getElementHtml(childElement)).toBe(`Before--After`); childInstance.showing = true; fixture.detectChanges(); expect(getElementHtml(childElement)).toBe(`Before-<div>A</div>Some text-After`); });
{ "end_byte": 9141, "start_byte": 640, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/content_spec.ts" }
angular/packages/core/test/acceptance/content_spec.ts_9145_17449
it('should project into dynamic views with specific selectors', () => { @Component({ selector: 'child', template: ` <ng-content></ng-content> Before- <ng-template [ngIf]="showing"> <ng-content select="div"></ng-content> </ng-template> -After`, standalone: false, }) class Child { showing = false; } @Component({ selector: 'parent', template: ` <child> <div>A</div> <span>B</span> </child> `, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child], imports: [CommonModule]}); const fixture = TestBed.createComponent(Parent); const childDebugEl = fixture.debugElement.query(By.directive(Child)); const childInstance = childDebugEl.injector.get(Child); childInstance.showing = true; fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toBe( '<child><span>B</span> Before- <div>A</div> -After</child>', ); childInstance.showing = false; fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toBe( '<child><span>B</span> Before- -After</child>', ); childInstance.showing = true; fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toBe( '<child><span>B</span> Before- <div>A</div> -After</child>', ); }); it('should project if <ng-content> is in a template that has different declaration/insertion points', () => { @Component({ selector: 'comp', template: `<ng-template><ng-content></ng-content></ng-template>`, standalone: false, }) class Comp { @ViewChild(TemplateRef, {static: true}) template!: TemplateRef<any>; } @Directive({ selector: '[trigger]', standalone: false, }) class Trigger { @Input() trigger!: Comp; constructor(public vcr: ViewContainerRef) {} open() { this.vcr.createEmbeddedView(this.trigger.template); } } @Component({ selector: 'parent', template: ` <button [trigger]="comp"></button> <comp #comp>Some content</comp> `, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Trigger, Comp]}); const fixture = TestBed.createComponent(Parent); const trigger = fixture.debugElement.query(By.directive(Trigger)).injector.get(Trigger); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toBe(`<button></button><comp></comp>`); trigger.open(); expect(getElementHtml(fixture.nativeElement)).toBe( `<button></button>Some content<comp></comp>`, ); }); it('should project nodes into the last ng-content', () => { @Component({ selector: 'child', template: `<div><ng-content></ng-content></div> <span><ng-content></ng-content></span>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child>content</child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child], imports: [CommonModule]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toBe( '<child><div></div><span>content</span></child>', ); }); // https://stackblitz.com/edit/angular-ceqmnw?file=src%2Fapp%2Fapp.component.ts it('should project nodes into the last ng-content unrolled by ngFor', () => { @Component({ selector: 'child', template: '<div *ngFor="let item of [1, 2]; let i = index">({{i}}):<ng-content></ng-content></div>', standalone: false, }) class Child {} @Component({ selector: 'parent', template: '<child>content</child>', standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child], imports: [CommonModule]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toBe( '<child><div>(0):</div><div>(1):content</div></child>', ); }); it('should handle projected containers inside other containers', () => { @Component({ selector: 'nested-comp', template: `<div>Child content</div>`, standalone: false, }) class NestedComp {} @Component({ selector: 'root-comp', template: `<ng-content></ng-content>`, standalone: false, }) class RootComp {} @Component({ selector: 'my-app', template: ` <root-comp> <ng-container *ngFor="let item of items; last as last"> <nested-comp *ngIf="!last"></nested-comp> </ng-container> </root-comp> `, standalone: false, }) class MyApp { items = [1, 2]; } TestBed.configureTestingModule({ declarations: [MyApp, RootComp, NestedComp], imports: [CommonModule], }); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); // expecting # of divs to be (items.length - 1), since last element is filtered out by *ngIf, // this applies to all other assertions below expect(fixture.nativeElement.querySelectorAll('div').length).toBe(1); fixture.componentInstance.items = [3, 4, 5]; fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('div').length).toBe(2); fixture.componentInstance.items = [6, 7, 8, 9]; fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('div').length).toBe(3); }); it('should handle projection into element containers at the view root', () => { @Component({ selector: 'root-comp', template: ` <ng-template [ngIf]="show"> <ng-container> <ng-content></ng-content> </ng-container> </ng-template>`, standalone: false, }) class RootComp { @Input() show: boolean = true; } @Component({ selector: 'my-app', template: `<root-comp [show]="show"><div></div></root-comp> `, standalone: false, }) class MyApp { show = true; } TestBed.configureTestingModule({declarations: [MyApp, RootComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('div').length).toBe(1); fixture.componentInstance.show = false; fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('div').length).toBe(0); }); it('should handle projection of views with element containers at the root', () => { @Component({ selector: 'root-comp', template: `<ng-template [ngIf]="show"><ng-content></ng-content></ng-template>`, standalone: false, }) class RootComp { @Input() show: boolean = true; } @Component({ selector: 'my-app', template: `<root-comp [show]="show"><ng-container><div></div></ng-container></root-comp>`, standalone: false, }) class MyApp { show = true; } TestBed.configureTestingModule({declarations: [MyApp, RootComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('div').length).toBe(1); fixture.componentInstance.show = false; fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('div').length).toBe(0); }); it('should project ng-container at the content root', () => { @Component({ selector: 'child', template: `<ng-content></ng-content>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child> <ng-container> <ng-container>content</ng-container> </ng-container> </child> `, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toBe('<child>content</child>'); });
{ "end_byte": 17449, "start_byte": 9145, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/content_spec.ts" }
angular/packages/core/test/acceptance/content_spec.ts_17453_19491
it('should re-project ng-container at the content root', () => { @Component({ selector: 'grand-child', template: `<ng-content></ng-content>`, standalone: false, }) class GrandChild {} @Component({ selector: 'child', template: `<grand-child> <ng-content></ng-content> </grand-child>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child> <ng-container> <ng-container>content</ng-container> </ng-container> </child> `, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Parent, Child, GrandChild]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toBe( '<child><grand-child>content</grand-child></child>', ); }); it('should handle re-projection at the root of an embedded view', () => { @Component({ selector: 'child-comp', template: `<ng-template [ngIf]="show"><ng-content></ng-content></ng-template>`, standalone: false, }) class ChildComp { @Input() show: boolean = true; } @Component({ selector: 'parent-comp', template: `<child-comp [show]="show"><ng-content></ng-content></child-comp>`, standalone: false, }) class ParentComp { @Input() show: boolean = true; } @Component({ selector: 'my-app', template: `<parent-comp [show]="show"><div></div></parent-comp>`, standalone: false, }) class MyApp { show = true; } TestBed.configureTestingModule({declarations: [MyApp, ParentComp, ChildComp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('div').length).toBe(1); fixture.componentInstance.show = false; fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('div').length).toBe(0); });
{ "end_byte": 19491, "start_byte": 17453, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/content_spec.ts" }
angular/packages/core/test/acceptance/content_spec.ts_19495_28191
describe('with selectors', () => { it('should project nodes using attribute selectors', () => { @Component({ selector: 'child', template: `<div id="first"><ng-content select="span[title=toFirst]"></ng-content></div> <div id="second"><ng-content select="span[title=toSecond]"></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><span title="toFirst">1</span><span title="toSecond">2</span></child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><div id="first"><span title="toFirst">1</span></div><div id="second"><span title="toSecond">2</span></div></child>', ); }); it('should project nodes using class selectors', () => { @Component({ selector: 'child', template: `<div id="first"><ng-content select="span.toFirst"></ng-content></div> <div id="second"><ng-content select="span.toSecond"></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><span class="toFirst">1</span><span class="toSecond">2</span></child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><div id="first"><span class="toFirst">1</span></div><div id="second"><span class="toSecond">2</span></div></child>', ); }); it('should project nodes using class selectors when element has multiple classes', () => { @Component({ selector: 'child', template: `<div id="first"><ng-content select="span.toFirst"></ng-content></div> <div id="second"><ng-content select="span.toSecond"></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><span class="other toFirst">1</span><span class="noise toSecond">2</span></child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><div id="first"><span class="other toFirst">1</span></div><div id="second"><span class="noise toSecond">2</span></div></child>', ); }); it('should project nodes into the first matching selector', () => { @Component({ selector: 'child', template: `<div id="first"><ng-content select="span"></ng-content></div> <div id="second"><ng-content select="span.toSecond"></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><span class="toFirst">1</span><span class="toSecond">2</span></child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><div id="first"><span class="toFirst">1</span><span class="toSecond">2</span></div><div id="second"></div></child>', ); }); it('should allow mixing ng-content with and without selectors', () => { @Component({ selector: 'child', template: `<div id="first"><ng-content select="span.toFirst"></ng-content></div> <div id="second"><ng-content></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><span class="toFirst">1</span><span>remaining</span>more remaining</child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><div id="first"><span class="toFirst">1</span></div><div id="second"><span>remaining</span>more remaining</div></child>', ); }); it('should allow mixing ng-content with and without selectors - ng-content first', () => { @Component({ selector: 'child', template: `<div id="first"><ng-content></ng-content></div> <div id="second"><ng-content select="span.toSecond"></ng-content></div>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><span>1</span><span class="toSecond">2</span>remaining</child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><div id="first"><span>1</span>remaining</div><div id="second"><span class="toSecond">2</span></div></child>', ); }); /** * Descending into projected content for selector-matching purposes is not supported * today: https://plnkr.co/edit/MYQcNfHSTKp9KvbzJWVQ?p=preview */ it('should not descend into re-projected content', () => { @Component({ selector: 'grand-child', template: `<ng-content select="span"></ng-content><hr><ng-content></ng-content>`, standalone: false, }) class GrandChild {} @Component({ selector: 'child', template: `<grand-child> <ng-content></ng-content> <span>in child template</span> </grand-child>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><span>parent content</span></child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [GrandChild, Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><grand-child><span>in child template</span><hr><span>parent content</span></grand-child></child>', ); }); it('should not descend into re-projected content', () => { @Component({ selector: 'card', template: `<ng-content select="[card-title]"></ng-content><hr><ng-content select="[card-content]"></ng-content>`, standalone: false, }) class Card {} @Component({ selector: 'card-with-title', template: `<card> <h1 card-title>Title</h1> <ng-content card-content></ng-content> </card>`, standalone: false, }) class CardWithTitle {} @Component({ selector: 'parent', template: `<card-with-title>content</card-with-title>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Card, CardWithTitle, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<card-with-title><card><h1 card-title="">Title</h1><hr>content</card></card-with-title>', ); }); it('should not match selectors against node having ngProjectAs attribute', () => { @Component({ selector: 'child', template: `<ng-content select="div"></ng-content>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><div ngProjectAs="span">should not project</div><div>should project</div></child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><div>should project</div></child>', ); }); // https://stackblitz.com/edit/angular-psokum?file=src%2Fapp%2Fapp.module.ts
{ "end_byte": 28191, "start_byte": 19495, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/content_spec.ts" }
angular/packages/core/test/acceptance/content_spec.ts_28196_35787
it('should project nodes where attribute selector matches a binding', () => { @Component({ selector: 'child', template: `<ng-content select="[title]"></ng-content>`, standalone: false, }) class Child {} @Component({ selector: 'parent', template: `<child><span [title]="'Some title'">Has title</span></child>`, standalone: false, }) class Parent {} TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><span title="Some title">Has title</span></child>', ); }); it('should match selectors against projected containers', () => { @Component({ selector: 'child', template: `<span><ng-content select="div"></ng-content></span>`, standalone: false, }) class Child {} @Component({ template: `<child><div *ngIf="value">content</div></child>`, standalone: false, }) class Parent { value = false; } TestBed.configureTestingModule({declarations: [Child, Parent]}); const fixture = TestBed.createComponent(Parent); fixture.componentInstance.value = true; fixture.detectChanges(); expect(getElementHtml(fixture.nativeElement)).toEqual( '<child><span><div>content</div></span></child>', ); }); }); it('should handle projected containers inside other containers', () => { @Component({ selector: 'child-comp', // template: '<ng-content></ng-content>', standalone: false, }) class ChildComp {} @Component({ selector: 'root-comp', // template: '<ng-content></ng-content>', standalone: false, }) class RootComp {} @Component({ selector: 'my-app', template: ` <root-comp> <ng-container *ngFor="let item of items; last as last"> <child-comp *ngIf="!last">{{ item }}|</child-comp> </ng-container> </root-comp> `, standalone: false, }) class MyApp { items: number[] = [1, 2, 3]; } TestBed.configureTestingModule({declarations: [ChildComp, RootComp, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); // expecting # of elements to be (items.length - 1), since last element is filtered out by // *ngIf, this applies to all other assertions below expect(fixture.nativeElement).toHaveText('1|2|'); fixture.componentInstance.items = [4, 5]; fixture.detectChanges(); expect(fixture.nativeElement).toHaveText('4|'); fixture.componentInstance.items = [6, 7, 8, 9]; fixture.detectChanges(); expect(fixture.nativeElement).toHaveText('6|7|8|'); }); it('should project content if the change detector has been detached', () => { @Component({ selector: 'my-comp', template: '<ng-content></ng-content>', standalone: false, }) class MyComp { constructor(changeDetectorRef: ChangeDetectorRef) { changeDetectorRef.detach(); } } @Component({ selector: 'my-app', template: ` <my-comp> <p>hello</p> </my-comp> `, standalone: false, }) class MyApp {} TestBed.configureTestingModule({declarations: [MyComp, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); expect(fixture.nativeElement).toHaveText('hello'); }); it('should support ngProjectAs with a various number of other bindings and attributes', () => { @Directive({ selector: '[color],[margin]', standalone: false, }) class ElDecorator { @Input() color?: string; @Input() margin?: number; } @Component({ selector: 'card', template: ` <ng-content select="[card-title]"></ng-content> --- <ng-content select="[card-subtitle]"></ng-content> --- <ng-content select="[card-content]"></ng-content> --- <ng-content select="[card-footer]"></ng-content> `, standalone: false, }) class Card {} @Component({ selector: 'card-with-title', template: ` <card> <h1 [color]="'red'" [margin]="10" ngProjectAs="[card-title]">Title</h1> <h2 xlink:href="google.com" ngProjectAs="[card-subtitle]">Subtitle</h2> <div style="font-color: blue;" ngProjectAs="[card-content]">content</div> <div [color]="'blue'" ngProjectAs="[card-footer]">footer</div> </card> `, standalone: false, }) class CardWithTitle {} TestBed.configureTestingModule({declarations: [Card, CardWithTitle, ElDecorator]}); const fixture = TestBed.createComponent(CardWithTitle); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Title --- Subtitle --- content --- footer'); }); it('should support ngProjectAs on elements (including <ng-content>)', () => { @Component({ selector: 'card', template: ` <ng-content select="[card-title]"></ng-content> --- <ng-content select="[card-content]"></ng-content> `, standalone: false, }) class Card {} @Component({ selector: 'card-with-title', template: ` <card> <h1 ngProjectAs="[card-title]">Title</h1> <ng-content ngProjectAs="[card-content]"></ng-content> </card> `, standalone: false, }) class CardWithTitle {} @Component({ selector: 'app', template: ` <card-with-title>content</card-with-title> `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [Card, CardWithTitle, App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('Title --- content'); }); it('should not match multiple selectors in ngProjectAs', () => { @Component({ selector: 'card', template: ` <ng-content select="[card-title]"></ng-content> content `, standalone: false, }) class Card {} @Component({ template: ` <card> <h1 ngProjectAs="[non-existing-title-slot],[card-title]">Title</h1> </card> `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [Card, App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).not.toEqual('Title content'); }); it('should preserve ngProjectAs and other attributes on projected element', () => { @Component({ selector: 'projector', template: `<ng-content select="projectMe"></ng-content>`, standalone: false, }) class Projector {} @Component({ template: ` <projector> <div ngProjectAs="projectMe" title="some title"></div> </projector> `, standalone: false, }) class Root {} TestBed.configureTestingModule({ declarations: [Root, Projector], }); const fixture = TestBed.createComponent(Root); fixture.detectChanges(); const projectedElement = fixture.debugElement.query(By.css('div')); const {ngProjectAs, title} = projectedElement.attributes; expect(ngProjectAs).toBe('projectMe'); expect(title).toBe('some title'); });
{ "end_byte": 35787, "start_byte": 28196, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/content_spec.ts" }