_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/core/test/animation/animation_query_integration_spec.ts_1199_10144
// these tests are only meant to be run within the DOM (for now) if (isNode) return; describe('animation query tests', function () { function getLog(): MockAnimationPlayer[] { return MockAnimationDriver.log as MockAnimationPlayer[]; } function resetLog() { MockAnimationDriver.log = []; } beforeEach(() => { resetLog(); TestBed.configureTestingModule({ providers: [{provide: AnimationDriver, useClass: MockAnimationDriver}], imports: [BrowserAnimationsModule, CommonModule], }); }); describe('query()', () => { it('should be able to query all elements that contain animation triggers via @*', () => { @Component({ selector: 'ani-cmp', template: ` <div [@parent]="exp0"> <div class="a" [@a]="exp1"></div> <div class="b" [@b]="exp2"></div> <section> <div class="c" @c></div> </section> </div> `, animations: [ trigger('parent', [ transition('* => go', [ query('@*', [ style({backgroundColor: 'blue'}), animate(1000, style({backgroundColor: 'red'})), ]), ]), ]), trigger('a', [transition('* => 1', [animate(1000, style({opacity: 0}))])]), trigger('b', [ transition('* => 1', [ animate(1000, style({opacity: 0})), query('.b-inner', [animate(1000, style({opacity: 0}))]), ]), ]), trigger('c', [transition('* => 1', [animate(1000, style({opacity: 0}))])]), ], standalone: false, }) class Cmp { public exp0: any; public exp1: any; public exp2: any; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp0 = 'go'; fixture.detectChanges(); let players = getLog(); expect(players.length).toEqual(3); // a,b,c resetLog(); const [p1, p2, p3] = players; expect(p1.element.classList.contains('a')).toBeTruthy(); expect(p2.element.classList.contains('b')).toBeTruthy(); expect(p3.element.classList.contains('c')).toBeTruthy(); }); it('should be able to query currently animating elements via :animating', () => { @Component({ selector: 'ani-cmp', template: ` <div [@parent]="exp0"> <div class="a" [@a]="exp1"></div> <div class="b" [@b]="exp2"> <div class="b-inner"></div> </div> <div class="c" [@c]="exp3"></div> </div> `, animations: [ trigger('parent', [ transition('* => go', [ query(':animating', [ style({backgroundColor: 'blue'}), animate(1000, style({backgroundColor: 'red'})), ]), ]), ]), trigger('a', [transition('* => 1', [animate(1000, style({opacity: 0}))])]), trigger('b', [ transition('* => 1', [ animate(1000, style({opacity: 0})), query('.b-inner', [animate(1000, style({opacity: 0}))]), ]), ]), trigger('c', [transition('* => 1', [animate(1000, style({opacity: 0}))])]), ], standalone: false, }) class Cmp { public exp0: any; public exp1: any; public exp2: any; public exp3: any; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp0 = ''; cmp.exp1 = 1; cmp.exp2 = 1; // note that exp3 is skipped here fixture.detectChanges(); let players = getLog(); expect(players.length).toEqual(3); // a,b,b-inner and not c resetLog(); cmp.exp0 = 'go'; fixture.detectChanges(); const expectedKeyframes = [ new Map<string, string | number>([ ['backgroundColor', 'blue'], ['offset', 0], ]), new Map<string, string | number>([ ['backgroundColor', 'red'], ['offset', 1], ]), ]; players = getLog(); expect(players.length).toEqual(3); const [p1, p2, p3] = players; expect(p1.element.classList.contains('a')).toBeTruthy(); expect(p1.keyframes).toEqual(expectedKeyframes); expect(p2.element.classList.contains('b')).toBeTruthy(); expect(p2.keyframes).toEqual(expectedKeyframes); expect(p3.element.classList.contains('b-inner')).toBeTruthy(); expect(p3.keyframes).toEqual(expectedKeyframes); }); it('should be able to query triggers directly by name', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp0"> <div class="f1" @foo></div> <div class="f2" [@foo]></div> <div class="f3" [@foo]="exp1"></div> <div class="b1" @bar></div> <div class="b2" [@bar]></div> <div class="b3" [@bar]="exp2"></div> </div> `, animations: [ trigger('foo', []), trigger('bar', []), trigger('myAnimation', [ transition('* => foo', [query('@foo', [animate(1000, style({color: 'red'}))])]), transition('* => bar', [query('@bar', [animate(1000, style({color: 'blue'}))])]), ]), ], standalone: false, }) class Cmp { public exp0: any; public exp1: any; public exp2: any; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; fixture.detectChanges(); engine.flush(); resetLog(); cmp.exp0 = 'foo'; fixture.detectChanges(); engine.flush(); let players = getLog(); expect(players.length).toEqual(3); const [p1, p2, p3] = players; resetLog(); expect(p1.element.classList.contains('f1')).toBeTruthy(); expect(p2.element.classList.contains('f2')).toBeTruthy(); expect(p3.element.classList.contains('f3')).toBeTruthy(); cmp.exp0 = 'bar'; fixture.detectChanges(); engine.flush(); players = getLog(); expect(players.length).toEqual(3); const [p4, p5, p6] = players; resetLog(); expect(p4.element.classList.contains('b1')).toBeTruthy(); expect(p5.element.classList.contains('b2')).toBeTruthy(); expect(p6.element.classList.contains('b3')).toBeTruthy(); }); it('should be able to query all active animations using :animating in a query', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp" #parent> <div *ngFor="let item of items" class="item e-{{ item }}"> </div> </div> `, animations: [ trigger('myAnimation', [ transition('* => a', [ query('.item:nth-child(odd)', [ style({opacity: 0}), animate(1000, style({opacity: 1})), ]), ]), transition('* => b', [ query('.item:animating', [style({opacity: 1}), animate(1000, style({opacity: 0}))]), ]), ]), ], standalone: false, }) class Cmp { public exp: any; public items: number[] = [0, 1, 2, 3, 4]; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'a'; fixture.detectChanges(); engine.flush(); let players = getLog(); expect(players.length).toEqual(3); resetLog(); cmp.exp = 'b'; fixture.detectChanges(); engine.flush(); players = getLog(); expect(players.length).toEqual(3); expect(players[0].element.classList.contains('e-0')).toBeTruthy(); expect(players[1].element.classList.contains('e-2')).toBeTruthy(); expect(players[2].element.classList.contains('e-4')).toBeTruthy(); });
{ "end_byte": 10144, "start_byte": 1199, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_query_integration_spec.ts" }
angular/packages/core/test/animation/animation_query_integration_spec.ts_10152_17649
hould be able to query all actively queued animation triggers via `@*:animating`', () => { @Component({ selector: 'ani-cmp', template: ` <div [@parent]="exp0"> <div class="c1" [@child]="exp1"></div> <div class="c2" [@child]="exp2"></div> <div class="c3" [@child]="exp3"></div> <div class="c4" [@child]="exp4"></div> <div class="c5" [@child]="exp5"></div> </div> `, animations: [ trigger('parent', [ transition('* => *', [ query('@*:animating', [animate(1000, style({background: 'red'}))], { optional: true, }), ]), ]), trigger('child', [transition('* => *', [])]), ], standalone: false, }) class Cmp { public exp0: any; public exp1: any; public exp2: any; public exp3: any; public exp4: any; public exp5: any; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp1 = 0; cmp.exp2 = 0; cmp.exp3 = 0; cmp.exp4 = 0; cmp.exp5 = 0; fixture.detectChanges(); cmp.exp0 = 0; fixture.detectChanges(); let players = engine.players; cancelAllPlayers(players); cmp.exp2 = 1; cmp.exp4 = 1; fixture.detectChanges(); cmp.exp0 = 1; fixture.detectChanges(); players = engine.players; cancelAllPlayers(players); expect(players.length).toEqual(3); cmp.exp1 = 2; cmp.exp2 = 2; cmp.exp3 = 2; cmp.exp4 = 2; cmp.exp5 = 2; fixture.detectChanges(); cmp.exp0 = 2; fixture.detectChanges(); players = engine.players; cancelAllPlayers(players); expect(players.length).toEqual(6); cmp.exp0 = 3; fixture.detectChanges(); players = engine.players; cancelAllPlayers(players); expect(players.length).toEqual(1); }); it('should collect styles for the same elements between queries', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp"> <header></header> <footer></footer> </div> `, animations: [ trigger('myAnimation', [ transition('* => go', [ query(':self, header, footer', style({opacity: '0.01'})), animate(1000, style({opacity: '1'})), query('header, footer', [stagger(500, [animate(1000, style({opacity: '1'}))])]), ]), ]), ], standalone: false, }) class Cmp { public exp: any; public items: any[] = [0, 1, 2]; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'go'; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(6); const [p1, p2, p3, p4, p5, p6] = players; expect(p1.delay).toEqual(0); expect(p1.duration).toEqual(0); expect(p1.keyframes).toEqual([ new Map<string, string | number>([ ['opacity', '0.01'], ['offset', 0], ]), new Map<string, string | number>([ ['opacity', '0.01'], ['offset', 1], ]), ]); expect(p2.delay).toEqual(0); expect(p2.duration).toEqual(0); expect(p2.keyframes).toEqual([ new Map<string, string | number>([ ['opacity', '0.01'], ['offset', 0], ]), new Map<string, string | number>([ ['opacity', '0.01'], ['offset', 1], ]), ]); expect(p3.delay).toEqual(0); expect(p3.duration).toEqual(0); expect(p3.keyframes).toEqual([ new Map<string, string | number>([ ['opacity', '0.01'], ['offset', 0], ]), new Map<string, string | number>([ ['opacity', '0.01'], ['offset', 1], ]), ]); expect(p4.delay).toEqual(0); expect(p4.duration).toEqual(1000); expect(p4.keyframes).toEqual([ new Map<string, string | number>([ ['opacity', '0.01'], ['offset', 0], ]), new Map<string, string | number>([ ['opacity', '1'], ['offset', 1], ]), ]); expect(p5.delay).toEqual(1000); expect(p5.duration).toEqual(1000); expect(p5.keyframes).toEqual([ new Map<string, string | number>([ ['opacity', '0.01'], ['offset', 0], ]), new Map<string, string | number>([ ['opacity', '1'], ['offset', 1], ]), ]); expect(p6.delay).toEqual(1500); expect(p6.duration).toEqual(1000); expect(p6.keyframes).toEqual([ new Map<string, string | number>([ ['opacity', '0.01'], ['offset', 0], ]), new Map<string, string | number>([ ['opacity', '1'], ['offset', 1], ]), ]); }); it('should retain style values when :self is used inside of a query', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp"></div> `, animations: [ trigger('myAnimation', [ transition('* => go', [ query(':self', style({opacity: '0.5'})), animate(1000, style({opacity: '1'})), ]), ]), ], standalone: false, }) class Cmp { public exp: any; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'go'; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(2); const [p1, p2] = players; expect(p1.delay).toEqual(0); expect(p1.duration).toEqual(0); expect(p1.keyframes).toEqual([ new Map<string, string | number>([ ['opacity', '0.5'], ['offset', 0], ]), new Map<string, string | number>([ ['opacity', '0.5'], ['offset', 1], ]), ]); expect(p2.delay).toEqual(0); expect(p2.duration).toEqual(1000); expect(p2.keyframes).toEqual([ new Map<string, string | number>([ ['opacity', '0.5'], ['offset', 0], ]), new Map<string, string | number>([ ['opacity', '1'], ['offset', 1], ]), ]); });
{ "end_byte": 17649, "start_byte": 10152, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_query_integration_spec.ts" }
angular/packages/core/test/animation/animation_query_integration_spec.ts_17657_26084
ld properly apply stagger after various other steps within a query', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp"> <header></header> <footer></footer> </div> `, animations: [ trigger('myAnimation', [ transition('* => go', [ query(':self, header, footer', [ style({opacity: '0'}), animate(1000, style({opacity: '0.3'})), animate(1000, style({opacity: '0.6'})), stagger(500, [animate(1000, style({opacity: '1'}))]), ]), ]), ]), ], standalone: false, }) class Cmp { public exp: any; public items: any[] = [0, 1, 2]; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'go'; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(3); const [p1, p2, p3] = players; expect(p1.delay).toEqual(0); expect(p1.duration).toEqual(3000); expect(p2.delay).toEqual(0); expect(p2.duration).toEqual(3500); expect(p3.delay).toEqual(0); expect(p3.duration).toEqual(4000); }); it('should properly apply pre styling before a stagger is issued', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp"> <div *ngFor="let item of items" class="item"> {{ item }} </div> </div> `, animations: [ trigger('myAnimation', [ transition('* => go', [ query(':enter', [ style({opacity: 0}), stagger(100, [animate(1000, style({opacity: 1}))]), ]), ]), ]), ], standalone: false, }) class Cmp { public exp: any; public items: any[] = [0, 1, 2, 3, 4]; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'go'; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(5); for (let i = 0; i < players.length; i++) { const player = players[i]; const kf = player.keyframes; const limit = kf.length - 1; const staggerDelay = 100 * i; const duration = 1000 + staggerDelay; expect(kf[0]).toEqual( new Map<string, string | number>([ ['opacity', '0'], ['offset', 0], ]), ); if (limit > 1) { const offsetAtStaggerDelay = staggerDelay / duration; expect(kf[1]).toEqual( new Map<string, string | number>([ ['opacity', '0'], ['offset', offsetAtStaggerDelay], ]), ); } expect(kf[limit]).toEqual( new Map<string, string | number>([ ['opacity', '1'], ['offset', 1], ]), ); expect(player.duration).toEqual(duration); } }); it('should apply a full stagger step delay if the timing data is left undefined', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp"> <div *ngFor="let item of items" class="item"> {{ item }} </div> </div> `, animations: [ trigger('myAnimation', [ transition('* => go', [ query('.item', [ stagger('full', [ style({opacity: 0}), animate(1000, style({opacity: 0.5})), animate(500, style({opacity: 1})), ]), ]), ]), ]), ], standalone: false, }) class Cmp { public exp: any; public items: any[] = [0, 1, 2, 3, 4]; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'go'; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(5); const [p1, p2, p3, p4, p5] = players; expect(p1.delay).toEqual(0); expect(p2.delay).toEqual(1500); expect(p3.delay).toEqual(3000); expect(p4.delay).toEqual(4500); expect(p5.delay).toEqual(6000); }); it('should persist inner sub trigger styles once their animation is complete', () => { @Component({ selector: 'ani-cmp', template: ` <div @parent *ngIf="exp1"> <div class="child" [@child]="exp2"></div> </div> `, animations: [ trigger('parent', [transition(':enter', [query('.child', [animateChild()])])]), trigger('child', [ state('*, void', style({height: '0px'})), state('b', style({height: '444px'})), transition('* => *', animate(500)), ]), ], standalone: false, }) class Cmp { public exp1: any; public exp2: any; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp1 = true; cmp.exp2 = 'b'; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(2); const player = players[1]; expect(player.keyframes).toEqual([ new Map<string, string | number>([ ['height', '0px'], ['offset', 0], ]), new Map<string, string | number>([ ['height', '444px'], ['offset', 1], ]), ]); player.finish(); expect(player.element.style.height).toEqual('444px'); }); it('should find newly inserted items in the component via :enter', () => { @Component({ selector: 'ani-cmp', template: ` <div @myAnimation> <div *ngFor="let item of items" class="child"> {{ item }} </div> </div> `, animations: [ trigger('myAnimation', [ transition(':enter', [ query(':enter', [style({opacity: 0}), animate(1000, style({opacity: 0.5}))]), ]), ]), ], standalone: false, }) class Cmp { public items: any[] = [0, 1, 2]; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(3); const [p1, p2, p3] = players; expect(p1.element.innerText.trim()).toEqual('0'); expect(p2.element.innerText.trim()).toEqual('1'); expect(p3.element.innerText.trim()).toEqual('2'); players.forEach((p) => { expect(p.keyframes).toEqual([ new Map<string, string | number>([ ['opacity', '0'], ['offset', 0], ]), new Map<string, string | number>([ ['opacity', '0.5'], ['offset', 1], ]), ]); }); }); it('s
{ "end_byte": 26084, "start_byte": 17657, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_query_integration_spec.ts" }
angular/packages/core/test/animation/animation_query_integration_spec.ts_26092_34064
eanup :enter and :leave artifacts from nodes when any animation sequences fail to be built', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="items.length" class="parent" #container> <div *ngFor="let item of items" class="child"> {{ item }} </div> <div *ngIf="items.length == 0" class="child">Leave!</div> </div> `, animations: [ trigger('myAnimation', [ transition('* => 0', []), transition('* => *', [ query('.child:enter', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), query('.incorrect-child:leave', [animate(1000, style({opacity: 0}))]), ]), ]), ], standalone: false, }) class Cmp { @ViewChild('container') public container: any; public items: any[] = []; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.items = []; fixture.detectChanges(); cmp.items = [0, 1, 2, 3, 4]; expect(() => { fixture.detectChanges(); }).toThrow(); const children = cmp.container.nativeElement.querySelectorAll('.child'); expect(children.length).toEqual(5); for (let i = 0; i < children.length; i++) { let child = children[i]; expect(child.classList.contains(ENTER_CLASSNAME)).toBe(false); expect(child.classList.contains(LEAVE_CLASSNAME)).toBe(false); } }); it('should find elements that have been removed via :leave', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp" class="parent"> <div *ngFor="let item of items" class="child"> {{ item }} </div> </div> `, animations: [ trigger('myAnimation', [ transition('a => b', [ query(':leave', [style({opacity: 1}), animate(1000, style({opacity: 0.5}))]), ]), ]), ], standalone: false, }) class Cmp { public exp: any; public items: any[] = [4, 2, 0]; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'a'; fixture.detectChanges(); engine.flush(); resetLog(); cmp.exp = 'b'; cmp.items = []; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(3); const [p1, p2, p3] = players; expect(p1.element.innerText.trim()).toEqual('4'); expect(p2.element.innerText.trim()).toEqual('2'); expect(p3.element.innerText.trim()).toEqual('0'); players.forEach((p) => { expect(p.keyframes).toEqual([ new Map<string, string | number>([ ['opacity', '1'], ['offset', 0], ]), new Map<string, string | number>([ ['opacity', '0.5'], ['offset', 1], ]), ]); }); }); it('should find :enter nodes that have been inserted around non enter nodes', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp" class="parent"> <div *ngFor="let item of items" class="child"> {{ item }} </div> </div> `, animations: [ trigger('myAnimation', [ transition('* => go', [ query(':enter', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), ]), ]), ], standalone: false, }) class Cmp { public exp: any; public items: any[] = []; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'no'; cmp.items = [2]; fixture.detectChanges(); engine.flush(); resetLog(); cmp.exp = 'go'; cmp.items = [0, 1, 2, 3, 4]; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(4); const [p1, p2, p3, p4] = players; expect(p1.element.innerText.trim()).toEqual('0'); expect(p2.element.innerText.trim()).toEqual('1'); expect(p3.element.innerText.trim()).toEqual('3'); expect(p4.element.innerText.trim()).toEqual('4'); }); it('should find :enter/:leave nodes that are nested inside of ng-container elements', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="items.length" class="parent"> <ng-container *ngFor="let item of items"> <section> <div *ngIf="item % 2 == 0">even {{ item }}</div> <div *ngIf="item % 2 == 1">odd {{ item }}</div> </section> </ng-container> </div> `, animations: [ trigger('myAnimation', [ transition('0 => 5', [ query(':enter', [style({opacity: '0'}), animate(1000, style({opacity: '1'}))]), ]), transition('5 => 0', [ query(':leave', [style({opacity: '1'}), animate(1000, style({opacity: '0'}))]), ]), ]), ], standalone: false, }) class Cmp { public items: any[] | undefined; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.items = []; fixture.detectChanges(); engine.flush(); resetLog(); cmp.items = [0, 1, 2, 3, 4]; fixture.detectChanges(); engine.flush(); let players = getLog(); expect(players.length).toEqual(5); for (let i = 0; i < 5; i++) { let player = players[i]; expect(player.keyframes).toEqual([ new Map<string, string | number>([ ['opacity', '0'], ['offset', 0], ]), new Map<string, string | number>([ ['opacity', '1'], ['offset', 1], ]), ]); let elm = player.element; let text = i % 2 == 0 ? `even ${i}` : `odd ${i}`; expect(elm.innerText.trim()).toEqual(text); } resetLog(); cmp.items = []; fixture.detectChanges(); engine.flush(); players = getLog(); expect(players.length).toEqual(5); for (let i = 0; i < 5; i++) { let player = players[i]; expect(player.keyframes).toEqual([ new Map<string, string | number>([ ['opacity', '1'], ['offset', 0], ]), new Map<string, string | number>([ ['opacity', '0'], ['offset', 1], ]), ]); let elm = player.element; let text = i % 2 == 0 ? `even ${i}` : `odd ${i}`; expect(elm.innerText.trim()).toEqual(text); } }); it('should
{ "end_byte": 34064, "start_byte": 26092, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_query_integration_spec.ts" }
angular/packages/core/test/animation/animation_query_integration_spec.ts_34072_42365
y cancel items that were queried into a former animation and pass in the associated styles into the follow-up players per element', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp" class="parent"> <div *ngFor="let item of items" class="child"> {{ item }} </div> </div> `, animations: [ trigger('myAnimation', [ transition('* => on', [ query(':enter', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), query(':enter', [style({width: 0}), animate(1000, style({height: 200}))]), ]), transition('* => off', [ query(':leave', [animate(1000, style({width: 0}))]), query(':leave', [animate(1000, style({opacity: 0}))]), ]), ]), ], standalone: false, }) class Cmp { public exp: any; public items: any[] | undefined; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'on'; cmp.items = [0, 1, 2, 3, 4]; fixture.detectChanges(); engine.flush(); const previousPlayers = getLog(); expect(previousPlayers.length).toEqual(10); resetLog(); cmp.exp = 'off'; cmp.items = [0, 1, 2]; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(4); const [p1, p2, p3, p4] = players; // p1 && p2 are the starting players for item3 and item4 expect(p1.previousStyles).toEqual( new Map([ ['opacity', AUTO_STYLE], ['width', AUTO_STYLE], ['height', AUTO_STYLE], ]), ); expect(p2.previousStyles).toEqual( new Map([ ['opacity', AUTO_STYLE], ['width', AUTO_STYLE], ['height', AUTO_STYLE], ]), ); // p3 && p4 are the following players for item3 and item4 expect(p3.previousStyles).toEqual(new Map()); expect(p4.previousStyles).toEqual(new Map()); }); it('should not remove a parent container if its contents are queried into by an ancestor element', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp1" class="ancestor" #ancestor> <div class="parent" *ngIf="exp2" #parent> <div class="child"></div> <div class="child"></div> </div> </div> `, animations: [ trigger('myAnimation', [ transition('* => go', [ query('.child', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), ]), ]), ], standalone: false, }) class Cmp { public exp1: any = ''; public exp2: any = true; @ViewChild('ancestor') public ancestorElm: any; @ViewChild('parent') public parentElm: any; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; fixture.detectChanges(); engine.flush(); resetLog(); const ancestorElm = cmp.ancestorElm.nativeElement; const parentElm = cmp.parentElm.nativeElement; cmp.exp1 = 'go'; cmp.exp2 = false; fixture.detectChanges(); engine.flush(); expect(ancestorElm.contains(parentElm)).toBe(true); const players = getLog(); expect(players.length).toEqual(2); const [p1, p2] = players; expect(parentElm.contains(p1.element)).toBe(true); expect(parentElm.contains(p2.element)).toBe(true); cancelAllPlayers(players); expect(ancestorElm.contains(parentElm)).toBe(false); }); it('should only retain a to-be-removed node if the inner queried items are apart of an animation issued by an ancestor', fakeAsync(() => { @Component({ selector: 'ani-cmp', template: ` <div [@one]="exp1" [@two]="exp2" class="ancestor" #ancestor> <header>hello</header> <div class="parent" *ngIf="parentExp" #parent> <div class="child">child</div> </div> </div> `, animations: [ trigger('one', [ transition('* => go', [ query('.child', [style({height: '100px'}), animate(1000, style({height: '0px'}))]), ]), ]), trigger('two', [ transition('* => go', [ query('header', [style({width: '100px'}), animate(1000, style({width: '0px'}))]), ]), ]), ], standalone: false, }) class Cmp { public exp1: any = ''; public exp2: any = ''; public parentExp: any = true; @ViewChild('ancestor') public ancestorElm: any; @ViewChild('parent') public parentElm: any; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; fixture.detectChanges(); engine.flush(); resetLog(); const ancestorElm = cmp.ancestorElm.nativeElement; const parentElm = cmp.parentElm.nativeElement; expect(ancestorElm.contains(parentElm)).toBe(true); cmp.exp1 = 'go'; fixture.detectChanges(); engine.flush(); expect(ancestorElm.contains(parentElm)).toBe(true); const onePlayers = getLog(); expect(onePlayers.length).toEqual(1); // element.child const [childPlayer] = onePlayers; let childPlayerComplete = false; childPlayer.onDone(() => (childPlayerComplete = true)); resetLog(); flushMicrotasks(); expect(childPlayerComplete).toBe(false); cmp.exp2 = 'go'; cmp.parentExp = false; fixture.detectChanges(); engine.flush(); const twoPlayers = getLog(); expect(twoPlayers.length).toEqual(1); // the header element expect(ancestorElm.contains(parentElm)).toBe(false); expect(childPlayerComplete).toBe(true); })); it('should finish queried players in an animation when the next animation takes over', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp" class="parent"> <div *ngFor="let item of items" class="child"> {{ item }} </div> </div> `, animations: [ trigger('myAnimation', [ transition('* => on', [ query(':enter', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), ]), transition('* => off', []), ]), ], standalone: false, }) class Cmp { public exp: any; public items: any[] | undefined; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'on'; cmp.items = [0, 1, 2, 3, 4]; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(5); let count = 0; players.forEach((p) => { p.onDone(() => count++); }); expect(count).toEqual(0); cmp.exp = 'off'; fixture.detectChanges(); engine.flush(); expect(count).toEqual(5); }); it('should fin
{ "end_byte": 42365, "start_byte": 34072, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_query_integration_spec.ts" }
angular/packages/core/test/animation/animation_query_integration_spec.ts_42373_51178
ied players when the previous player is finished', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp" class="parent"> <div *ngFor="let item of items" class="child"> {{ item }} </div> </div> `, animations: [ trigger('myAnimation', [ transition('* => on', [ query(':enter', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), ]), transition('* => off', []), ]), ], standalone: false, }) class Cmp { public exp: any; public items: any[] | undefined; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'on'; cmp.items = [0, 1, 2, 3, 4]; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(5); let count = 0; players.forEach((p) => { p.onDone(() => count++); }); expect(count).toEqual(0); expect(engine.players.length).toEqual(1); engine.players[0].finish(); expect(count).toEqual(5); }); it('should allow multiple triggers to animate on queried elements at the same time', () => { @Component({ selector: 'ani-cmp', template: ` <div [@one]="exp1" [@two]="exp2" class="parent"> <div *ngFor="let item of items" class="child"> {{ item }} </div> </div> `, animations: [ trigger('one', [ transition('* => on', [ query('.child', [style({width: '0px'}), animate(1000, style({width: '100px'}))]), ]), transition('* => off', []), ]), trigger('two', [ transition('* => on', [ query('.child:nth-child(odd)', [ style({height: '0px'}), animate(1000, style({height: '100px'})), ]), ]), transition('* => off', []), ]), ], standalone: false, }) class Cmp { public exp1: any; public exp2: any; public items: any[] | undefined; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp1 = 'on'; cmp.items = [0, 1, 2, 3, 4]; fixture.detectChanges(); engine.flush(); let players = getLog(); expect(players.length).toEqual(5); let count = 0; players.forEach((p) => { p.onDone(() => count++); }); resetLog(); expect(count).toEqual(0); cmp.exp2 = 'on'; fixture.detectChanges(); engine.flush(); expect(count).toEqual(0); players = getLog(); expect(players.length).toEqual(3); players.forEach((p) => { p.onDone(() => count++); }); cmp.exp1 = 'off'; fixture.detectChanges(); engine.flush(); expect(count).toEqual(5); cmp.exp2 = 'off'; fixture.detectChanges(); engine.flush(); expect(count).toEqual(8); }); it("should cancel inner queried animations if a trigger state value changes, but isn't detected as a valid transition", () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp" class="parent"> <div *ngFor="let item of items" class="child"> {{ item }} </div> </div> `, animations: [ trigger('myAnimation', [ transition('* => on', [ query(':enter', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), ]), ]), ], standalone: false, }) class Cmp { public exp: any; public items: any[] | undefined; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'on'; cmp.items = [0, 1, 2, 3, 4]; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(5); let count = 0; players.forEach((p) => { p.onDone(() => count++); }); expect(count).toEqual(0); cmp.exp = 'off'; fixture.detectChanges(); engine.flush(); expect(count).toEqual(5); }); it('should allow for queried items to restore their styling back to the original state via animate(time, "*")', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp" class="parent"> <div *ngFor="let item of items" class="child"> {{ item }} </div> </div> `, animations: [ trigger('myAnimation', [ transition('* => on', [ query(':enter', [ style({opacity: '0', width: '0px', height: '0px'}), animate(1000, style({opacity: '1'})), animate(1000, style(['*', {height: '200px'}])), ]), ]), ]), ], standalone: false, }) class Cmp { public exp: any; public items: any[] | undefined; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'on'; cmp.items = [0, 1, 2]; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(3); players.forEach((p) => { expect(p.keyframes).toEqual([ new Map<string, string | number>([ ['opacity', '0'], ['width', '0px'], ['height', '0px'], ['offset', 0], ]), new Map<string, string | number>([ ['opacity', '1'], ['width', '0px'], ['height', '0px'], ['offset', 0.5], ]), new Map<string, string | number>([ ['opacity', AUTO_STYLE], ['width', AUTO_STYLE], ['height', '200px'], ['offset', 1], ]), ]); }); }); it('should query elements in sub components that do not contain animations using the :enter selector', () => { @Component({ selector: 'parent-cmp', template: ` <div [@myAnimation]="exp"> <child-cmp #child></child-cmp> </div> `, animations: [ trigger('myAnimation', [ transition('* => on', [ query(':enter', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), ]), ]), ], standalone: false, }) class ParentCmp { public exp: any; @ViewChild('child') public child: any; } @Component({ selector: 'child-cmp', template: ` <div *ngFor="let item of items"> {{ item }} </div> `, standalone: false, }) class ChildCmp { public items: any[] = []; } TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); const fixture = TestBed.createComponent(ParentCmp); const cmp = fixture.componentInstance; fixture.detectChanges(); cmp.exp = 'on'; cmp.child.items = [1, 2, 3]; fixture.detectChanges(); const players = getLog() as any[]; expect(players.length).toEqual(3); expect(players[0].element.innerText.trim()).toEqual('1'); expect(players[1].element.innerText.trim()).toEqual('2'); expect(players[2].element.innerText.trim()).toEqual('3'); }); it('should query e
{ "end_byte": 51178, "start_byte": 42373, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_query_integration_spec.ts" }
angular/packages/core/test/animation/animation_query_integration_spec.ts_51186_55630
in sub components that do not contain animations using the :leave selector', () => { @Component({ selector: 'parent-cmp', template: ` <div [@myAnimation]="exp"> <child-cmp #child></child-cmp> </div> `, animations: [ trigger('myAnimation', [ transition('* => on', [query(':leave', [animate(1000, style({opacity: 0}))])]), ]), ], standalone: false, }) class ParentCmp { public exp: any; @ViewChild('child', {static: true}) public child: any; } @Component({ selector: 'child-cmp', template: ` <div *ngFor="let item of items"> {{ item }} </div> `, standalone: false, }) class ChildCmp { public items: any[] = []; } TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); const fixture = TestBed.createComponent(ParentCmp); const cmp = fixture.componentInstance; cmp.child.items = [4, 5, 6]; fixture.detectChanges(); cmp.exp = 'on'; cmp.child.items = []; fixture.detectChanges(); const players = getLog() as any[]; expect(players.length).toEqual(3); expect(players[0].element.innerText.trim()).toEqual('4'); expect(players[1].element.innerText.trim()).toEqual('5'); expect(players[2].element.innerText.trim()).toEqual('6'); }); describe('options.limit', () => { it('should limit results when a limit value is passed into the query options', () => { @Component({ selector: 'cmp', template: ` <div [@myAnimation]="exp"> <div *ngFor="let item of items" class="item"> {{ item }} </div> </div> `, animations: [ trigger('myAnimation', [ transition('* => go', [ query('.item', [style({opacity: 0}), animate('1s', style({opacity: 1}))], { limit: 2, }), ]), ]), ], standalone: false, }) class Cmp { public exp: any; public items: any[] = []; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.items = ['a', 'b', 'c', 'd', 'e']; fixture.detectChanges(); cmp.exp = 'go'; fixture.detectChanges(); const players = getLog() as any[]; expect(players.length).toEqual(2); expect(players[0].element.innerText.trim()).toEqual('a'); expect(players[1].element.innerText.trim()).toEqual('b'); }); it('should support negative limit values by pulling in elements from the end of the query', () => { @Component({ selector: 'cmp', template: ` <div [@myAnimation]="exp"> <div *ngFor="let item of items" class="item"> {{ item }} </div> </div> `, animations: [ trigger('myAnimation', [ transition('* => go', [ query('.item', [style({opacity: 0}), animate('1s', style({opacity: 1}))], { limit: -3, }), ]), ]), ], standalone: false, }) class Cmp { public exp: any; public items: any[] = []; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.items = ['a', 'b', 'c', 'd', 'e']; fixture.detectChanges(); cmp.exp = 'go'; fixture.detectChanges(); const players = getLog() as any[]; expect(players.length).toEqual(3); expect(players[0].element.innerText.trim()).toEqual('c'); expect(players[1].element.innerText.trim()).toEqual('d'); expect(players[2].element.innerText.trim()).toEqual('e'); }); }); }); describe('sub trigge
{ "end_byte": 55630, "start_byte": 51186, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_query_integration_spec.ts" }
angular/packages/core/test/animation/animation_query_integration_spec.ts_55636_63200
) => { it('should animate a sub trigger that exists in an inner element in the template', () => { @Component({ selector: 'ani-cmp', template: ` <div #parent class="parent" [@parent]="exp1"> <div #child class="child" [@child]="exp2"></div> </div> `, animations: [ trigger('parent', [ transition('* => go1', [ style({width: '0px'}), animate(1000, style({width: '100px'})), query('.child', [animateChild()]), ]), ]), trigger('child', [ transition('* => go2', [ style({height: '0px'}), animate(1000, style({height: '100px'})), ]), ]), ], standalone: false, }) class Cmp { public exp1: any; public exp2: any; @ViewChild('parent') public elm1: any; @ViewChild('child') public elm2: any; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp1 = 'go1'; cmp.exp2 = 'go2'; fixture.detectChanges(); engine.flush(); const elm1 = cmp.elm1; const elm2 = cmp.elm2; const players = getLog(); // players: // - _scp (skipped child player): player for the child animation // - pp (parent player): player for parent animation (from 0px to 100px) // - pcp (parent child player): // player for child animation executed by parent via query and animateChild const [_scp, pp, pcp] = players; expect(pp.delay).toEqual(0); expect(pp.element).toEqual(elm1.nativeElement); expect(pp.duration).toEqual(1000); expect(pp.keyframes).toEqual([ new Map<string, string | number>([ ['width', '0px'], ['offset', 0], ]), new Map<string, string | number>([ ['width', '100px'], ['offset', 1], ]), ]); expect(pcp.delay).toEqual(0); expect(pcp.element).toEqual(elm2.nativeElement); expect(pcp.duration).toEqual(2000); expect(pcp.keyframes).toEqual([ new Map<string, string | number>([ ['height', '0px'], ['offset', 0], ]), new Map<string, string | number>([ ['height', '0px'], ['offset', 0.5], ]), new Map<string, string | number>([ ['height', '100px'], ['offset', 1], ]), ]); }); it('should run and operate a series of triggers on a list of elements with overridden timing data', () => { @Component({ selector: 'ani-cmp', template: ` <div #parent class="parent" [@parent]="exp"> <div class="item" *ngFor="let item of items" @child></div> </div> `, animations: [ trigger('parent', [ transition('* => go', [ style({opacity: '0'}), animate(1000, style({opacity: '1'})), query('.item', [animateChild({duration: '2.5s', delay: '500ms'})]), animate(1000, style({opacity: '0'})), ]), ]), trigger('child', [ transition(':enter', [ style({height: '0px'}), animate(1000, style({height: '100px'})), ]), ]), ], standalone: false, }) class Cmp { public exp: any; public items: any[] = [0, 1, 2, 3, 4]; @ViewChild('parent') public elm: any; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'go'; fixture.detectChanges(); engine.flush(); const parent = cmp.elm.nativeElement; const elements = parent.querySelectorAll('.item'); const players = getLog(); expect(players.length).toEqual(12); // players: // - _sc1p, _sc2p, _sc3p, _sc4p (skipped child n (1 to 4) players): // players for the children animations // - pp1 (parent player 1): player for parent animation (from opacity 0 to opacity 1) // - pc1p, pc2p, pc3p, pc4p, pc5p (parent child n (1 to 4) player): // players for children animations executed by parent via query and animateChild // - pp2 (parent player 2): player for parent animation (from opacity 1 to opacity 0) const [_sc1p, _sc2p, _sc3p, _sc4p, _sc5p, pp1, pc1p, pc2p, pc3p, pc4p, pc5p, pp2] = players; expect(pp1.element).toEqual(parent); expect(pp1.delay).toEqual(0); expect(pp1.duration).toEqual(1000); expect(pc1p.element).toEqual(elements[0]); expect(pc1p.delay).toEqual(0); expect(pc1p.duration).toEqual(4000); expect(pc2p.element).toEqual(elements[1]); expect(pc2p.delay).toEqual(0); expect(pc2p.duration).toEqual(4000); expect(pc3p.element).toEqual(elements[2]); expect(pc3p.delay).toEqual(0); expect(pc3p.duration).toEqual(4000); expect(pc4p.element).toEqual(elements[3]); expect(pc4p.delay).toEqual(0); expect(pc4p.duration).toEqual(4000); expect(pc5p.element).toEqual(elements[4]); expect(pc5p.delay).toEqual(0); expect(pc5p.duration).toEqual(4000); expect(pp2.element).toEqual(parent); expect(pp2.delay).toEqual(4000); expect(pp2.duration).toEqual(1000); }); it("should silently continue if a sub trigger is animated that doesn't exist", () => { @Component({ selector: 'ani-cmp', template: ` <div #parent class="parent" [@parent]="exp"> <div class="child"></div> </div> `, animations: [ trigger('parent', [ transition('* => go', [ style({opacity: 0}), animate(1000, style({opacity: 1})), query('.child', [animateChild({duration: '1s'})]), animate(1000, style({opacity: 0})), ]), ]), ], standalone: false, }) class Cmp { public exp: any; public items: any[] = [0, 1, 2, 3, 4]; @ViewChild('parent') public elm: any; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'go'; fixture.detectChanges(); engine.flush(); const parent = cmp.elm.nativeElement; const players = getLog(); expect(players.length).toEqual(2); const [pA, pZ] = players; expect(pA.element).toEqual(parent); expect(pA.delay).toEqual(0); expect(pA.duration).toEqual(1000); expect(pZ.element).toEqual(parent); expect(pZ.delay).toEqual(1000); expect(pZ.duration).toEqual(1000); }); it("should silently c
{ "end_byte": 63200, "start_byte": 55636, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_query_integration_spec.ts" }
angular/packages/core/test/animation/animation_query_integration_spec.ts_63208_69604
if a sub trigger is animated that doesn't contain a trigger that is setup for animation", () => { @Component({ selector: 'ani-cmp', template: ` <div #parent class="parent" [@parent]="exp1"> <div [@child]="exp2" class="child"></div> </div> `, animations: [ trigger('child', [ transition('a => z', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), ]), trigger('parent', [ transition('a => z', [ style({opacity: 0}), animate(1000, style({opacity: 1})), query('.child', [animateChild({duration: '1s'})]), animate(1000, style({opacity: 0})), ]), ]), ], standalone: false, }) class Cmp { public exp1: any; public exp2: any; @ViewChild('parent') public elm: any; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp1 = 'a'; cmp.exp2 = 'a'; fixture.detectChanges(); engine.flush(); resetLog(); cmp.exp1 = 'z'; fixture.detectChanges(); engine.flush(); const parent = cmp.elm.nativeElement; const players = getLog(); expect(players.length).toEqual(2); const [pA, pZ] = players; expect(pA.element).toEqual(parent); expect(pA.delay).toEqual(0); expect(pA.duration).toEqual(1000); expect(pZ.element).toEqual(parent); expect(pZ.delay).toEqual(1000); expect(pZ.duration).toEqual(1000); }); it('should animate all sub triggers on the element at the same time', () => { @Component({ selector: 'ani-cmp', template: ` <div #parent class="parent" [@parent]="exp1"> <div [@w]="exp2" [@h]="exp2" class="child"></div> </div> `, animations: [ trigger('w', [ transition('* => go', [style({width: 0}), animate(1800, style({width: '100px'}))]), ]), trigger('h', [ transition('* => go', [style({height: 0}), animate(1500, style({height: '100px'}))]), ]), trigger('parent', [ transition('* => go', [ style({opacity: 0}), animate(1000, style({opacity: 1})), query('.child', [animateChild()]), animate(1000, style({opacity: 0})), ]), ]), ], standalone: false, }) class Cmp { public exp1: any; public exp2: any; @ViewChild('parent') public elm: any; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp1 = 'go'; cmp.exp2 = 'go'; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(6); // players: // - _scwp (skipped child w player): player for the child animation (trigger w) // - _schp (skipped child h player): player for the child animation (trigger h) // - _pp1 (parent player 1): player for parent animation (from opacity 0 to opacity 1) // - pcwp (parent child w player): // player for child w animation executed by parent via query and animateChild // - pchp (parent child h player): // player for child w animation executed by parent via query and animateChild // - pp2 (parent player 2): player for parent animation (from opacity 1 to opacity 0) const [_scwp, _schp, _pp1, pcwp, pchp, pp2] = players; expect(pcwp.delay).toEqual(0); expect(pcwp.duration).toEqual(2800); expect(pchp.delay).toEqual(0); expect(pchp.duration).toEqual(2500); expect(pp2.delay).toEqual(2800); expect(pp2.duration).toEqual(1000); }); it('should skip a sub animation when a zero duration value is passed in', () => { @Component({ selector: 'ani-cmp', template: ` <div #parent class="parent" [@parent]="exp1"> <div [@child]="exp2" class="child"></div> </div> `, animations: [ trigger('child', [ transition('* => go', [style({width: 0}), animate(1800, style({width: '100px'}))]), ]), trigger('parent', [ transition('* => go', [ style({opacity: 0}), animate(1000, style({opacity: 1})), query('.child', [animateChild({duration: '0'})]), animate(1000, style({opacity: 0})), ]), ]), ], standalone: false, }) class Cmp { public exp1: any; public exp2: any; @ViewChild('parent') public elm: any; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp1 = 'go'; cmp.exp2 = 'go'; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(3); // players: // - _scp (skipped child player): player for the child animation // - pp1 (parent player 1): player for parent animation (from opacity 0 to opacity 1) // - ( the player for the child animation executed by parent via query // and animateChild is skipped entirely ) // - pp2 (parent player 2): player for parent animation (from opacity 1 to opacity 0) const [_scp, pp1, pp2] = players; expect(pp1.delay).toEqual(0); expect(pp1.duration).toEqual(1000); expect(pp2.delay).toEqual(1000); expect(pp2.duration).toEqual(1000); }); it('should only allow a
{ "end_byte": 69604, "start_byte": 63208, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_query_integration_spec.ts" }
angular/packages/core/test/animation/animation_query_integration_spec.ts_69612_78858
ation to be used up by a parent trigger once', () => { @Component({ selector: 'ani-cmp', template: ` <div [@parent]="exp1" class="parent1" #parent> <div [@parent]="exp1" class="parent2"> <div [@child]="exp2" class="child"> </div> </div> </div> `, animations: [ trigger('parent', [ transition('* => go', [ style({opacity: 0}), animate(1000, style({opacity: 1})), query('.child', animateChild()), ]), ]), trigger('child', [ transition('* => go', [style({opacity: 0}), animate(1800, style({opacity: 1}))]), ]), ], standalone: false, }) class Cmp { public exp1: any; public exp2: any; @ViewChild('parent') public elm: any; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp1 = 'go'; cmp.exp2 = 'go'; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(5); // players: // - _scp (skipped child player): player for the child animation // (note: parent2 is evaluated first because it is inside of parent1) // - p2p (parent 2 player): player for parent animation (from opacity 0 to opacity 1) // - p2cp (parent 2 child player): // player for child animation executed by parent 2 via query and animateChild // - p1p (parent 1 player): player for parent animation (from opacity 0 to opacity 1) // - p1cp (parent 1 child player): // player for child animation executed by parent 1 via query and animateChild const [_scp, p2p, p2cp, p1p, p1cp] = players; expect(p2p.element.classList.contains('parent2')).toBeTruthy(); expect(p2cp.element.classList.contains('child')).toBeTruthy(); expect(p1p.element.classList.contains('parent1')).toBeTruthy(); expect(p1cp.element.classList.contains('child')).toBeTruthy(); }); it('should emulate a leave animation on the nearest sub host elements when a parent is removed', fakeAsync(() => { @Component({ selector: 'ani-cmp', template: ` <div @parent *ngIf="exp" class="parent1" #parent> <child-cmp #child @leave (@leave.start)="animateStart($event)"></child-cmp> </div> `, animations: [ trigger('leave', [transition(':leave', [animate(1000, style({color: 'gold'}))])]), trigger('parent', [transition(':leave', [query(':leave', animateChild())])]), ], standalone: false, }) class ParentCmp { public exp: boolean = true; @ViewChild('child') public childElm: any; public childEvent: any; animateStart(event: any) { if (event.toState == 'void') { this.childEvent = event; } } } @Component({ selector: 'child-cmp', template: '...', animations: [ trigger('child', [transition(':leave', [animate(1000, style({color: 'gold'}))])]), ], standalone: false, }) class ChildCmp { public childEvent: any; @HostBinding('@child') public animate = true; @HostListener('@child.start', ['$event']) animateStart(event: any) { if (event.toState == 'void') { this.childEvent = event; } } } TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); const fixture = TestBed.createComponent(ParentCmp); const cmp = fixture.componentInstance; fixture.detectChanges(); const childCmp = cmp.childElm; cmp.exp = false; fixture.detectChanges(); flushMicrotasks(); expect(cmp.childEvent.toState).toEqual('void'); expect(cmp.childEvent.totalTime).toEqual(1000); expect(childCmp.childEvent.toState).toEqual('void'); expect(childCmp.childEvent.totalTime).toEqual(1000); })); it("should emulate a leave animation on a sub component's inner elements when a parent leave animation occurs with animateChild", () => { @Component({ selector: 'ani-cmp', template: ` <div @myAnimation *ngIf="exp" class="parent"> <child-cmp></child-cmp> </div> `, animations: [ trigger('myAnimation', [transition(':leave', [query('@*', animateChild())])]), ], standalone: false, }) class ParentCmp { public exp: boolean = true; } @Component({ selector: 'child-cmp', template: ` <section> <div class="inner-div" @myChildAnimation></div> </section> `, animations: [ trigger('myChildAnimation', [ transition(':leave', [style({opacity: 0}), animate('1s', style({opacity: 1}))]), ]), ], standalone: false, }) class ChildCmp {} TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(ParentCmp); const cmp = fixture.componentInstance; cmp.exp = true; fixture.detectChanges(); cmp.exp = false; fixture.detectChanges(); let players = getLog(); expect(players.length).toEqual(2); // players: // - _scp (skipped child player): player for the child animation // - pcp (parent child player): // player for child animation executed by parent via query and animateChild const [_scp, pcp] = players; expect(pcp.element.classList.contains('inner-div')).toBeTruthy(); expect(pcp.keyframes).toEqual([ new Map<string, string | number>([ ['opacity', '0'], ['offset', 0], ]), new Map<string, string | number>([ ['opacity', '1'], ['offset', 1], ]), ]); }); it(`should emulate a leave animation on a nested sub component's inner elements when a parent leave animation occurs with animateChild`, () => { @Component({ selector: 'ani-cmp', template: ` <div @myAnimation *ngIf="exp" class="parent"> <child-cmp></child-cmp> </div> `, animations: [ trigger('myAnimation', [transition(':leave', [query('@*', animateChild())])]), ], standalone: false, }) class ParentCmp { public exp: boolean = true; } @Component({ selector: 'child-cmp', template: ` <nested-child-cmp></nested-child-cmp> `, standalone: false, }) class ChildCmp {} @Component({ selector: 'nested-child-cmp', template: ` <section> <div class="inner-div" @myChildAnimation></div> </section> `, animations: [ trigger('myChildAnimation', [ transition(':leave', [style({opacity: 0}), animate('1s', style({opacity: 1}))]), ]), ], standalone: false, }) class NestedChildCmp {} TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp, NestedChildCmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(ParentCmp); const cmp = fixture.componentInstance; cmp.exp = true; fixture.detectChanges(); cmp.exp = false; fixture.detectChanges(); // Inspect the players of the AnimationEngine and not those from getLog. The latter only // returns the actual animation players, which the parent leave animation is not part // of given that it does not have animation instructions of its own. const players = engine.players; expect(players.length).toEqual(1); const player = players[0] as TransitionAnimationPlayer; const realPlayer = player.getRealPlayer() as MockAnimationPlayer; expect(player.element.classList.contains('parent')).toBeTruthy(); expect(realPlayer.element.classList.contains('inner-div')).toBeTruthy(); expect(realPlayer.keyframes).toEqual([ new Map<string, string | number>([ ['opacity', '0'], ['offset', 0], ]), new Map<string, string | number>([ ['opacity', '1'], ['offset', 1], ]), ]); }); it('should not cause a remo
{ "end_byte": 78858, "start_byte": 69612, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_query_integration_spec.ts" }
angular/packages/core/test/animation/animation_query_integration_spec.ts_78866_87731
nner @trigger DOM nodes when a parent animation occurs', fakeAsync(() => { @Component({ selector: 'ani-cmp', template: ` <div @parent *ngIf="exp" class="parent"> this <div @child>child</div> </div> `, animations: [ trigger('parent', [ transition(':leave', [style({opacity: 0}), animate('1s', style({opacity: 1}))]), ]), trigger('child', [ transition('* => something', [ style({opacity: 0}), animate('1s', style({opacity: 1})), ]), ]), ], standalone: false, }) class Cmp { public exp: boolean = true; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = true; fixture.detectChanges(); flushMicrotasks(); cmp.exp = false; fixture.detectChanges(); flushMicrotasks(); const players = getLog(); expect(players.length).toEqual(1); const element = players[0].element; expect(element.innerText.trim()).toMatch(/this\s+child/gm); })); it('should only mark outermost *directive nodes :enter and :leave when inserts and removals occur', () => { @Component({ selector: 'ani-cmp', animations: [ trigger('anim', [ transition('* => enter', [query(':enter', [animate(1000, style({color: 'red'}))])]), transition('* => leave', [query(':leave', [animate(1000, style({color: 'blue'}))])]), ]), ], template: ` <section class="container" [@anim]="exp ? 'enter' : 'leave'"> <div class="a" *ngIf="exp"> <div class="b" *ngIf="exp"> <div class="c" *ngIf="exp"> text </div> </div> </div> <div> <div class="d" *ngIf="exp"> text2 </div> </div> </section> `, standalone: false, }) class Cmp { public exp: boolean | undefined; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; const container = fixture.elementRef.nativeElement; cmp.exp = true; fixture.detectChanges(); engine.flush(); let players = getLog(); resetLog(); expect(players.length).toEqual(2); const [p1, p2] = players; expect(p1.element.classList.contains('a')).toBeTrue(); expect(p2.element.classList.contains('d')).toBeTrue(); cmp.exp = false; fixture.detectChanges(); engine.flush(); players = getLog(); resetLog(); expect(players.length).toEqual(2); const [p3, p4] = players; expect(p3.element.classList.contains('a')).toBeTrue(); expect(p4.element.classList.contains('d')).toBeTrue(); }); it('should collect multiple root levels of :enter and :leave nodes', () => { @Component({ selector: 'ani-cmp', animations: [ trigger('pageAnimation', [ transition(':enter', []), transition('* => *', [ query(':leave', [animate('1s', style({opacity: 0}))], {optional: true}), query(':enter', [animate('1s', style({opacity: 1}))], {optional: true}), ]), ]), ], template: ` <div [@pageAnimation]="status"> <header> <div *ngIf="!loading" class="title">{{ title }}</div> <div *ngIf="loading" class="loading">loading...</div> </header> <section> <div class="page"> <div *ngIf="page1" class="page1"> <div *ngIf="true">page 1</div> </div> <div *ngIf="page2" class="page2"> <div *ngIf="true">page 2</div> </div> </div> </section> </div> `, standalone: false, }) class Cmp { get title() { if (this.page1) { return 'hello from page1'; } return 'greetings from page2'; } page1 = false; page2 = false; loading = false; get status() { if (this.loading) return 'loading'; if (this.page1) return 'page1'; if (this.page2) return 'page2'; return ''; } } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.loading = true; fixture.detectChanges(); engine.flush(); let players = getLog(); resetLog(); cancelAllPlayers(players); cmp.page1 = true; cmp.loading = false; fixture.detectChanges(); engine.flush(); let p1: MockAnimationPlayer; let p2: MockAnimationPlayer; let p3: MockAnimationPlayer; players = getLog(); expect(players.length).toEqual(3); [p1, p2, p3] = players; expect(p1.element.classList.contains('loading')).toBe(true); expect(p2.element.classList.contains('title')).toBe(true); expect(p3.element.classList.contains('page1')).toBe(true); resetLog(); cancelAllPlayers(players); cmp.page1 = false; cmp.loading = true; fixture.detectChanges(); players = getLog(); cancelAllPlayers(players); expect(players.length).toEqual(3); [p1, p2, p3] = players; expect(p1.element.classList.contains('title')).toBe(true); expect(p2.element.classList.contains('page1')).toBe(true); expect(p3.element.classList.contains('loading')).toBe(true); resetLog(); cancelAllPlayers(players); cmp.page2 = true; cmp.loading = false; fixture.detectChanges(); engine.flush(); players = getLog(); expect(players.length).toEqual(3); [p1, p2, p3] = players; expect(p1.element.classList.contains('loading')).toBe(true); expect(p2.element.classList.contains('title')).toBe(true); expect(p3.element.classList.contains('page2')).toBe(true); }); it('should emulate leave animation callbacks for all sub elements that have leave triggers within the component', fakeAsync(() => { @Component({ selector: 'ani-cmp', animations: [ trigger('parent', []), trigger('child', []), trigger('childWithAnimation', [ transition(':leave', [animate(1000, style({background: 'red'}))]), ]), ], template: ` <div data-name="p" class="parent" @parent *ngIf="exp" (@parent.start)="callback($event)" (@parent.done)="callback($event)"> <div data-name="c1" @child (@child.start)="callback($event)" (@child.done)="callback($event)"></div> <div data-name="c2" @child (@child.start)="callback($event)" (@child.done)="callback($event)"></div> <div data-name="c3" @childWithAnimation (@childWithAnimation.start)="callback($event)" (@childWithAnimation.done)="callback($event)"></div> </div> `, standalone: false, }) class Cmp { public exp: boolean | undefined; public log: string[] = []; callback(event: any) { this.log.push(event.element.getAttribute('data-name') + '-' + event.phaseName); } } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = true; fixture.detectChanges(); flushMicrotasks(); cmp.log = []; cmp.exp = false; fixture.detectChanges(); flushMicrotasks(); expect(cmp.log).toEqual([ 'c1-start', 'c1-done', 'c2-start', 'c2-done', 'p-start', 'c3-start', 'c3-done', 'p-done', ]); })); it('should build, but not run
{ "end_byte": 87731, "start_byte": 78866, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_query_integration_spec.ts" }
angular/packages/core/test/animation/animation_query_integration_spec.ts_87739_95022
gers when a parent animation is scheduled', () => { @Component({ selector: 'parent-cmp', animations: [ trigger('parent', [transition('* => *', [animate(1000, style({opacity: 0}))])]), ], template: '<div [@parent]="exp"><child-cmp #child></child-cmp></div>', standalone: false, }) class ParentCmp { public exp: any; @ViewChild('child') public childCmp: any; } @Component({ selector: 'child-cmp', animations: [ trigger('child', [transition('* => *', [animate(1000, style({color: 'red'}))])]), ], template: '<div [@child]="exp"></div>', standalone: false, }) class ChildCmp { public exp: any; } TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(ParentCmp); fixture.detectChanges(); engine.flush(); resetLog(); const cmp = fixture.componentInstance; const childCmp = cmp.childCmp; cmp.exp = 1; childCmp.exp = 1; fixture.detectChanges(); engine.flush(); // we have 2 players, but the child is not used even though // it is created. const players = getLog(); expect(players.length).toEqual(2); expect(engine.players.length).toEqual(1); expect((engine.players[0] as TransitionAnimationPlayer).getRealPlayer()).toBe(players[1]); }); it('should fire and synchronize the start/done callbacks on sub triggers even if they are not allowed to animate within the animation', fakeAsync(() => { @Component({ selector: 'parent-cmp', animations: [ trigger('parent', [ transition('* => go', [ style({height: '0px'}), animate(1000, style({height: '100px'})), ]), ]), ], template: ` <div *ngIf="!remove" [@parent]="exp" (@parent.start)="track($event)" (@parent.done)="track($event)"> <child-cmp #child></child-cmp> </div> `, standalone: false, }) class ParentCmp { @ViewChild('child') public childCmp: any; public exp: any; public log: string[] = []; public remove = false; track(event: any) { this.log.push(`${event.triggerName}-${event.phaseName}`); } } @Component({ selector: 'child-cmp', animations: [ trigger('child', [ transition('* => go', [ style({width: '0px'}), animate(1000, style({width: '100px'})), ]), ]), ], template: ` <div [@child]="exp" (@child.start)="track($event)" (@child.done)="track($event)"></div> `, standalone: false, }) class ChildCmp { public exp: any; public log: string[] = []; track(event: any) { this.log.push(`${event.triggerName}-${event.phaseName}`); } } TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(ParentCmp); fixture.detectChanges(); flushMicrotasks(); const cmp = fixture.componentInstance; const child = cmp.childCmp; expect(cmp.log).toEqual(['parent-start', 'parent-done']); expect(child.log).toEqual(['child-start', 'child-done']); cmp.log = []; child.log = []; cmp.exp = 'go'; cmp.childCmp.exp = 'go'; fixture.detectChanges(); flushMicrotasks(); expect(cmp.log).toEqual(['parent-start']); expect(child.log).toEqual(['child-start']); const players = engine.players; expect(players.length).toEqual(1); players[0].finish(); expect(cmp.log).toEqual(['parent-start', 'parent-done']); expect(child.log).toEqual(['child-start', 'child-done']); cmp.log = []; child.log = []; cmp.remove = true; fixture.detectChanges(); flushMicrotasks(); expect(cmp.log).toEqual(['parent-start', 'parent-done']); expect(child.log).toEqual(['child-start', 'child-done']); })); it('should fire and synchronize the start/done callbacks on multiple blocked sub triggers', fakeAsync(() => { @Component({ selector: 'cmp', animations: [ trigger('parent1', [ transition('* => go, * => go-again', [ style({opacity: 0}), animate('1s', style({opacity: 1})), ]), ]), trigger('parent2', [ transition('* => go, * => go-again', [ style({lineHeight: '0px'}), animate('1s', style({lineHeight: '10px'})), ]), ]), trigger('child1', [ transition('* => go, * => go-again', [ style({width: '0px'}), animate('1s', style({width: '100px'})), ]), ]), trigger('child2', [ transition('* => go, * => go-again', [ style({height: '0px'}), animate('1s', style({height: '100px'})), ]), ]), ], template: ` <div [@parent1]="parent1Exp" (@parent1.start)="track($event)" [@parent2]="parent2Exp" (@parent2.start)="track($event)"> <div [@child1]="child1Exp" (@child1.start)="track($event)" [@child2]="child2Exp" (@child2.start)="track($event)"></div> </div> `, standalone: false, }) class Cmp { public parent1Exp = ''; public parent2Exp = ''; public child1Exp = ''; public child2Exp = ''; public log: string[] = []; track(event: any) { this.log.push(`${event.triggerName}-${event.phaseName}`); } } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); flushMicrotasks(); const cmp = fixture.componentInstance; cmp.log = []; cmp.parent1Exp = 'go'; cmp.parent2Exp = 'go'; cmp.child1Exp = 'go'; cmp.child2Exp = 'go'; fixture.detectChanges(); flushMicrotasks(); expect(cmp.log).toEqual(['parent1-start', 'parent2-start', 'child1-start', 'child2-start']); cmp.parent1Exp = 'go-again'; cmp.parent2Exp = 'go-again'; cmp.child1Exp = 'go-again'; cmp.child2Exp = 'go-again'; fixture.detectChanges(); flushMicrotasks(); })); it('should stretch the starting k
{ "end_byte": 95022, "start_byte": 87739, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_query_integration_spec.ts" }
angular/packages/core/test/animation/animation_query_integration_spec.ts_95030_102817
of a child animation queries are issued by the parent', () => { @Component({ selector: 'parent-cmp', animations: [ trigger('parent', [ transition('* => *', [ animate(1000, style({color: 'red'})), query('@child', animateChild()), ]), ]), ], template: '<div [@parent]="exp"><child-cmp #child></child-cmp></div>', standalone: false, }) class ParentCmp { public exp: any; @ViewChild('child') public childCmp: any; } @Component({ selector: 'child-cmp', animations: [ trigger('child', [ transition('* => *', [style({color: 'blue'}), animate(1000, style({color: 'red'}))]), ]), ], template: '<div [@child]="exp" class="child"></div>', standalone: false, }) class ChildCmp { public exp: any; } TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(ParentCmp); fixture.detectChanges(); engine.flush(); resetLog(); const cmp = fixture.componentInstance; const childCmp = cmp.childCmp; cmp.exp = 1; childCmp.exp = 1; fixture.detectChanges(); engine.flush(); expect(engine.players.length).toEqual(1); // child player, parent cover, parent player const groupPlayer = ( engine.players[0] as TransitionAnimationPlayer ).getRealPlayer() as AnimationGroupPlayer; const childPlayer = groupPlayer.players.find((player) => { if (player instanceof MockAnimationPlayer) { return player.element.classList.contains('child'); } return false; }) as MockAnimationPlayer; const keyframes = normalizeKeyframes(childPlayer.keyframes).map((kf) => { kf.delete('offset'); return kf; }); expect(keyframes.length).toEqual(3); const [k1, k2, k3] = keyframes; expect(k1).toEqual(k2); }); it('should allow a parent trigger to control child triggers across multiple template boundaries even if there are no animations in between', () => { @Component({ selector: 'parent-cmp', animations: [ trigger('parentAnimation', [ transition('* => go', [ query(':self, @grandChildAnimation', style({opacity: 0})), animate(1000, style({opacity: 1})), query('@grandChildAnimation', [animate(1000, style({opacity: 1})), animateChild()]), ]), ]), ], template: '<div [@parentAnimation]="exp"><child-cmp #child></child-cmp></div>', standalone: false, }) class ParentCmp { public exp: any; @ViewChild('child') public innerCmp: any; } @Component({ selector: 'child-cmp', template: '<grandchild-cmp #grandchild></grandchild-cmp>', standalone: false, }) class ChildCmp { @ViewChild('grandchild') public innerCmp: any; } @Component({ selector: 'grandchild-cmp', animations: [ trigger('grandChildAnimation', [ transition('* => go', [ style({width: '0px'}), animate(1000, style({width: '200px'})), ]), ]), ], template: '<div [@grandChildAnimation]="exp"></div>', standalone: false, }) class GrandChildCmp { public exp: any; } TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp, GrandChildCmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(ParentCmp); fixture.detectChanges(); engine.flush(); resetLog(); const cmp = fixture.componentInstance; const grandChildCmp = cmp.innerCmp.innerCmp; cmp.exp = 'go'; grandChildCmp.exp = 'go'; fixture.detectChanges(); engine.flush(); const players = getLog(); expect(players.length).toEqual(6); // players: // - _sgcp (skipped grand child player): player for the grand child animation // - _psp (parent self player): player for parent self animation (opacity 0) // - _pgcp1 (parent grand child player 1): // player for child animation executed by parent via query (opacity 0) // - _pp1 (parent player 1): player for parent animation (from opacity 0 to opacity 1) // - _pgcp2 (parent grand child player 2): // player for child animation executed by parent via query and animate // (from opacity 0 to opacity 1) // - pgcp3 (parent grand child player 3): // player for child animation executed by parent via query and animateChild // (from 0px to 200px) const [_sgcp, _psp, _pgcp1, _pp1, _pgcp2, pgcp3] = players; expect(pgcp3.keyframes).toEqual([ new Map<string, string | number>([ ['offset', 0], ['width', '0px'], ]), new Map<string, string | number>([ ['offset', 0.67], ['width', '0px'], ]), new Map<string, string | number>([ ['offset', 1], ['width', '200px'], ]), ]); }); it('should scope :enter queries between sub animations', () => { @Component({ selector: 'cmp', animations: [ trigger('parent', [ transition( ':enter', group([ sequence([style({opacity: 0}), animate(1000, style({opacity: 1}))]), query(':enter @child', animateChild()), ]), ), ]), trigger('child', [ transition(':enter', [ query(':enter .item', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), ]), ]), ], template: ` <div @parent *ngIf="exp1" class="container"> <div *ngIf="exp2"> <div @child> <div *ngIf="exp3"> <div class="item"></div> </div> </div> </div> </div> `, standalone: false, }) class Cmp { public exp1: any; public exp2: any; public exp3: any; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); resetLog(); const cmp = fixture.componentInstance; cmp.exp1 = true; cmp.exp2 = true; cmp.exp3 = true; fixture.detectChanges(); const players = getLog(); expect(players.length).toEqual(3); // players: // - _scp (skipped child player): player for the child animation // - pp (parent player): player for parent animation (from opacity 0 to opacity 1) // - pcp (parent child player): // player for child animation executed by parent via query and animateChild const [_scp, pp, pcp] = players; expect(pp.element.classList.contains('container')).toBeTruthy(); expect(pcp.element.classList.contains('item')).toBeTruthy(); }); it('should scope :leave queries bet
{ "end_byte": 102817, "start_byte": 95030, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_query_integration_spec.ts" }
angular/packages/core/test/animation/animation_query_integration_spec.ts_102825_110880
animations', () => { @Component({ selector: 'cmp', animations: [ trigger('parent', [ transition( ':leave', group([ sequence([style({opacity: 0}), animate(1000, style({opacity: 1}))]), query(':leave @child', animateChild()), ]), ), ]), trigger('child', [ transition(':leave', [ query(':leave .item', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), ]), ]), ], template: ` <div @parent *ngIf="exp1" class="container"> <div *ngIf="exp2"> <div @child> <div *ngIf="exp3"> <div class="item"></div> </div> </div> </div> </div> `, standalone: false, }) class Cmp { public exp1: any; public exp2: any; public exp3: any; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp1 = true; cmp.exp2 = true; cmp.exp3 = true; fixture.detectChanges(); resetLog(); cmp.exp1 = false; fixture.detectChanges(); const players = getLog(); expect(players.length).toEqual(3); // players: // - _scp (skipped child player): player for the child animation // - pp (parent player): player for parent animation (from opacity 0 to opacity 1) // - pcp (parent child player): // player for child animation executed by parent via query and animateChild const [_scp, pp, pcp] = players; expect(pp.element.classList.contains('container')).toBeTruthy(); expect(pcp.element.classList.contains('item')).toBeTruthy(); }); it('should correctly remove a leaving element queried/animated by a parent queried via animateChild', fakeAsync(() => { @Component({ selector: 'cmp', template: ` <div class="grand-parent" [@grandParentAnimation]="childPresent"> <div class="parent" [@parentAnimation]="childPresent"> <div *ngIf="childPresent" class="child"></div> </div> </div> `, animations: [ trigger('grandParentAnimation', [ transition('true <=> false', query('@parentAnimation', animateChild())), ]), trigger('parentAnimation', [ transition( 'true => false', query(':leave.child', animate('.2s', style({opacity: 0}))), ), ]), ], standalone: false, }) class Cmp { public childPresent = true; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; fixture.detectChanges(); let children = fixture.debugElement.nativeElement.querySelectorAll('.child'); expect(children.length).toEqual(1); cmp.childPresent = false; fixture.detectChanges(); flushMicrotasks(); engine.players.forEach((player) => player.finish()); children = fixture.debugElement.nativeElement.querySelectorAll('.child'); expect(children.length).toEqual(0); })); it('should correctly animate state styles of the root element applied via animate inside a group (independently of the order)', () => { @Component({ selector: 'cmp', template: ` <div class="parent" [@parent]="exp"> <div class="child" *ngIf="exp"></div> </div> `, animations: [ trigger('parent', [ state('true', style({backgroundColor: 'red'})), state('false', style({backgroundColor: 'blue'})), transition('true <=> false', [ group([ animate(500), query(':leave', [animate(500, style({opacity: 0}))], {optional: true}), query(':enter', [style({opacity: 0}), animate(500, style({opacity: '*'}))], { optional: true, }), ]), ]), ]), ], standalone: false, }) class Cmp { public exp = true; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; fixture.detectChanges(); cmp.exp = false; fixture.detectChanges(); const players = getLog(); expect(players.length).toEqual(3); // players: // - _pp1 (parent player 1): player for parent animation (from background red to red) // - pp2 (parent player 2): player for parent animation (from background red to blue) // - _cp (child player): player for child animation (from current opacity to 0) const [_pp1, pp2, _cp] = players; expect(pp2.element.classList.contains('parent')).toBeTruthy(); const expectedKeyframes = [ new Map<string, string | number>([ ['backgroundColor', 'red'], ['offset', 0], ]), new Map<string, string | number>([ ['backgroundColor', 'blue'], ['offset', 1], ]), ]; expect(pp2.keyframes).toEqual(expectedKeyframes); }); it('should correctly animate state styles of the root element applied via animate inside a sequence (independently of the order)', () => { @Component({ selector: 'cmp', template: ` <div class="parent" [@parent]="exp"> <div class="child" *ngIf="exp"></div> </div> `, animations: [ trigger('parent', [ state('true', style({backgroundColor: 'red'})), state('false', style({backgroundColor: 'blue'})), transition('true <=> false', [ sequence([ query(':enter', [style({opacity: 0}), animate(500, style({opacity: '*'}))], { optional: true, }), animate(500), query(':leave', [animate(500, style({opacity: 0}))], {optional: true}), ]), ]), ]), ], standalone: false, }) class Cmp { public exp = false; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; fixture.detectChanges(); cmp.exp = true; fixture.detectChanges(); const players = getLog(); expect(players.length).toEqual(3); // players: // - _pp1 (parent player 1): player for parent animation (from background blue to blue) // - _cp (child player): player for child animation (from opacity 0 to *) // - pp2 (parent player 2): player for parent animation (from background blue to red) const [_pp1, _cp, pp2] = players; expect(pp2.element.classList.contains('parent')).toBeTruthy(); const expectedKeyframes = [ new Map<string, string | number>([ ['backgroundColor', 'blue'], ['offset', 0], ]), new Map<string, string | number>([ ['backgroundColor', 'red'], ['offset', 1], ]), ]; expect(pp2.keyframes).toEqual(expectedKeyframes); }); }); describe('animation control flags', ()
{ "end_byte": 110880, "start_byte": 102825, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_query_integration_spec.ts" }
angular/packages/core/test/animation/animation_query_integration_spec.ts_110886_116226
describe('[@.disabled]', () => { it('should allow a parent animation to query and animate inner nodes that are in a disabled region', () => { @Component({ selector: 'some-cmp', template: ` <div [@myAnimation]="exp"> <div [@.disabled]="disabledExp"> <div class="header"></div> <div class="footer"></div> </div> </div> `, animations: [ trigger('myAnimation', [ transition('* => go', [ query('.header', animate(750, style({opacity: 0}))), query('.footer', animate(250, style({opacity: 0}))), ]), ]), ], standalone: false, }) class Cmp { exp: any = ''; disabledExp = false; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.disabledExp = true; fixture.detectChanges(); resetLog(); cmp.exp = 'go'; fixture.detectChanges(); const players = getLog(); expect(players.length).toEqual(2); const [p1, p2] = players; expect(p1.duration).toEqual(750); expect(p1.element.classList.contains('header')).toBeTrue(); expect(p2.duration).toEqual(250); expect(p2.element.classList.contains('footer')).toBeTrue(); }); it('should allow a parent animation to query and animate sub animations that are in a disabled region', () => { @Component({ selector: 'some-cmp', template: ` <div class="parent" [@parentAnimation]="exp"> <div [@.disabled]="disabledExp"> <div class="child" [@childAnimation]="exp"></div> </div> </div> `, animations: [ trigger('parentAnimation', [ transition('* => go', [ query('@childAnimation', animateChild()), animate(1000, style({opacity: 0})), ]), ]), trigger('childAnimation', [ transition('* => go', [animate(500, style({opacity: 0}))]), ]), ], standalone: false, }) class Cmp { exp: any = ''; disabledExp = false; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.disabledExp = true; fixture.detectChanges(); resetLog(); cmp.exp = 'go'; fixture.detectChanges(); const players = getLog(); expect(players.length).toEqual(2); const [p1, p2] = players; expect(p1.duration).toEqual(500); expect(p1.element.classList.contains('child')).toBeTrue(); expect(p2.duration).toEqual(1000); expect(p2.element.classList.contains('parent')).toBeTrue(); }); it('should disable the animation for the given element regardless of existing parent element animation queries or child element animation queries', () => { @Component({ selector: 'some-cmp', template: ` <div class="parent" [@parentAnimation]="exp"> <div class="child" [@.disabled]="disabledExp" [@childAnimation]="exp"> <div class="grand-child" [@grandChildAnimation]="exp"></div> </div> </div> `, animations: [ trigger('parentAnimation', [ transition('* => go', [ query('@*', animateChild()), animate(1500, style({opacity: 0})), ]), ]), trigger('childAnimation', [ transition('* => go', [animate(1000, style({opacity: 0}))]), ]), trigger('grandChildAnimation', [ transition('* => go', [animate(500, style({opacity: 0}))]), ]), ], standalone: false, }) class Cmp { exp: any = ''; disabledExp = false; } TestBed.configureTestingModule({declarations: [Cmp]}); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.disabledExp = true; fixture.detectChanges(); resetLog(); cmp.exp = 'go'; fixture.detectChanges(); const players = getLog(); expect(players.length).toEqual(2); const [p1, p2] = players; expect(p1.duration).toEqual(500); expect(p1.element.classList.contains('grand-child')).toBeTrue(); expect(p2.duration).toEqual(1500); expect(p2.element.classList.contains('parent')).toBeTrue(); }); }); }); }); })(); function cancelAllPlayers(players: AnimationPlayer[]) { players.forEach((p) => p.destroy()); }
{ "end_byte": 116226, "start_byte": 110886, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_query_integration_spec.ts" }
angular/packages/core/test/animation/animation_router_integration_spec.ts_0_8536
/** * @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 { animate, animateChild, group, query, sequence, style, transition, trigger, ɵAnimationGroupPlayer as AnimationGroupPlayer, } from '@angular/animations'; import {AnimationDriver, ɵAnimationEngine} from '@angular/animations/browser'; import {TransitionAnimationPlayer} from '@angular/animations/browser/src/render/transition_animation_engine'; import {MockAnimationDriver, MockAnimationPlayer} from '@angular/animations/browser/testing'; import {Component, HostBinding} from '@angular/core'; import {fakeAsync, flushMicrotasks, TestBed, tick} from '@angular/core/testing'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {ActivatedRoute, Router, RouterModule, RouterOutlet} from '@angular/router'; (function () { // these tests are only meant to be run within the DOM (for now) if (isNode) return; describe('Animation Router Tests', function () { function getLog(): MockAnimationPlayer[] { return MockAnimationDriver.log as MockAnimationPlayer[]; } function resetLog() { MockAnimationDriver.log = []; } beforeEach(() => { resetLog(); TestBed.configureTestingModule({ imports: [RouterModule.forRoot([]), BrowserAnimationsModule], providers: [{provide: AnimationDriver, useClass: MockAnimationDriver}], }); }); it('should query the old and new routes via :leave and :enter', fakeAsync(() => { @Component({ animations: [ trigger('routerAnimations', [ transition('page1 => page2', [ query(':leave', animateChild()), query(':enter', animateChild()), ]), ]), ], template: ` <div [@routerAnimations]="prepareRouteAnimation(r)"> <router-outlet #r="outlet"></router-outlet> </div> `, standalone: false, }) class ContainerCmp { constructor(public router: Router) {} prepareRouteAnimation(r: RouterOutlet) { const animation = r.activatedRouteData['animation']; const value = animation ? animation['value'] : null; return value; } } @Component({ selector: 'page1', template: `page1`, animations: [ trigger('page1Animation', [ transition(':leave', [style({width: '200px'}), animate(1000, style({width: '0px'}))]), ]), ], standalone: false, }) class Page1Cmp { @HostBinding('@page1Animation') public doAnimate = true; } @Component({ selector: 'page2', template: `page2`, animations: [ trigger('page2Animation', [ transition(':enter', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), ]), ], standalone: false, }) class Page2Cmp { @HostBinding('@page2Animation') public doAnimate = true; } TestBed.configureTestingModule({ declarations: [Page1Cmp, Page2Cmp, ContainerCmp], imports: [ RouterModule.forRoot([ {path: 'page1', component: Page1Cmp, data: makeAnimationData('page1')}, {path: 'page2', component: Page2Cmp, data: makeAnimationData('page2')}, ]), ], }); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(ContainerCmp); const cmp = fixture.componentInstance; cmp.router.initialNavigation(); tick(); fixture.detectChanges(); engine.flush(); cmp.router.navigateByUrl('/page1'); tick(); fixture.detectChanges(); engine.flush(); cmp.router.navigateByUrl('/page2'); tick(); fixture.detectChanges(); engine.flush(); const player = engine.players[0]!; const groupPlayer = ( player as TransitionAnimationPlayer ).getRealPlayer() as AnimationGroupPlayer; const players = groupPlayer.players as MockAnimationPlayer[]; expect(players.length).toEqual(2); const [p1, p2] = players; expect(p1.duration).toEqual(1000); expect(p1.keyframes).toEqual([ new Map<string, string | number>([ ['offset', 0], ['width', '200px'], ]), new Map<string, string | number>([ ['offset', 1], ['width', '0px'], ]), ]); expect(p2.duration).toEqual(2000); expect(p2.keyframes).toEqual([ new Map<string, string | number>([ ['offset', 0], ['opacity', '0'], ]), new Map<string, string | number>([ ['offset', 0.5], ['opacity', '0'], ]), new Map<string, string | number>([ ['offset', 1], ['opacity', '1'], ]), ]); })); it('should allow inner enter animations to be emulated within a routed item', fakeAsync(() => { @Component({ animations: [ trigger('routerAnimations', [ transition('page1 => page2', [query(':enter', animateChild())]), ]), ], template: ` <div [@routerAnimations]="prepareRouteAnimation(r)"> <router-outlet #r="outlet"></router-outlet> </div> `, standalone: false, }) class ContainerCmp { constructor(public router: Router) {} prepareRouteAnimation(r: RouterOutlet) { const animation = r.activatedRouteData['animation']; const value = animation ? animation['value'] : null; return value; } } @Component({ selector: 'page1', template: `page1`, animations: [], standalone: false, }) class Page1Cmp {} @Component({ selector: 'page2', template: ` <h1>Page 2</h1> <div *ngIf="exp" class="if-one" @ifAnimation></div> <div *ngIf="exp" class="if-two" @ifAnimation></div> `, animations: [ trigger('page2Animation', [ transition(':enter', [ query('.if-one', animateChild()), query('.if-two', animateChild()), ]), ]), trigger('ifAnimation', [ transition(':enter', [style({opacity: 0}), animate(1000, style({opacity: 1}))]), ]), ], standalone: false, }) class Page2Cmp { @HostBinding('@page2Animation') public doAnimate = true; public exp = true; } TestBed.configureTestingModule({ declarations: [Page1Cmp, Page2Cmp, ContainerCmp], imports: [ RouterModule.forRoot([ {path: 'page1', component: Page1Cmp, data: makeAnimationData('page1')}, {path: 'page2', component: Page2Cmp, data: makeAnimationData('page2')}, ]), ], }); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(ContainerCmp); const cmp = fixture.componentInstance; cmp.router.initialNavigation(); tick(); fixture.detectChanges(); engine.flush(); cmp.router.navigateByUrl('/page1'); tick(); fixture.detectChanges(); engine.flush(); cmp.router.navigateByUrl('/page2'); tick(); fixture.detectChanges(); engine.flush(); const player = engine.players[0]!; const groupPlayer = ( player as TransitionAnimationPlayer ).getRealPlayer() as AnimationGroupPlayer; const players = groupPlayer.players as MockAnimationPlayer[]; expect(players.length).toEqual(2); const [p1, p2] = players; expect(p1.keyframes).toEqual([ new Map<string, string | number>([ ['offset', 0], ['opacity', '0'], ]), new Map<string, string | number>([ ['offset', 1], ['opacity', '1'], ]), ]); expect(p2.keyframes).toEqual([ new Map<string, string | number>([ ['offset', 0], ['opacity', '0'], ]), new Map<string, string | number>([ ['offset', 0.5], ['opacity', '0'], ]), new Map<string, string | number>([ ['offset', 1], ['opacity', '1'], ]), ]); }));
{ "end_byte": 8536, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_router_integration_spec.ts" }
angular/packages/core/test/animation/animation_router_integration_spec.ts_8542_17494
should allow inner leave animations to be emulated within a routed item', fakeAsync(() => { @Component({ animations: [ trigger('routerAnimations', [ transition('page1 => page2', [query(':leave', animateChild())]), ]), ], template: ` <div [@routerAnimations]="prepareRouteAnimation(r)"> <router-outlet #r="outlet"></router-outlet> </div> `, standalone: false, }) class ContainerCmp { constructor(public router: Router) {} prepareRouteAnimation(r: RouterOutlet) { const animation = r.activatedRouteData['animation']; const value = animation ? animation['value'] : null; return value; } } @Component({ selector: 'page1', template: ` <h1>Page 1</h1> <div *ngIf="exp" class="if-one" @ifAnimation></div> <div *ngIf="exp" class="if-two" @ifAnimation></div> `, animations: [ trigger('page1Animation', [ transition(':leave', [ query('.if-one', animateChild()), query('.if-two', animateChild()), ]), ]), trigger('ifAnimation', [ transition(':leave', [style({opacity: 1}), animate(1000, style({opacity: 0}))]), ]), ], standalone: false, }) class Page1Cmp { @HostBinding('@page1Animation') public doAnimate = true; public exp = true; } @Component({ selector: 'page2', template: `page2`, animations: [], standalone: false, }) class Page2Cmp {} TestBed.configureTestingModule({ declarations: [Page1Cmp, Page2Cmp, ContainerCmp], imports: [ RouterModule.forRoot([ {path: 'page1', component: Page1Cmp, data: makeAnimationData('page1')}, {path: 'page2', component: Page2Cmp, data: makeAnimationData('page2')}, ]), ], }); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(ContainerCmp); const cmp = fixture.componentInstance; cmp.router.initialNavigation(); tick(); fixture.detectChanges(); engine.flush(); cmp.router.navigateByUrl('/page1'); tick(); fixture.detectChanges(); engine.flush(); cmp.router.navigateByUrl('/page2'); tick(); fixture.detectChanges(); engine.flush(); const player = engine.players[0]!; const groupPlayer = ( player as TransitionAnimationPlayer ).getRealPlayer() as AnimationGroupPlayer; const players = groupPlayer.players as MockAnimationPlayer[]; expect(players.length).toEqual(2); const [p1, p2] = players; expect(p1.keyframes).toEqual([ new Map<string, string | number>([ ['offset', 0], ['opacity', '1'], ]), new Map<string, string | number>([ ['offset', 1], ['opacity', '0'], ]), ]); expect(p2.keyframes).toEqual([ new Map<string, string | number>([ ['offset', 0], ['opacity', '1'], ]), new Map<string, string | number>([ ['offset', 0.5], ['opacity', '1'], ]), new Map<string, string | number>([ ['offset', 1], ['opacity', '0'], ]), ]); })); it('should properly collect :enter / :leave router nodes even when another non-router *template component is within the trigger boundaries', fakeAsync(() => { @Component({ selector: 'ani-cmp', animations: [ trigger('pageAnimation', [ transition('page1 => page2', [ query('.router-container :leave', animate('1s', style({opacity: 0}))), query('.router-container :enter', animate('1s', style({opacity: 1}))), ]), ]), ], template: ` <div [@pageAnimation]="prepRoute(outlet)"> <header> <div class="inner"> <div *ngIf="!loading" class="title">Page Ready</div> <div *ngIf="loading" class="loading">loading...</div> </div> </header> <section class="router-container"> <router-outlet #outlet="outlet"></router-outlet> </section> </div> `, standalone: false, }) class ContainerCmp { loading = false; constructor(public router: Router) {} prepRoute(outlet: any) { return outlet.activatedRouteData['animation']; } } @Component({ selector: 'page1', template: `page1`, standalone: false, }) class Page1Cmp {} @Component({ selector: 'page2', template: `page2`, standalone: false, }) class Page2Cmp {} TestBed.configureTestingModule({ declarations: [Page1Cmp, Page2Cmp, ContainerCmp], imports: [ RouterModule.forRoot([ {path: 'page1', component: Page1Cmp, data: makeAnimationData('page1')}, {path: 'page2', component: Page2Cmp, data: makeAnimationData('page2')}, ]), ], }); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(ContainerCmp); const cmp = fixture.componentInstance; cmp.router.initialNavigation(); tick(); fixture.detectChanges(); engine.flush(); cmp.router.navigateByUrl('/page1'); tick(); cmp.loading = true; fixture.detectChanges(); engine.flush(); cmp.router.navigateByUrl('/page2'); tick(); cmp.loading = false; fixture.detectChanges(); engine.flush(); const players = engine.players; expect(players.length).toEqual(1); const [p1] = players; const innerPlayers = ( (p1 as TransitionAnimationPlayer).getRealPlayer() as AnimationGroupPlayer ).players; expect(innerPlayers.length).toEqual(2); const [ip1, ip2] = innerPlayers as any; expect(ip1.element.innerText).toEqual('page1'); expect(ip2.element.innerText).toEqual('page2'); })); it('should allow a recursive set of :leave animations to occur for nested routes', fakeAsync(() => { @Component({ selector: 'ani-cmp', template: '<router-outlet name="recur"></router-outlet>', standalone: false, }) class ContainerCmp { constructor(private _router: Router) {} log: string[] = []; enter() { this._router.navigateByUrl('/(recur:recur/nested)'); } leave() { this._router.navigateByUrl('/'); } } @Component({ selector: 'recur-page', template: 'Depth: {{ depth }} \n <router-outlet></router-outlet>', animations: [ trigger('pageAnimations', [ transition(':leave', [ group([ sequence([style({opacity: 1}), animate('1s', style({opacity: 0}))]), query('@*', animateChild(), {optional: true}), ]), ]), ]), ], standalone: false, }) class RecurPageCmp { @HostBinding('@pageAnimations') public animatePage = true; @HostBinding('attr.data-depth') public depth = 0; constructor( private container: ContainerCmp, private route: ActivatedRoute, ) { this.route.data.subscribe((data) => { this.container.log.push(`DEPTH ${data['depth']}`); this.depth = data['depth']; }); } } TestBed.configureTestingModule({ declarations: [ContainerCmp, RecurPageCmp], imports: [ RouterModule.forRoot([ { path: 'recur', component: RecurPageCmp, outlet: 'recur', data: {depth: 0}, children: [{path: 'nested', component: RecurPageCmp, data: {depth: 1}}], }, ]), ], }); const fixture = TestBed.createComponent(ContainerCmp); const cmp = fixture.componentInstance; cmp.enter(); tick(); fixture.detectChanges(); flushMicrotasks(); expect(cmp.log).toEqual(['DEPTH 0', 'DEPTH 1']); cmp.leave(); tick(); fixture.detectChanges(); const players = getLog(); expect(players.length).toEqual(2); const [p1, p2] = players; expect(p1.element.getAttribute('data-depth')).toEqual('0'); expect(p2.element.getAttribute('data-depth')).toEqual('1'); })); }); }); function makeAnimationData(value: string, params: {[key: string]: any} = {}): {[key: string]: any} { return {'animation': {value, params}}; }
{ "end_byte": 17494, "start_byte": 8542, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_router_integration_spec.ts" }
angular/packages/core/test/animation/animations_with_web_animations_integration_spec.ts_0_806
/** * @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 {animate, query, state, style, transition, trigger} from '@angular/animations'; import { AnimationDriver, ɵAnimationEngine, ɵWebAnimationsDriver, ɵWebAnimationsPlayer, } from '@angular/animations/browser'; import {TransitionAnimationPlayer} from '@angular/animations/browser/src/render/transition_animation_engine'; import {AnimationGroupPlayer} from '@angular/animations/src/players/animation_group_player'; import {Component, ViewChild} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; (
{ "end_byte": 806, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animations_with_web_animations_integration_spec.ts" }
angular/packages/core/test/animation/animations_with_web_animations_integration_spec.ts_808_9259
nction () { // these tests are only meant to be run within the DOM (for now) // Buggy in Chromium 39, see https://github.com/angular/angular/issues/15793 if (isNode) return; describe('animation integration tests using web animations', function () { beforeEach(() => { TestBed.configureTestingModule({ providers: [{provide: AnimationDriver, useClass: ɵWebAnimationsDriver}], imports: [BrowserAnimationsModule], }); }); it('should compute (*) animation styles for a container that is being removed', () => { @Component({ selector: 'ani-cmp', template: ` <div @auto *ngIf="exp"> <div style="line-height:20px;">1</div> <div style="line-height:20px;">2</div> <div style="line-height:20px;">3</div> <div style="line-height:20px;">4</div> <div style="line-height:20px;">5</div> </div> `, animations: [ trigger('auto', [ state('void', style({height: '0px'})), state('*', style({height: '*'})), transition('* => *', animate(1000)), ]), ], standalone: false, }) class Cmp { public exp: boolean = false; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = true; fixture.detectChanges(); expect(engine.players.length).toEqual(1); let webPlayer = ( engine.players[0] as TransitionAnimationPlayer ).getRealPlayer() as ɵWebAnimationsPlayer; expect(webPlayer.keyframes).toEqual([ new Map<string, string | number>([ ['height', '0px'], ['offset', 0], ]), new Map<string, string | number>([ ['height', '100px'], ['offset', 1], ]), ]); webPlayer.finish(); cmp.exp = false; fixture.detectChanges(); engine.flush(); expect(engine.players.length).toEqual(1); webPlayer = ( engine.players[0] as TransitionAnimationPlayer ).getRealPlayer() as ɵWebAnimationsPlayer; expect(webPlayer.keyframes).toEqual([ new Map<string, string | number>([ ['height', '100px'], ['offset', 0], ]), new Map<string, string | number>([ ['height', '0px'], ['offset', 1], ]), ]); }); it('should compute (!) animation styles for a container that is being inserted', () => { @Component({ selector: 'ani-cmp', template: ` <div @auto *ngIf="exp"> <div style="line-height:20px;">1</div> <div style="line-height:20px;">2</div> <div style="line-height:20px;">3</div> <div style="line-height:20px;">4</div> <div style="line-height:20px;">5</div> </div> `, animations: [ trigger('auto', [ transition(':enter', [style({height: '!'}), animate(1000, style({height: '120px'}))]), ]), ], standalone: false, }) class Cmp { public exp: boolean = false; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = true; fixture.detectChanges(); engine.flush(); expect(engine.players.length).toEqual(1); let webPlayer = ( engine.players[0] as TransitionAnimationPlayer ).getRealPlayer() as ɵWebAnimationsPlayer; expect(webPlayer.keyframes).toEqual([ new Map<string, string | number>([ ['height', '100px'], ['offset', 0], ]), new Map<string, string | number>([ ['height', '120px'], ['offset', 1], ]), ]); }); it('should compute pre (!) and post (*) animation styles with different dom states', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp" #parent> <div *ngFor="let item of items" class="child" style="line-height:20px"> - {{ item }} </div> </div> `, animations: [ trigger('myAnimation', [ transition('* => *', [style({height: '!'}), animate(1000, style({height: '*'}))]), ]), ], standalone: false, }) class Cmp { public exp!: number; public items = [0, 1, 2, 3, 4]; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 1; fixture.detectChanges(); engine.flush(); expect(engine.players.length).toEqual(1); let player = engine.players[0]; let webPlayer = (player as TransitionAnimationPlayer).getRealPlayer() as ɵWebAnimationsPlayer; expect(webPlayer.keyframes).toEqual([ new Map<string, string | number>([ ['height', '0px'], ['offset', 0], ]), new Map<string, string | number>([ ['height', '100px'], ['offset', 1], ]), ]); // we destroy the player because since it has started and is // at 0ms duration a height value of `0px` will be extracted // from the element and passed into the follow-up animation. player.destroy(); cmp.exp = 2; cmp.items = [0, 1, 2, 6]; fixture.detectChanges(); engine.flush(); expect(engine.players.length).toEqual(1); player = engine.players[0]; webPlayer = (player as TransitionAnimationPlayer).getRealPlayer() as ɵWebAnimationsPlayer; expect(webPlayer.keyframes).toEqual([ new Map<string, string | number>([ ['height', '100px'], ['offset', 0], ]), new Map<string, string | number>([ ['height', '80px'], ['offset', 1], ]), ]); }); it('should treat * styles as ! when a removal animation is being rendered', () => { @Component({ selector: 'ani-cmp', styles: [ ` .box { width: 500px; overflow:hidden; background:orange; line-height:300px; font-size:100px; text-align:center; } `, ], template: ` <button (click)="toggle()">Open / Close</button> <hr /> <div *ngIf="exp" @slide class="box"> ... </div> `, animations: [ trigger('slide', [ state('void', style({height: '0px'})), state('*', style({height: '*'})), transition('* => *', animate('500ms')), ]), ], standalone: false, }) class Cmp { exp = false; toggle() { this.exp = !this.exp; } } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = true; fixture.detectChanges(); let player = engine.players[0]; let webPlayer = (player as TransitionAnimationPlayer).getRealPlayer() as ɵWebAnimationsPlayer; expect(webPlayer.keyframes).toEqual([ new Map<string, string | number>([ ['height', '0px'], ['offset', 0], ]), new Map<string, string | number>([ ['height', '300px'], ['offset', 1], ]), ]); player.finish(); cmp.exp = false; fixture.detectChanges(); player = engine.players[0]; webPlayer = (player as TransitionAnimationPlayer).getRealPlayer() as ɵWebAnimationsPlayer; expect(webPlayer.keyframes).toEqual([ new Map<string, string | number>([ ['height', '300px'], ['offset', 0], ]), new Map<string, string | number>([ ['height', '0px'], ['offset', 1], ]), ]); }); it('shoul
{ "end_byte": 9259, "start_byte": 808, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animations_with_web_animations_integration_spec.ts" }
angular/packages/core/test/animation/animations_with_web_animations_integration_spec.ts_9265_16460
t * styles as ! for queried items that are collected in a container that is being removed', () => { @Component({ selector: 'my-app', styles: [ ` .list .outer { overflow:hidden; } .list .inner { box-sizing: border-box; height: 50px; } `, ], template: ` <button (click)="empty()">Empty</button> <button (click)="middle()">Middle</button> <button (click)="full()">Full</button> <hr /> <div [@list]="exp" class="list"> <div *ngFor="let item of items" class="outer"> <div class="inner"> {{ item }} </div> </div> </div> `, animations: [ trigger('list', [ transition(':enter', []), transition('* => empty', [query(':leave', [animate(500, style({height: '0px'}))])]), transition('* => full', [ query(':enter', [style({height: '0px'}), animate(500, style({height: '*'}))]), ]), ]), ], standalone: false, }) class Cmp { items: any[] = []; get exp() { return this.items.length ? 'full' : 'empty'; } empty() { this.items = []; } full() { this.items = [0, 1, 2, 3, 4]; } } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.empty(); fixture.detectChanges(); let player = engine.players[0] as TransitionAnimationPlayer; player.finish(); cmp.full(); fixture.detectChanges(); player = engine.players[0] as TransitionAnimationPlayer; let queriedPlayers = ( (player as TransitionAnimationPlayer).getRealPlayer() as AnimationGroupPlayer ).players; expect(queriedPlayers.length).toEqual(5); let i = 0; for (i = 0; i < queriedPlayers.length; i++) { let player = queriedPlayers[i] as ɵWebAnimationsPlayer; expect(player.keyframes).toEqual([ new Map<string, string | number>([ ['height', '0px'], ['offset', 0], ]), new Map<string, string | number>([ ['height', '50px'], ['offset', 1], ]), ]); player.finish(); } cmp.empty(); fixture.detectChanges(); player = engine.players[0] as TransitionAnimationPlayer; queriedPlayers = ( (player as TransitionAnimationPlayer).getRealPlayer() as AnimationGroupPlayer ).players; expect(queriedPlayers.length).toEqual(5); for (i = 0; i < queriedPlayers.length; i++) { let player = queriedPlayers[i] as ɵWebAnimationsPlayer; expect(player.keyframes).toEqual([ new Map<string, string | number>([ ['height', '50px'], ['offset', 0], ]), new Map<string, string | number>([ ['height', '0px'], ['offset', 1], ]), ]); } }); it('should compute intermediate styles properly when an animation is cancelled', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp" style="background-color: blue;">...</div> `, animations: [ trigger('myAnimation', [ transition('* => a', [ style({width: 0, height: 0}), animate('1s', style({width: '300px', height: '600px'})), ]), transition('* => b', [animate('1s', style({opacity: 0}))]), ]), ], standalone: false, }) class Cmp { public exp: string | undefined; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'a'; fixture.detectChanges(); const player1 = engine.players[0]; const webPlayer1 = ( player1 as TransitionAnimationPlayer ).getRealPlayer() as ɵWebAnimationsPlayer; webPlayer1.setPosition(0.5); cmp.exp = 'b'; fixture.detectChanges(); const player2 = engine.players[0]; const webPlayer2 = ( player2 as TransitionAnimationPlayer ).getRealPlayer() as ɵWebAnimationsPlayer; expect( approximate(parseFloat(webPlayer2.keyframes[0].get('width') as string), 150), ).toBeLessThan(0.05); expect( approximate(parseFloat(webPlayer2.keyframes[0].get('height') as string), 300), ).toBeLessThan(0.05); }); it('should compute intermediate styles properly for multiple queried elements when an animation is cancelled', () => { @Component({ selector: 'ani-cmp', template: ` <div [@myAnimation]="exp"> <div *ngFor="let item of items" class="target"></div> </div> `, animations: [ trigger('myAnimation', [ transition('* => full', [ query('.target', [ style({width: 0, height: 0}), animate('1s', style({width: '500px', height: '1000px'})), ]), ]), transition('* => empty', [query('.target', [animate('1s', style({opacity: 0}))])]), ]), ], standalone: false, }) class Cmp { public exp: string | undefined; public items: any[] = []; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; cmp.exp = 'full'; cmp.items = [0, 1, 2, 3, 4]; fixture.detectChanges(); let player = engine.players[0]; let groupPlayer = ( player as TransitionAnimationPlayer ).getRealPlayer() as AnimationGroupPlayer; let players = groupPlayer.players; expect(players.length).toEqual(5); for (let i = 0; i < players.length; i++) { const p = players[i] as ɵWebAnimationsPlayer; p.setPosition(0.5); } cmp.exp = 'empty'; cmp.items = []; fixture.detectChanges(); player = engine.players[0]; groupPlayer = (player as TransitionAnimationPlayer).getRealPlayer() as AnimationGroupPlayer; players = groupPlayer.players; expect(players.length).toEqual(5); for (let i = 0; i < players.length; i++) { const p = players[i] as ɵWebAnimationsPlayer; expect(approximate(parseFloat(p.keyframes[0].get('width') as string), 250)).toBeLessThan( 0.05, ); expect(approximate(parseFloat(p.keyframes[0].get('height') as string), 500)).toBeLessThan( 0.05, ); } }); it('should apply t
{ "end_byte": 16460, "start_byte": 9265, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animations_with_web_animations_integration_spec.ts" }
angular/packages/core/test/animation/animations_with_web_animations_integration_spec.ts_16466_21837
splay` and `position` styles as regular inline styles for the duration of the animation', () => { @Component({ selector: 'ani-cmp', template: ` <div #elm [@myAnimation]="myAnimationExp" style="display:table; position:fixed"></div> `, animations: [ trigger('myAnimation', [ state('go', style({display: 'inline-block'})), transition('* => go', [ style({display: 'inline', position: 'absolute', opacity: 0}), animate('1s', style({display: 'inline', opacity: 1, position: 'static'})), animate('1s', style({display: 'flexbox', opacity: 0})), ]), ]), ], standalone: false, }) class Cmp { @ViewChild('elm', {static: true}) public element: any; public myAnimationExp = ''; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; const elm = cmp.element.nativeElement; expect(elm.style.getPropertyValue('display')).toEqual('table'); expect(elm.style.getPropertyValue('position')).toEqual('fixed'); cmp.myAnimationExp = 'go'; fixture.detectChanges(); expect(elm.style.getPropertyValue('display')).toEqual('inline'); expect(elm.style.getPropertyValue('position')).toEqual('absolute'); const player = engine.players.pop()!; player.finish(); player.destroy(); expect(elm.style.getPropertyValue('display')).toEqual('inline-block'); expect(elm.style.getPropertyValue('position')).toEqual('fixed'); }); it('should set normalized style property values on animation end', () => { @Component({ selector: 'ani-cmp', template: ` <div #elm [@myAnimation]="myAnimationExp" style="width: 100%; font-size: 2rem"></div> `, animations: [ trigger('myAnimation', [ state('go', style({width: 300, 'font-size': 14})), transition('* => go', [animate('1s')]), ]), ], standalone: false, }) class Cmp { @ViewChild('elm', {static: true}) public element: any; public myAnimationExp = ''; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; const elm = cmp.element.nativeElement; expect(elm.style.getPropertyValue('width')).toEqual('100%'); expect(elm.style.getPropertyValue('font-size')).toEqual('2rem'); cmp.myAnimationExp = 'go'; fixture.detectChanges(); const player = engine.players.pop()!; player.finish(); player.destroy(); expect(elm.style.getPropertyValue('width')).toEqual('300px'); expect(elm.style.getPropertyValue('font-size')).toEqual('14px'); }); it('should apply correct state transitions for both CamelCase and kebab-case CSS properties', () => { @Component({ selector: 'ani-cmp', template: ` <div id="camelCaseDiv" [@camelCaseTrigger]="status"></div> <div id="kebab-case-div" [@kebab-case-trigger]="status"></div> `, animations: [ trigger('camelCaseTrigger', [ state( 'active', style({ 'backgroundColor': 'green', }), ), transition('inactive => active', [ style({ 'backgroundColor': 'red', }), animate(500), ]), ]), trigger('kebab-case-trigger', [ state( 'active', style({ 'background-color': 'green', }), ), transition('inactive => active', [ style({ 'background-color': 'red', }), animate(500), ]), ]), ], standalone: false, }) class Cmp { public status: 'active' | 'inactive' = 'inactive'; } TestBed.configureTestingModule({declarations: [Cmp]}); const engine = TestBed.inject(ɵAnimationEngine); const fixture = TestBed.createComponent(Cmp); const cmp = fixture.componentInstance; fixture.detectChanges(); cmp.status = 'active'; fixture.detectChanges(); engine.flush(); expect(engine.players.length).toEqual(2); const [camelCaseWebPlayer, kebabCaseWebPlayer] = engine.players.map( (player) => (player as TransitionAnimationPlayer).getRealPlayer() as ɵWebAnimationsPlayer, ); [camelCaseWebPlayer, kebabCaseWebPlayer].forEach((webPlayer) => { expect(webPlayer.keyframes).toEqual([ new Map<string, string | number>([ ['backgroundColor', 'red'], ['offset', 0], ]), new Map<string, string | number>([ ['backgroundColor', 'green'], ['offset', 1], ]), ]); }); }); }); })(); function approximate(value: number, target: number) { return Math.abs(target - value) / value; }
{ "end_byte": 21837, "start_byte": 16466, "url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animations_with_web_animations_integration_spec.ts" }
angular/packages/core/test/authoring/input_signal_spec.ts_0_3145
/** * @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, computed, effect, input} from '@angular/core'; import {SIGNAL} from '@angular/core/primitives/signals'; import {setUseMicrotaskEffectsByDefault} from '@angular/core/src/render3/reactivity/effect'; import {TestBed} from '@angular/core/testing'; describe('input signal', () => { let prev: boolean; beforeEach(() => { prev = setUseMicrotaskEffectsByDefault(false); }); afterEach(() => setUseMicrotaskEffectsByDefault(prev)); it('should properly notify live consumers (effect)', () => { @Component({ template: '', standalone: false, }) class TestCmp { input = input(0); effectCalled = 0; constructor() { effect(() => { this.effectCalled++; this.input(); }); } } const fixture = TestBed.createComponent(TestCmp); const node = fixture.componentInstance.input[SIGNAL]; fixture.detectChanges(); expect(fixture.componentInstance.effectCalled).toBe(1); node.applyValueToInputSignal(node, 1); fixture.detectChanges(); expect(fixture.componentInstance.effectCalled).toBe(2); }); it('should work with computed expressions', () => { TestBed.runInInjectionContext(() => { const signal = input(0); let computedCount = 0; const derived = computed(() => (computedCount++, signal() + 1000)); const node = signal[SIGNAL]; expect(derived()).toBe(1000); expect(computedCount).toBe(1); node.applyValueToInputSignal(node, 1); expect(computedCount).toBe(1); expect(derived()).toBe(1001); expect(computedCount).toBe(2); }); }); it('should capture transform for later use in framework', () => { TestBed.runInInjectionContext(() => { const signal = input(0, {transform: (v: number) => v + 1000}); const node = signal[SIGNAL]; expect(node.transformFn?.(1)).toBe(1001); }); }); it('should throw if there is no value for required inputs', () => { TestBed.runInInjectionContext(() => { const signal = input.required(); const node = signal[SIGNAL]; expect(() => signal()).toThrowError(/Input is required but no value is available yet\./); node.applyValueToInputSignal(node, 1); expect(signal()).toBe(1); }); }); it('should throw if a `computed` depends on an uninitialized required input', () => { TestBed.runInInjectionContext(() => { const signal = input.required<number>(); const expr = computed(() => signal() + 1000); const node = signal[SIGNAL]; expect(() => expr()).toThrowError(/Input is required but no value is available yet\./); node.applyValueToInputSignal(node, 1); expect(expr()).toBe(1001); }); }); it('should have a toString implementation', () => { TestBed.runInInjectionContext(() => { const signal = input(0); expect(signal + '').toBe('[Input Signal: 0]'); }); }); });
{ "end_byte": 3145, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/authoring/input_signal_spec.ts" }
angular/packages/core/test/authoring/type_tester.ts_0_2814
/** * @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 fs from 'fs'; import path from 'path'; import ts from 'typescript'; import url from 'url'; /** Currently-configured tests. */ const TESTS = new Map<string, (value: string) => string>([ [ 'signal_input_signature_test', (v) => (v.includes(',') ? `InputSignalWithTransform<${v}>` : `InputSignal<${v}>`), ], ['signal_queries_signature_test', (v) => `Signal<${v}>`], ['signal_model_signature_test', (v) => `ModelSignal<${v}>`], ['unwrap_writable_signal_signature_test', (v) => v], ]); const containingDir = path.dirname(url.fileURLToPath(import.meta.url)); /** * Verify that we are looking at a test class declaration (a given file might have multiple class * declarations). */ function isTestClass(classDeclaration: ts.ClassDeclaration): boolean { return classDeclaration.name !== undefined && classDeclaration.name.text.endsWith('Test'); } function testFile(testFileName: string, getType: (v: string) => string): boolean { const fileContent = fs.readFileSync(path.join(containingDir, `${testFileName}.d.ts`), 'utf8'); const sourceFile = ts.createSourceFile('test.ts', fileContent, ts.ScriptTarget.ESNext, true); const testClazz = sourceFile.statements.find( (s): s is ts.ClassDeclaration => ts.isClassDeclaration(s) && isTestClass(s), ); if (testClazz === undefined) { return false; } let failing = false; for (const member of testClazz.members) { if (!ts.isPropertyDeclaration(member)) { continue; } const leadingCommentRanges = ts.getLeadingCommentRanges(sourceFile.text, member.getFullStart()); const leadingComments = leadingCommentRanges?.map((r) => sourceFile.text.substring(r.pos, r.end), ); if (leadingComments === undefined || leadingComments.length === 0) { throw new Error(`No expected type for: ${member.name.getText()}`); } // strip comment start, and beginning (plus whitespace). const expectedTypeComment = leadingComments[0].replace(/(^\/\*\*?\s*|\s*\*+\/$)/g, ''); const expectedType = getType(expectedTypeComment); // strip excess whitespace or newlines. const got = member.type?.getText().replace(/(\n+|\s\s+)/g, ''); if (expectedType !== got) { console.error(`${member.name.getText()}: expected: ${expectedType}, got: ${got}`); failing = true; } } return failing; } async function main() { let failing = false; TESTS.forEach((callback, filename) => (failing ||= testFile(filename, callback))); if (failing) { throw new Error('Failing assertions'); } } main().catch((e) => { console.error(e); process.exitCode = 1; });
{ "end_byte": 2814, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/authoring/type_tester.ts" }
angular/packages/core/test/authoring/signal_model_signature_test.ts_0_1602
/** * @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 */ /** * @fileoverview * This file contains various signal `model()` patterns and ensures * the resulting types match our expectations (via comments asserting the `.d.ts`). */ import {model} from '@angular/core'; // import preserved to simplify `.d.ts` emit and simplify the `type_tester` logic. // tslint:disable-next-line no-duplicate-imports import {ModelSignal} from '@angular/core'; export class SignalModelSignatureTest { /** string | undefined */ noInitialValueExplicitRead = model<string>(); /** boolean */ initialValueBooleanNoType = model(false); /** string */ initialValueStringNoType = model('bla'); /** number */ initialValueNumberNoType = model(0); /** string[] */ initialValueObjectNoType = model([] as string[]); /** number */ initialValueEmptyOptions = model(1, {}); /** RegExp */ nonPrimitiveInitialValue = model(/default regex/); /** string | undefined */ withNoInitialValue = model<string>(); /** string */ requiredNoInitialValue = model.required<string>(); /** string | undefined */ requiredNoInitialValueExplicitUndefined = model.required<string | undefined>(); /** unknown */ noInitialValueNoType = model(); /** string */ requiredNoInitialValueNoType = model.required<string>(); /** @internal */ __shouldErrorIfInitialValueWithRequired = model.required({ // @ts-expect-error initialValue: 0, }); }
{ "end_byte": 1602, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/authoring/signal_model_signature_test.ts" }
angular/packages/core/test/authoring/signal_queries_signature_test.ts_0_7462
/** * @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 { contentChild, contentChildren, ElementRef, forwardRef, InjectionToken, Signal, viewChild, viewChildren, } from '@angular/core'; class QueryType { // a random field to brand the type query = true; } class ReadType { // a random field to brand the type read = true; } const QUERY_TYPE_TOKEN = new InjectionToken<QueryType>('QueryTypeToken'); // A const to reference the Signal type import const _import: Signal<unknown> | undefined = undefined; export class SignalQuerySignatureTest { // optional view child /** unknown */ viewChildStringLocatorNoRead = viewChild('ref'); /** ElementRef<HTMLAnchorElement> | undefined */ viewChildStringLocatorNoReadElementRefTypeHint = viewChild<ElementRef<HTMLAnchorElement>>('ref'); // any due to https://github.com/angular/angular/issues/53894 /** ElementRef<any> | undefined */ viewChildStringLocatorWithElementRefRead = viewChild('ref', { read: ElementRef<HTMLAnchorElement>, }); /** ReadType | undefined */ viewChildStringLocatorWithRead = viewChild('ref', {read: ReadType}); /** QueryType | undefined */ viewChildTypeLocatorNoRead = viewChild(QueryType); /** any */ viewChildTypeLocatorForwardRefNoRead = viewChild(forwardRef(() => QueryType)); /** QueryType | undefined */ viewChildInjectionTokenLocatorNoRead = viewChild(QUERY_TYPE_TOKEN); /** ReadType | undefined */ viewChildTypeLocatorAndRead = viewChild(QueryType, {read: ReadType}); // any due to https://github.com/angular/angular/issues/53894 /** ElementRef<any> | undefined */ viewChildTypeLocatorAndElementRefRead = viewChild(QueryType, { read: ElementRef<HTMLAnchorElement>, }); // required view child /** ElementRef<HTMLAnchorElement> */ viewChildStringLocatorNoReadElementRefTypeHintReq = viewChild.required<ElementRef<HTMLAnchorElement>>('ref'); // any due to https://github.com/angular/angular/issues/53894 /** ElementRef<any> */ viewChildStringLocatorWithElementRefReadReq = viewChild.required('ref', { read: ElementRef<HTMLAnchorElement>, }); /** ReadType */ viewChildStringLocatorWithReadReq = viewChild.required('ref', {read: ReadType}); /** QueryType */ viewChildTypeLocatorNoReadReq = viewChild.required(QueryType); /** ReadType */ viewChildTypeLocatorAndReadReq = viewChild.required(QueryType, {read: ReadType}); // any due to https://github.com/angular/angular/issues/53894 /** ElementRef<any> */ viewChildTypeLocatorAndElementRefReadReq = viewChild.required(QueryType, { read: ElementRef<HTMLAnchorElement>, }); // view children /** readonly unknown[] */ viewChildrenStringLocatorNoRead = viewChildren('ref'); /** readonly ElementRef<HTMLAnchorElement>[] */ viewChildrenStringLocatorNoReadElementRefTypeHint = viewChildren<ElementRef<HTMLAnchorElement>>('ref'); /** readonly ReadType[] */ viewChildrenStringLocatorWithTypeRead = viewChildren('ref', {read: ReadType}); // any due to https://github.com/angular/angular/issues/53894 /** readonly ElementRef<any>[] */ viewChildrenStringLocatorWithElementRefRead = viewChildren('ref', { read: ElementRef<HTMLAnchorElement>, }); /** readonly QueryType[]*/ viewChildrenTypeLocatorNoRead = viewChildren(QueryType); /** readonly any[] */ viewChildrenTypeLocatorForwardRefNoRead = viewChildren(forwardRef(() => QueryType)); /** readonly QueryType[] */ viewChildrenInjectionTokenLocatorNoRead = viewChildren(QUERY_TYPE_TOKEN); /** readonly ReadType[] */ viewChildrenTypeLocatorAndRead = viewChildren(QueryType, {read: ReadType}); // any due to https://github.com/angular/angular/issues/53894 /** readonly ElementRef<any>[] */ viewChildrenTypeLocatorAndElementRefRead = viewChildren(QueryType, { read: ElementRef<HTMLAnchorElement>, }); // optional content child /** unknown */ contentChildStringLocatorNoRead = contentChild('ref'); /** ElementRef<HTMLAnchorElement> | undefined */ contentChildStringLocatorNoReadElementRefTypeHint = contentChild<ElementRef<HTMLAnchorElement>>('ref'); // any due to https://github.com/angular/angular/issues/53894 /** ElementRef<any> | undefined */ contentChildStringLocatorWithElementRefRead = contentChild('ref', { read: ElementRef<HTMLAnchorElement>, }); /** ReadType | undefined */ contentChildStringLocatorWithRead = contentChild('ref', {read: ReadType}); /** QueryType | undefined */ contentChildTypeLocatorNoRead = contentChild(QueryType); /** any */ contentChildTypeLocatorForwardRefNoRead = contentChild(forwardRef(() => QueryType)); /** QueryType | undefined */ contentChildInjectionTokenLocatorNoRead = contentChild(QUERY_TYPE_TOKEN); /** ReadType | undefined */ contentChildTypeLocatorAndRead = contentChild(QueryType, {read: ReadType}); // any due to https://github.com/angular/angular/issues/53894 /** ElementRef<any> | undefined */ contentChildTypeLocatorAndElementRefRead = contentChild(QueryType, { read: ElementRef<HTMLAnchorElement>, }); // required content child /** ElementRef<HTMLAnchorElement> */ contentChildStringLocatorNoReadElementRefTypeHintReq = contentChild.required<ElementRef<HTMLAnchorElement>>('ref'); // any due to https://github.com/angular/angular/issues/53894 /** ElementRef<any> */ contentChildStringLocatorWithElementRefReadReq = contentChild.required('ref', { read: ElementRef<HTMLAnchorElement>, }); /** ReadType */ contentChildStringLocatorWithReadReq = contentChild.required('ref', {read: ReadType}); /** QueryType */ contentChildTypeLocatorNoReadReq = contentChild.required(QueryType); /** ReadType */ contentChildTypeLocatorAndReadReq = contentChild.required(QueryType, {read: ReadType}); // any due to https://github.com/angular/angular/issues/53894 /** ElementRef<any> */ contentChildTypeLocatorAndElementRefReadReq = contentChild.required(QueryType, { read: ElementRef<HTMLAnchorElement>, }); // view children /** readonly unknown[] */ contentChildrenStringLocatorNoRead = contentChildren('ref'); /** readonly ElementRef<HTMLAnchorElement>[] */ contentChildrenStringLocatorNoReadElementRefTypeHint = contentChildren<ElementRef<HTMLAnchorElement>>('ref'); /** readonly ReadType[] */ contentChildrenStringLocatorWithTypeRead = contentChildren('ref', {read: ReadType}); // any due to https://github.com/angular/angular/issues/53894 /** readonly ElementRef<any>[] */ contentChildrenStringLocatorWithElementRefRead = contentChildren('ref', { read: ElementRef<HTMLAnchorElement>, }); /** readonly QueryType[]*/ contentChildrenTypeLocatorNoRead = contentChildren(QueryType); /** readonly any[] */ contentChildrenTypeLocatorForwardRefNoRead = contentChildren(forwardRef(() => QueryType)); /** readonly QueryType[] */ contentChildrenInjectionTokenLocatorNoRead = contentChildren(QUERY_TYPE_TOKEN); /** readonly ReadType[] */ contentChildrenTypeLocatorAndRead = contentChildren(QueryType, {read: ReadType}); // any due to https://github.com/angular/angular/issues/53894 /** readonly ElementRef<any>[] */ contentChildrenTypeLocatorAndElementRefRead = contentChildren(QueryType, { read: ElementRef<HTMLAnchorElement>, }); }
{ "end_byte": 7462, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/authoring/signal_queries_signature_test.ts" }
angular/packages/core/test/authoring/signal_input_signature_test.ts_0_4067
/** * @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 */ /** * @fileoverview * This file contains various signal `input()` patterns and ensures * the resulting types match our expectations (via comments asserting the `.d.ts`). */ import {input} from '@angular/core'; // import preserved to simplify `.d.ts` emit and simplify the `type_tester` logic. // tslint:disable-next-line no-duplicate-imports import {InputSignal, InputSignalWithTransform} from '@angular/core'; export class InputSignatureTest { /** string | undefined */ noInitialValueExplicitRead = input<string>(); /** boolean */ initialValueBooleanNoType = input(false); /** string */ initialValueStringNoType = input('bla'); /** number */ initialValueNumberNoType = input(0); /** string[] */ initialValueObjectNoType = input([] as string[]); /** number */ initialValueEmptyOptions = input(1, {}); /** @internal */ // @ts-expect-error Transform is needed __explicitWriteTWithoutTransformForbidden = input<string, string>('bla__'); /** number, string | number */ noInitialValueWithTransform = input.required({transform: (_v: number | string) => 0}); /** number, string | number */ initialValueWithTransform = input(0, {transform: (_v: number | string) => 0}); /** boolean | undefined, string | boolean */ undefinedInitialValueWithTransform = input(undefined, { transform: (_v: boolean | string) => true, }); /** {works: boolean;}, string | boolean */ complexTransformWithInitialValue = input( {works: true}, { transform: (_v: boolean | string) => ({works: !!_v}), }, ); /** RegExp */ nonPrimitiveInitialValue = input(/default regex/); /** string, string | null */ requiredExplicitReadAndWriteButNoTransform = input.required<string, string | null>({ transform: (_v) => '', }); /** string, string | null */ withInitialValueExplicitReadAndWrite = input<string, string | null>('', {transform: (bla) => ''}); /** string | undefined */ withNoInitialValue = input<string>(); /** undefined */ initialValueUndefinedWithoutOptions = input(undefined); /** undefined */ initialValueUndefinedWithOptions = input(undefined, {}); /** @internal */ __shouldErrorIfInitialValueUndefinedExplicitReadWithoutOptions = input<string>( // @ts-expect-error undefined, ); /** string | undefined, unknown */ initialValueUndefinedWithUntypedTransform = input(undefined, {transform: (bla) => ''}); /** string | undefined, string */ initialValueUndefinedWithTypedTransform = input(undefined, {transform: (bla: string) => ''}); /** string | undefined, string */ initialValueUndefinedExplicitReadWithTransform = input<string, string>(undefined, { transform: (bla) => '', }); /** string */ requiredNoInitialValue = input.required<string>(); /** string | undefined */ requiredNoInitialValueExplicitUndefined = input.required<string | undefined>(); /** string, string | boolean */ requiredWithTransform = input.required<string, string | boolean>({ transform: (v: string | boolean) => '', }); /** @internal */ __requiredWithTransformButNoWriteT = input.required<string>({ // @ts-expect-error transform: (v: string | boolean) => '', }); /** string, string | boolean */ requiredWithTransformInferenceNoExplicitGeneric = input.required({ transform: (v: string | boolean) => '', }); // Unknown as `WriteT` is acceptable because the user explicitly opted into handling // the transform- so they will need to work with the `unknown` values. /** string, unknown */ requiredTransformButNoTypes = input.required({transform: (v) => ''}); /** unknown */ noInitialValueNoType = input(); /** string */ requiredNoInitialValueNoType = input.required<string>(); /** @internal */ __shouldErrorIfInitialValueWithRequired = input.required({ // @ts-expect-error initialValue: 0, }); }
{ "end_byte": 4067, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/authoring/signal_input_signature_test.ts" }
angular/packages/core/test/authoring/BUILD.bazel_0_1207
load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "nodejs_test", "ts_library") ts_library( name = "signal_authoring_signature_test_lib", testonly = True, srcs = [ "signal_input_signature_test.ts", "signal_model_signature_test.ts", "signal_queries_signature_test.ts", "unwrap_writable_signal_signature_test.ts", ], deps = ["//packages/core"], ) ts_library( name = "type_tester_lib", testonly = True, srcs = ["type_tester.ts"], deps = [ "@npm//typescript", ], ) nodejs_test( name = "type_test", data = [ ":signal_authoring_signature_test_lib", ":type_tester_lib", ], entry_point = ":type_tester.ts", ) ts_library( name = "test_lib", testonly = True, srcs = [ "input_signal_spec.ts", "model_input_spec.ts", ], deps = [ "//packages/core", "//packages/core/primitives/signals", "//packages/core/testing", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node"], deps = [ ":test_lib", ], ) karma_web_test_suite( name = "test_web", deps = [":test_lib"], )
{ "end_byte": 1207, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/authoring/BUILD.bazel" }
angular/packages/core/test/authoring/unwrap_writable_signal_signature_test.ts_0_1426
/** * @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 */ /** * @fileoverview * This file contains various signal `model()` patterns and ensures * the resulting types match our expectations (via comments asserting the `.d.ts`). */ import {input, model, signal, ɵunwrapWritableSignal as unwrapWritableSignal} from '@angular/core'; // import preserved to simplify `.d.ts` emit and simplify the `type_tester` logic. // tslint:disable-next-line no-duplicate-imports import {InputSignal, WritableSignal} from '@angular/core'; export class SignalModelSignatureTest { /** string | undefined */ optionalModel = unwrapWritableSignal(model<string>()); /** string */ requiredModel = unwrapWritableSignal(model.required<string>()); /** string | number */ writableSignal = unwrapWritableSignal(signal<string | number>(0)); /** InputSignal<string | undefined> */ optionalReadonlySignal = unwrapWritableSignal(input<string>()); /** InputSignal<string> */ requiredReadonlySignal = unwrapWritableSignal(input.required<string>()); /** number */ primitiveValue = unwrapWritableSignal(123); /** (value: string | null | undefined) => number */ getterFunction = unwrapWritableSignal((value: string | null | undefined) => value ? parseInt(value) : 0, ); }
{ "end_byte": 1426, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/authoring/unwrap_writable_signal_signature_test.ts" }
angular/packages/core/test/authoring/model_input_spec.ts_0_4602
/** * @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 {computed, isSignal, model, WritableSignal} from '@angular/core'; import {TestBed} from '@angular/core/testing'; describe('model signal', () => { it('should work with computed expressions', () => { const signal = TestBed.runInInjectionContext(() => model(0)); let computedCount = 0; const derived = computed(() => (computedCount++, signal() + 1000)); expect(derived()).toBe(1000); expect(computedCount).toBe(1); signal.set(1); expect(computedCount).toBe(1); expect(derived()).toBe(1001); expect(computedCount).toBe(2); }); it('should allow updates based on the previous value', () => { const signal = TestBed.runInInjectionContext(() => model(2)); signal.update((value) => value * 3); expect(signal()).toBe(6); signal.update((value) => value * 3); expect(signal()).toBe(18); }); it('should return readonly signal', () => { const signal = TestBed.runInInjectionContext(() => model(2)); const readOnly = signal.asReadonly(); expect(isSignal(readOnly)).toBeTrue(); expect(readOnly()).toBe(2); expect((readOnly as WritableSignal<unknown>).set).toBeUndefined(); expect((readOnly as WritableSignal<unknown>).update).toBeUndefined(); }); it('should emit when the value changes', () => { const signal = TestBed.runInInjectionContext(() => model(1)); const values: number[] = []; signal.subscribe((value) => values.push(value)); signal.set(2); expect(values).toEqual([2]); signal.update((previous) => previous * 2); expect(values).toEqual([2, 4]); signal.set(5); expect(values).toEqual([2, 4, 5]); }); it('should error when subscribing to a destroyed model', () => { const signal = TestBed.runInInjectionContext(() => model(1)); const values: number[] = []; signal.subscribe((value) => values.push(value)); TestBed.resetTestingModule(); expect(() => signal.subscribe(() => {})).toThrowError( /Unexpected subscription to destroyed `OutputRef`/, ); }); it('should stop emitting after unsubscribing', () => { const signal = TestBed.runInInjectionContext(() => model(0)); const values: number[] = []; const subscription = signal.subscribe((value) => values.push(value)); signal.set(1); expect(values).toEqual([1]); subscription.unsubscribe(); signal.set(2); expect(values).toEqual([1]); }); it('should not emit if the value does not change', () => { const signal = TestBed.runInInjectionContext(() => model(0)); const values: number[] = []; signal.subscribe((value) => values.push(value)); signal.set(1); expect(values).toEqual([1]); signal.set(1); expect(values).toEqual([1]); signal.update((previous) => previous * 2); expect(values).toEqual([1, 2]); signal.update((previous) => previous * 1); expect(values).toEqual([1, 2]); }); it('should not share subscriptions between models', () => { let emitCount = 0; const signal1 = TestBed.runInInjectionContext(() => model(0)); const signal2 = TestBed.runInInjectionContext(() => model(0)); const callback = () => emitCount++; const subscription1 = signal1.subscribe(callback); const subscription2 = signal2.subscribe(callback); signal1.set(1); expect(emitCount).toBe(1); signal2.set(1); expect(emitCount).toBe(2); subscription1.unsubscribe(); signal2.set(2); expect(emitCount).toBe(3); subscription2.unsubscribe(); signal2.set(3); expect(emitCount).toBe(3); }); it('should throw if there is no value for required model', () => { const signal = TestBed.runInInjectionContext(() => model.required()); expect(() => signal()).toThrowError(/Model is required but no value is available yet\./); signal.set(1); expect(signal()).toBe(1); }); it('should throw if a `computed` depends on an uninitialized required model', () => { const signal = TestBed.runInInjectionContext(() => model.required<number>()); const expr = computed(() => signal() + 1000); expect(() => expr()).toThrowError(/Model is required but no value is available yet\./); signal.set(1); expect(expr()).toBe(1001); }); it('should have a toString implementation', () => { const signal = TestBed.runInInjectionContext(() => model(0)); expect(signal + '').toBe('[Model Signal: 0]'); }); });
{ "end_byte": 4602, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/authoring/model_input_spec.ts" }
angular/packages/core/test/acceptance/ng_module_spec.ts_0_7039
/** * @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, createNgModule, CUSTOM_ELEMENTS_SCHEMA, destroyPlatform, Directive, Injectable, InjectionToken, NgModule, NgModuleRef, NO_ERRORS_SCHEMA, Pipe, ɵsetClassMetadata as setClassMetadata, ɵɵdefineComponent as defineComponent, ɵɵdefineInjector as defineInjector, ɵɵdefineNgModule as defineNgModule, ɵɵelement as element, ɵɵproperty as property, } from '@angular/core'; import {KNOWN_CONTROL_FLOW_DIRECTIVES} from '@angular/core/src/render3/instructions/element_validation'; import {TestBed} from '@angular/core/testing'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {withBody} from '@angular/private/testing'; describe('NgModule', () => { @Component({ template: 'hello', standalone: false, }) class TestCmp {} @Component({ template: 'hello', standalone: false, }) class TestCmp2 {} describe('bootstrap', () => { it('should throw when specified bootstrap component is not added to a module', () => { @NgModule({bootstrap: [TestCmp, [TestCmp2]]}) class MyModule {} TestBed.configureTestingModule({imports: [MyModule]}); expect(() => { TestBed.createComponent(TestCmp); TestBed.createComponent(TestCmp2); }).toThrowError(/not part of any NgModule/); }); it('should not throw when specified bootstrap component is added to a module', () => { @NgModule({declarations: [TestCmp, TestCmp2], bootstrap: [TestCmp, [TestCmp2]]}) class MyModule {} TestBed.configureTestingModule({imports: [MyModule]}); expect(() => { TestBed.createComponent(TestCmp); TestBed.createComponent(TestCmp2); }).not.toThrow(); }); }); it('initializes the module imports before the module itself', () => { @Injectable() class Service { initializations: string[] = []; } @NgModule({providers: [Service]}) class RoutesModule { constructor(service: Service) { service.initializations.push('RoutesModule'); } } @NgModule({imports: [RoutesModule]}) class AppModule { constructor(service: Service) { service.initializations.push('AppModule'); } } TestBed.configureTestingModule({imports: [AppModule]}); expect(TestBed.inject(Service).initializations).toEqual(['RoutesModule', 'AppModule']); }); describe('standalone components, directives, and pipes', () => { it('should throw when a standalone component is added to NgModule declarations', () => { @Component({ selector: 'my-comp', standalone: true, template: '', }) class MyComp {} @NgModule({ declarations: [MyComp], }) class MyModule {} TestBed.configureTestingModule({imports: [MyModule]}); expect(() => { TestBed.createComponent(MyComp); }).toThrowError( `Unexpected "MyComp" found in the "declarations" array of the "MyModule" NgModule, "MyComp" is marked as standalone and can't be declared in any NgModule - did you intend to import it instead (by adding it to the "imports" array)?`, ); }); it('should throw when a standalone directive is added to NgModule declarations', () => { @Directive({ selector: '[my-dir]', standalone: true, }) class MyDir {} @Component({ selector: 'my-comp', template: '', standalone: false, }) class MyComp {} @NgModule({ declarations: [MyDir], }) class MyModule {} TestBed.configureTestingModule({declarations: [MyComp], imports: [MyModule]}); expect(() => { TestBed.createComponent(MyComp); }).toThrowError( `Unexpected "MyDir" found in the "declarations" array of the "MyModule" NgModule, "MyDir" is marked as standalone and can't be declared in any NgModule - did you intend to import it instead (by adding it to the "imports" array)?`, ); }); it('should throw when a standalone pipe is added to NgModule declarations', () => { @Pipe({ name: 'my-pipe', standalone: true, }) class MyPipe {} @Component({ selector: 'my-comp', template: '', standalone: false, }) class MyComp {} @NgModule({ declarations: [MyPipe], }) class MyModule {} TestBed.configureTestingModule({declarations: [MyComp], imports: [MyModule]}); expect(() => { TestBed.createComponent(MyComp); }).toThrowError( `Unexpected "MyPipe" found in the "declarations" array of the "MyModule" NgModule, "MyPipe" is marked as standalone and can't be declared in any NgModule - did you intend to import it instead (by adding it to the "imports" array)?`, ); }); it('should throw a testing specific error when a standalone component is added to the configureTestingModule declarations', () => { @Component({ selector: 'my-comp', template: '', standalone: true, }) class MyComp {} expect(() => { TestBed.configureTestingModule({declarations: [MyComp]}); }).toThrowError( `Unexpected "MyComp" found in the "declarations" array of the "TestBed.configureTestingModule" call, "MyComp" is marked as standalone and can't be declared in any NgModule - did you intend to import it instead (by adding it to the "imports" array)?`, ); }); }); describe('destroy', () => { beforeEach(destroyPlatform); afterEach(destroyPlatform); it( 'should clear bootstrapped component contents', withBody('<div>before</div><button></button><div>after</div>', async () => { let wasOnDestroyCalled = false; @Component({ selector: 'button', template: 'button content', standalone: false, }) class App { ngOnDestroy() { wasOnDestroyCalled = true; } } @NgModule({ imports: [BrowserModule], declarations: [App], bootstrap: [App], }) class AppModule {} const ngModuleRef = await platformBrowserDynamic().bootstrapModule(AppModule); const button = document.body.querySelector('button')!; expect(button.textContent).toEqual('button content'); expect(document.body.childNodes.length).toEqual(3); ngModuleRef.destroy(); expect(wasOnDestroyCalled).toEqual(true); expect(document.body.querySelector('button')).toBeFalsy(); // host element is removed expect(document.body.childNodes.length).toEqual(2); // other elements are preserved }), ); }); describ
{ "end_byte": 7039, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/ng_module_spec.ts" }
angular/packages/core/test/acceptance/ng_module_spec.ts_7043_15909
chemas', () => { it('should log an error on unknown props if NO_ERRORS_SCHEMA is absent', () => { @Component({ selector: 'my-comp', template: ` <ng-container *ngIf="condition"> <div [unknown-prop]="true"></div> </ng-container> `, standalone: false, }) class MyComp { condition = true; } @NgModule({ imports: [CommonModule], declarations: [MyComp], }) class MyModule {} TestBed.configureTestingModule({imports: [MyModule]}); const spy = spyOn(console, 'error'); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(spy.calls.mostRecent().args[0]).toMatch( /Can't bind to 'unknown-prop' since it isn't a known property of 'div' \(used in the 'MyComp' component template\)/, ); }); it('should log an error on unknown props of `ng-template` if NO_ERRORS_SCHEMA is absent', () => { @Component({ selector: 'my-comp', template: ` <ng-template *ngIf="condition"></ng-template> `, standalone: false, }) class MyComp { condition = true; } @NgModule({ declarations: [MyComp], }) class MyModule {} TestBed.configureTestingModule({imports: [MyModule]}); const spy = spyOn(console, 'error'); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(spy.calls.mostRecent().args[0]).toMatch( /Can't bind to 'ngIf' since it isn't a known property of 'ng-template' \(used in the 'MyComp' component template\)/, ); }); it('should log an error on unknown props of `ng-container` if NO_ERRORS_SCHEMA is absent', () => { @Component({ selector: 'my-comp', template: ` <ng-container *ngIf="condition"></ng-container> `, standalone: false, }) class MyComp { condition = true; } @NgModule({ declarations: [MyComp], }) class MyModule {} TestBed.configureTestingModule({imports: [MyModule]}); const spy = spyOn(console, 'error'); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(spy.calls.mostRecent().args[0]).toMatch( /Can't bind to 'ngIf' since it isn't a known property of 'ng-container' \(used in the 'MyComp' component template\)/, ); }); it('should log an error on unknown props of `ng-content` if NO_ERRORS_SCHEMA is absent', () => { @Component({ selector: 'my-comp', template: ` <ng-content *ngIf="condition"></ng-content> `, standalone: false, }) class MyComp { condition = true; } @NgModule({ declarations: [MyComp], }) class MyModule {} TestBed.configureTestingModule({imports: [MyModule]}); const spy = spyOn(console, 'error'); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(spy.calls.mostRecent().args[0]).toMatch( /Can't bind to 'ngIf' since it isn't a known property of 'ng-content' \(used in the 'MyComp' component template\)/, ); }); it('should throw an error with errorOnUnknownProperties on unknown props if NO_ERRORS_SCHEMA is absent', () => { @Component({ selector: 'my-comp', template: ` <ng-container *ngIf="condition"> <div [unknown-prop]="true"></div> </ng-container> `, standalone: false, }) class MyComp { condition = true; } @NgModule({ imports: [CommonModule], declarations: [MyComp], }) class MyModule {} TestBed.configureTestingModule({imports: [MyModule], errorOnUnknownProperties: true}); expect(() => { const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); }).toThrowError( /NG0303: Can't bind to 'unknown-prop' since it isn't a known property of 'div' \(used in the 'MyComp' component template\)/g, ); }); it('should not throw on unknown props if NO_ERRORS_SCHEMA is present', () => { @Component({ selector: 'my-comp', template: ` <ng-container *ngIf="condition"> <div [unknown-prop]="true"></div> </ng-container> `, standalone: false, }) class MyComp { condition = true; } @NgModule({ imports: [CommonModule], schemas: [NO_ERRORS_SCHEMA], declarations: [MyComp], }) class MyModule {} TestBed.configureTestingModule({imports: [MyModule]}); expect(() => { const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); }).not.toThrow(); }); it('should not throw on unknown props with errorOnUnknownProperties if NO_ERRORS_SCHEMA is present', () => { @Component({ selector: 'my-comp', template: ` <ng-container *ngIf="condition"> <div [unknown-prop]="true"></div> </ng-container> `, standalone: false, }) class MyComp { condition = true; } @NgModule({ imports: [CommonModule], schemas: [NO_ERRORS_SCHEMA], declarations: [MyComp], }) class MyModule {} TestBed.configureTestingModule({imports: [MyModule], errorOnUnknownProperties: true}); expect(() => { const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); }).not.toThrow(); }); it('should log an error about unknown element without CUSTOM_ELEMENTS_SCHEMA for element with dash in tag name', () => { @Component({ template: `<custom-el></custom-el>`, standalone: false, }) class MyComp {} const spy = spyOn(console, 'error'); TestBed.configureTestingModule({declarations: [MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(spy.calls.mostRecent().args[0]).toMatch(/'custom-el' is not a known element/); }); it('should log an error about unknown element for a standalone component without CUSTOM_ELEMENTS_SCHEMA', () => { @Component({ template: `<custom-el></custom-el>`, standalone: true, }) class MyComp {} const spy = spyOn(console, 'error'); TestBed.configureTestingModule({imports: [MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(spy.calls.mostRecent().args[0]).toMatch(/'custom-el' is not a known element/); }); it('should not log an error about unknown element for a standalone component with CUSTOM_ELEMENTS_SCHEMA', () => { @Component({ template: `<custom-el></custom-el>`, standalone: true, schemas: [CUSTOM_ELEMENTS_SCHEMA], }) class MyComp {} const spy = spyOn(console, 'error'); TestBed.configureTestingModule({imports: [MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(spy).not.toHaveBeenCalled(); }); it('should throw an error about unknown element without CUSTOM_ELEMENTS_SCHEMA for element with dash in tag name', () => { @Component({ template: `<custom-el></custom-el>`, standalone: false, }) class MyComp {} TestBed.configureTestingModule({declarations: [MyComp], errorOnUnknownElements: true}); expect(() => { const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); }).toThrowError(/NG0304: 'custom-el' is not a known element/g); }); it('should log an error about unknown element without CUSTOM_ELEMENTS_SCHEMA for element without dash in tag name', () => { @Component({ template: `<custom></custom>`, standalone: false, }) class MyComp {} const spy = spyOn(console, 'error'); TestBed.configureTestingModule({declarations: [MyComp]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(spy.calls.mostRecent().args[0]).toMatch(/'custom' is not a known element/); }); it('should throw an error about unknown element without CUSTOM_ELEMENTS_SCHEMA for element without dash in tag name', () => { @Component({ template: `<custom></custom>`, standalone: false, }) class MyComp {} TestBed.configureTestingModule({declarations: [MyComp], errorOnUnknownElements: true}); expect(() => { const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); }).toThrowError(/NG0304: 'custom' is not a known element/g); }); it('s
{ "end_byte": 15909, "start_byte": 7043, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/ng_module_spec.ts" }
angular/packages/core/test/acceptance/ng_module_spec.ts_15915_22605
report unknown property bindings on ng-content', () => { @Component({ template: `<ng-content *unknownProp="123"></ng-content>`, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App]}); const spy = spyOn(console, 'error'); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(spy.calls.mostRecent()?.args[0]).toMatch( /Can't bind to 'unknownProp' since it isn't a known property of 'ng-content' \(used in the 'App' component template\)/, ); }); it('should throw an error on unknown property bindings on ng-content when errorOnUnknownProperties is enabled', () => { @Component({ template: `<ng-content *unknownProp="123"></ng-content>`, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App], errorOnUnknownProperties: true}); expect(() => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); }).toThrowError( /NG0303: Can't bind to 'unknownProp' since it isn't a known property of 'ng-content' \(used in the 'App' component template\)/g, ); }); it('should report unknown property bindings on ng-container', () => { @Component({ template: `<ng-container [unknown-prop]="123"></ng-container>`, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App]}); const spy = spyOn(console, 'error'); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(spy.calls.mostRecent()?.args[0]).toMatch( /Can't bind to 'unknown-prop' since it isn't a known property of 'ng-container' \(used in the 'App' component template\)/, ); }); it('should throw error on unknown property bindings on ng-container when errorOnUnknownProperties is enabled', () => { @Component({ template: `<ng-container [unknown-prop]="123"></ng-container>`, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App], errorOnUnknownProperties: true}); expect(() => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); }).toThrowError( /NG0303: Can't bind to 'unknown-prop' since it isn't a known property of 'ng-container' \(used in the 'App' component template\)/g, ); }); it('should log an error on unknown props and include a note on Web Components', () => { @Component({ selector: 'may-be-web-component', template: `...`, standalone: false, }) class MaybeWebComp {} @Component({ selector: 'my-comp', template: `<may-be-web-component [unknownProp]="condition"></may-be-web-component>`, standalone: false, }) class MyComp { condition = true; } @NgModule({ declarations: [MyComp, MaybeWebComp], }) class MyModule {} TestBed.configureTestingModule({imports: [MyModule]}); const spy = spyOn(console, 'error'); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); const errorMessage = spy.calls.mostRecent().args[0]; // Split the error message into chunks, so it's easier to debug if needed. const lines = [ `NG0303: Can't bind to 'unknownProp' since it isn't a known property of 'may-be-web-component' \\(used in the 'MyComp' component template\\).`, `1. If 'may-be-web-component' is an Angular component and it has the 'unknownProp' input, then verify that it is a part of an @NgModule where this component is declared.`, `2. If 'may-be-web-component' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`, `3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`, ]; lines.forEach((line) => expect(errorMessage).toMatch(line)); }); KNOWN_CONTROL_FLOW_DIRECTIVES.forEach((correspondingImport, directive) => { it( `should produce a warning when the '${directive}' directive ` + `is used in a template, but not imported in corresponding NgModule`, () => { @Component({ template: `<div *${directive}="expr"></div>`, standalone: false, }) class App { expr = true; } @NgModule({ declarations: [App], }) class Module {} TestBed.configureTestingModule({imports: [Module]}); const spy = spyOn(console, 'error'); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const errorMessage = spy.calls.mostRecent()?.args[0]; // Split the error message into chunks, so it's easier to debug if needed. const lines = [ `NG0303: Can't bind to '${directive}' since it isn't a known property of 'div' \\(used in the 'App' component template\\).`, `If the '${directive}' is an Angular control flow directive, please make sure ` + `that either the '${correspondingImport}' directive or the 'CommonModule' is a part of an @NgModule where this component is declared.`, ]; lines.forEach((line) => expect(errorMessage).toMatch(line)); }, ); it( `should produce a warning when the '${directive}' directive ` + `is used in a template, but not imported in a standalone component`, () => { @Component({ standalone: true, template: `<div *${directive}="expr"></div>`, }) class App { expr = true; } const spy = spyOn(console, 'error'); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const errorMessage = spy.calls.mostRecent()?.args[0]; // Split the error message into chunks, so it's easier to debug if needed. const lines = [ `NG0303: Can't bind to '${directive}' since it isn't a known property of 'div' \\(used in the 'App' component template\\).`, `If the '${directive}' is an Angular control flow directive, please make sure ` + `that either the '${correspondingImport}' directive or the 'CommonModule' is included in the '@Component.imports' of this component.`, ]; lines.forEach((line) => expect(errorMessage).toMatch(line)); }, ); }); descr
{ "end_byte": 22605, "start_byte": 15915, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/ng_module_spec.ts" }
angular/packages/core/test/acceptance/ng_module_spec.ts_22611_31100
OT-compiled components', () => { function createComponent( template: (rf: any) => void, vars: number, consts?: (number | string)[][], ) { class Comp { static ɵfac = () => new Comp(); static ɵcmp = defineComponent({ type: Comp, selectors: [['comp']], decls: 1, vars, consts, template, encapsulation: 2, }); } setClassMetadata( Comp, [ { type: Component, args: [{selector: 'comp', template: '...'}], }, ], null, null, ); return Comp; } function createNgModule(Comp: any) { class Module { static ɵmod = defineNgModule({type: Module}); static ɵinj = defineInjector({}); } setClassMetadata( Module, [ { type: NgModule, args: [ { declarations: [Comp], schemas: [NO_ERRORS_SCHEMA], }, ], }, ], null, null, ); return Module; } it('should not log unknown element warning for AOT-compiled components', () => { const spy = spyOn(console, 'warn'); /* * @Component({ * selector: 'comp', * template: '<custom-el></custom-el>', * }) * class MyComp {} */ const MyComp = createComponent((rf: any) => { if (rf & 1) { element(0, 'custom-el'); } }, 0); /* * @NgModule({ * declarations: [MyComp], * schemas: [NO_ERRORS_SCHEMA], * }) * class MyModule {} */ const MyModule = createNgModule(MyComp); TestBed.configureTestingModule({ imports: [MyModule], }); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(spy).not.toHaveBeenCalled(); }); it('should not log unknown property warning for AOT-compiled components', () => { const spy = spyOn(console, 'warn'); /* * @Component({ * selector: 'comp', * template: '<div [foo]="1"></div>', * }) * class MyComp {} */ const MyComp = createComponent( (rf: any) => { if (rf & 1) { element(0, 'div', 0); } if (rf & 2) { property('foo', true); } }, 1, [[3, 'foo']], ); /* * @NgModule({ * declarations: [MyComp], * schemas: [NO_ERRORS_SCHEMA], * }) * class MyModule {} */ const MyModule = createNgModule(MyComp); TestBed.configureTestingModule({ imports: [MyModule], }); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(spy).not.toHaveBeenCalled(); }); }); it('should not log an error about unknown elements with CUSTOM_ELEMENTS_SCHEMA', () => { @Component({ template: `<custom-el></custom-el>`, standalone: false, }) class MyComp {} const spy = spyOn(console, 'error'); TestBed.configureTestingModule({ declarations: [MyComp], schemas: [CUSTOM_ELEMENTS_SCHEMA], }); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(spy).not.toHaveBeenCalled(); }); it('should not throw an error about unknown elements with CUSTOM_ELEMENTS_SCHEMA', () => { @Component({ template: `<custom-el></custom-el>`, standalone: false, }) class MyComp {} const spy = spyOn(console, 'error'); TestBed.configureTestingModule({ declarations: [MyComp], schemas: [CUSTOM_ELEMENTS_SCHEMA], errorOnUnknownElements: true, }); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); // We do not expect any errors being thrown or logged in a console, // since the `CUSTOM_ELEMENTS_SCHEMA` is applied. expect(spy).not.toHaveBeenCalled(); }); it('should not log an error about unknown elements with NO_ERRORS_SCHEMA', () => { @Component({ template: `<custom-el></custom-el>`, standalone: false, }) class MyComp {} const spy = spyOn(console, 'error'); TestBed.configureTestingModule({ declarations: [MyComp], schemas: [NO_ERRORS_SCHEMA], }); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(spy).not.toHaveBeenCalled(); }); it('should not throw an error about unknown elements with NO_ERRORS_SCHEMA', () => { @Component({ template: `<custom-el></custom-el>`, standalone: false, }) class MyComp {} const spy = spyOn(console, 'error'); TestBed.configureTestingModule({ declarations: [MyComp], schemas: [NO_ERRORS_SCHEMA], errorOnUnknownElements: true, }); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); // We do not expect any errors being thrown or logged in a console, // since the `NO_ERRORS_SCHEMA` is applied. expect(spy).not.toHaveBeenCalled(); }); it('should not log an error about unknown elements if element matches a directive', () => { @Component({ selector: 'custom-el', template: '', standalone: false, }) class CustomEl {} @Component({ template: `<custom-el></custom-el>`, standalone: false, }) class MyComp {} const spy = spyOn(console, 'error'); TestBed.configureTestingModule({declarations: [MyComp, CustomEl]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(spy).not.toHaveBeenCalled(); }); it('should not throw an error about unknown elements if element matches a directive', () => { @Component({ selector: 'custom-el', template: '', standalone: false, }) class CustomEl {} @Component({ template: `<custom-el></custom-el>`, standalone: false, }) class MyComp {} const spy = spyOn(console, 'error'); TestBed.configureTestingModule({ declarations: [MyComp, CustomEl], errorOnUnknownElements: true, }); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); // We do not expect any errors being thrown or logged in a console, // since the element matches a directive. expect(spy).not.toHaveBeenCalled(); }); it('should not log an error for HTML elements inside an SVG foreignObject', () => { @Component({ template: ` <svg> <svg:foreignObject> <xhtml:div>Hello</xhtml:div> </svg:foreignObject> </svg> `, standalone: false, }) class MyComp {} @NgModule({declarations: [MyComp]}) class MyModule {} const spy = spyOn(console, 'error'); TestBed.configureTestingModule({imports: [MyModule]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(spy).not.toHaveBeenCalled(); }); it('should not throw an error for HTML elements inside an SVG foreignObject', () => { @Component({ template: ` <svg> <svg:foreignObject> <xhtml:div>Hello</xhtml:div> </svg:foreignObject> </svg> `, standalone: false, }) class MyComp {} @NgModule({declarations: [MyComp]}) class MyModule {} const spy = spyOn(console, 'error'); TestBed.configureTestingModule({imports: [MyModule], errorOnUnknownElements: true}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); // We do not expect any errors being thrown or logged in a console, // since the element is inside an SVG foreignObject. expect(spy).not.toHaveBeenCalled(); }); }); describe('c
{ "end_byte": 31100, "start_byte": 22611, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/ng_module_spec.ts" }
angular/packages/core/test/acceptance/ng_module_spec.ts_31104_33514
eNgModule function', () => { it('should create an NgModuleRef instance', () => { const TOKEN_A = new InjectionToken('A'); const TOKEN_B = new InjectionToken('B'); @NgModule({ providers: [{provide: TOKEN_A, useValue: 'TokenValueA'}], }) class AppModule {} @NgModule({ providers: [{provide: TOKEN_B, useValue: 'TokenValueB'}], }) class ChildModule {} // Simple case, just passing NgModule class. const ngModuleRef = createNgModule(AppModule); expect(ngModuleRef).toBeInstanceOf(NgModuleRef); expect(ngModuleRef.injector.get(TOKEN_A)).toBe('TokenValueA'); expect(ngModuleRef.injector.get(TOKEN_B, null)).toBe(null); // Both NgModule and parent Injector are present. const ngModuleRef2 = createNgModule(ChildModule, ngModuleRef.injector /* parent injector */); expect(ngModuleRef2).toBeInstanceOf(NgModuleRef); expect(ngModuleRef2.injector.get(TOKEN_A)).toBe('TokenValueA'); expect(ngModuleRef2.injector.get(TOKEN_B)).toBe('TokenValueB'); }); }); it('should be able to use DI through the NgModuleRef inside the module constructor', () => { const token = new InjectionToken<string>('token'); let value: string | undefined; @NgModule({ imports: [CommonModule], providers: [{provide: token, useValue: 'foo'}], }) class TestModule { constructor(ngRef: NgModuleRef<TestModule>) { value = ngRef.injector.get(token); } } TestBed.configureTestingModule({imports: [TestModule], declarations: [TestCmp]}); const fixture = TestBed.createComponent(TestCmp); fixture.detectChanges(); expect(value).toBe('foo'); }); it('should be able to create a component through the ComponentFactoryResolver of an NgModuleRef in a module constructor', () => { let componentInstance: TestCmp | undefined; @NgModule({ declarations: [TestCmp], exports: [TestCmp], }) class MyModule { constructor(ngModuleRef: NgModuleRef<any>) { const factory = ngModuleRef.componentFactoryResolver.resolveComponentFactory(TestCmp); componentInstance = factory.create(ngModuleRef.injector).instance; } } TestBed.configureTestingModule({imports: [MyModule]}); TestBed.createComponent(TestCmp); expect(componentInstance).toBeInstanceOf(TestCmp); }); });
{ "end_byte": 33514, "start_byte": 31104, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/ng_module_spec.ts" }
angular/packages/core/test/acceptance/view_insertion_spec.ts_0_8958
/** * @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, Directive, EmbeddedViewRef, Injectable, Injector, Input, TemplateRef, ViewChild, ViewContainerRef, ViewRef, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; describe('view insertion', () => { describe('of a simple template', () => { it('should insert into an empty container, at the front, in the middle, and at the end', () => { let _counter = 0; @Component({ selector: 'increment-comp', template: `<span>created{{counter}}</span>`, standalone: false, }) class IncrementComp { counter = _counter++; } @Component({ template: ` <ng-template #simple><increment-comp></increment-comp></ng-template> <div #container></div> `, standalone: false, }) class App { @ViewChild('container', {read: ViewContainerRef, static: true}) container: ViewContainerRef = null!; @ViewChild('simple', {read: TemplateRef, static: true}) simple: TemplateRef<any> = null!; view0: EmbeddedViewRef<any> = null!; view1: EmbeddedViewRef<any> = null!; view2: EmbeddedViewRef<any> = null!; view3: EmbeddedViewRef<any> = null!; constructor(public changeDetector: ChangeDetectorRef) {} ngAfterViewInit() { // insert at the front this.view1 = this.container.createEmbeddedView(this.simple); // "created0" // insert at the front again this.view0 = this.container.createEmbeddedView(this.simple, {}, 0); // "created1" // insert at the end this.view3 = this.container.createEmbeddedView(this.simple); // "created2" // insert in the middle this.view2 = this.container.createEmbeddedView(this.simple, {}, 2); // "created3" // We need to run change detection here to avoid // ExpressionChangedAfterItHasBeenCheckedError because of the value updating in // increment-comp this.changeDetector.detectChanges(); } } TestBed.configureTestingModule({ declarations: [App, IncrementComp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const app = fixture.componentInstance; expect(app.container.indexOf(app.view0)).toBe(0); expect(app.container.indexOf(app.view1)).toBe(1); expect(app.container.indexOf(app.view2)).toBe(2); expect(app.container.indexOf(app.view3)).toBe(3); // The text in each component differs based on *when* it was created. expect(fixture.nativeElement.textContent).toBe('created1created0created3created2'); }); }); describe('of an empty template', () => { it('should insert into an empty container, at the front, in the middle, and at the end', () => { @Component({ template: ` <ng-template #empty></ng-template> <div #container></div> `, standalone: false, }) class App { @ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef = null!; @ViewChild('empty', {read: TemplateRef}) empty: TemplateRef<any> = null!; view0: EmbeddedViewRef<any> = null!; view1: EmbeddedViewRef<any> = null!; view2: EmbeddedViewRef<any> = null!; view3: EmbeddedViewRef<any> = null!; ngAfterViewInit() { // insert at the front this.view1 = this.container.createEmbeddedView(this.empty); // insert at the front again this.view0 = this.container.createEmbeddedView(this.empty, {}, 0); // insert at the end this.view3 = this.container.createEmbeddedView(this.empty); // insert in the middle this.view2 = this.container.createEmbeddedView(this.empty, {}, 2); } } TestBed.configureTestingModule({ declarations: [App], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const app = fixture.componentInstance; expect(app.container.indexOf(app.view0)).toBe(0); expect(app.container.indexOf(app.view1)).toBe(1); expect(app.container.indexOf(app.view2)).toBe(2); expect(app.container.indexOf(app.view3)).toBe(3); }); }); describe('of an ng-content projection', () => { it('should insert into an empty container, at the front, in the middle, and at the end', () => { @Component({ selector: 'comp', template: ` <ng-template #projection><ng-content></ng-content></ng-template> <div #container></div> `, standalone: false, }) class Comp { @ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef = null!; @ViewChild('projection', {read: TemplateRef}) projection: TemplateRef<any> = null!; view0: EmbeddedViewRef<any> = null!; view1: EmbeddedViewRef<any> = null!; view2: EmbeddedViewRef<any> = null!; view3: EmbeddedViewRef<any> = null!; ngAfterViewInit() { // insert at the front this.view1 = this.container.createEmbeddedView(this.projection); // insert at the front again this.view0 = this.container.createEmbeddedView(this.projection, {}, 0); // insert at the end this.view3 = this.container.createEmbeddedView(this.projection); // insert in the middle this.view2 = this.container.createEmbeddedView(this.projection, {}, 2); } } @Component({ template: ` <comp>test</comp> `, standalone: false, }) class App {} TestBed.configureTestingModule({ declarations: [App, Comp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const comp = fixture.debugElement.query(By.directive(Comp)).injector.get(Comp); expect(comp.container.indexOf(comp.view0)).toBe(0); expect(comp.container.indexOf(comp.view1)).toBe(1); expect(comp.container.indexOf(comp.view2)).toBe(2); expect(comp.container.indexOf(comp.view3)).toBe(3); // Both ViewEngine and Ivy only honor one of the inserted ng-content components, even though // all are inserted. expect(fixture.nativeElement.textContent).toBe('test'); }); }); describe('of another container like ngIf', () => { it('should insert into an empty container, at the front, in the middle, and at the end', () => { @Component({ template: ` <ng-template #subContainer><div class="dynamic" *ngIf="true">test</div></ng-template> <div #container></div> `, standalone: false, }) class App { @ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef = null!; @ViewChild('subContainer', {read: TemplateRef}) subContainer: TemplateRef<any> = null!; view0: EmbeddedViewRef<any> = null!; view1: EmbeddedViewRef<any> = null!; view2: EmbeddedViewRef<any> = null!; view3: EmbeddedViewRef<any> = null!; constructor(public changeDetectorRef: ChangeDetectorRef) {} ngAfterViewInit() { // insert at the front this.view1 = this.container.createEmbeddedView(this.subContainer, null, 0); // insert at the front again this.view0 = this.container.createEmbeddedView(this.subContainer, null, 0); // insert at the end this.view3 = this.container.createEmbeddedView(this.subContainer, null, 2); // insert in the middle this.view2 = this.container.createEmbeddedView(this.subContainer, null, 2); // We need to run change detection here to avoid // ExpressionChangedAfterItHasBeenCheckedError because of the value getting passed to ngIf // in the template. this.changeDetectorRef.detectChanges(); } } TestBed.configureTestingModule({ declarations: [App], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const app = fixture.componentInstance; expect(app.container.indexOf(app.view0)).toBe(0); expect(app.container.indexOf(app.view1)).toBe(1); expect(app.container.indexOf(app.view2)).toBe(2); expect(app.container.indexOf(app.view3)).toBe(3); expect(fixture.debugElement.queryAll(By.css('div.dynamic')).length).toBe(4); }); });
{ "end_byte": 8958, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_insertion_spec.ts" }
angular/packages/core/test/acceptance/view_insertion_spec.ts_8962_17234
describe('before another view', () => { @Directive({ selector: '[viewInserting]', exportAs: 'vi', standalone: false, }) class ViewInsertingDir { constructor(private _vcRef: ViewContainerRef) {} insert(beforeView: ViewRef, insertTpl: TemplateRef<{}>) { this._vcRef.insert(beforeView, 0); this._vcRef.createEmbeddedView(insertTpl, {}, 0); } } describe('before embedded view', () => { @Component({ selector: 'test-cmpt', template: '', standalone: false, }) class TestCmpt { @ViewChild('before', {static: true}) beforeTpl!: TemplateRef<{}>; @ViewChild('insert', {static: true}) insertTpl!: TemplateRef<{}>; @ViewChild('vi', {static: true}) viewInsertingDir!: ViewInsertingDir; minutes = 10; insert() { const beforeView = this.beforeTpl.createEmbeddedView({}); // change-detect the "before view" to create all child views beforeView.detectChanges(); this.viewInsertingDir.insert(beforeView, this.insertTpl); } } beforeEach(() => { TestBed.configureTestingModule({ declarations: [TestCmpt, ViewInsertingDir], imports: [CommonModule], }); }); function createAndInsertViews(beforeTpl: string): any { TestBed.overrideTemplate( TestCmpt, ` <ng-template #insert>insert</ng-template> <ng-template #before>${beforeTpl}</ng-template> <div><ng-template #vi="vi" viewInserting></ng-template></div> `, ); const fixture = TestBed.createComponent(TestCmpt); fixture.detectChanges(); fixture.componentInstance.insert(); fixture.detectChanges(); return fixture.nativeElement; } it('should insert before a view with the text node as the first root node', () => { expect(createAndInsertViews('|before').textContent).toBe('insert|before'); }); it('should insert before a view with the element as the first root node', () => { expect(createAndInsertViews('<span>|before</span>').textContent).toBe('insert|before'); }); it('should insert before a view with the ng-container as the first root node', () => { expect( createAndInsertViews(` <ng-container> <ng-container>|before</ng-container> </ng-container> `).textContent, ).toBe('insert|before'); }); it('should insert before a view with the empty ng-container as the first root node', () => { expect(createAndInsertViews(`<ng-container></ng-container>|before`).textContent).toBe( 'insert|before', ); }); it('should insert before a view with ICU container inside a ng-container as the first root node', () => { expect( createAndInsertViews( `<ng-container i18n>{minutes, plural, =0 {just now} =1 {one minute ago} other {|before}}</ng-container>`, ).textContent, ).toBe('insert|before'); }); it('should insert before a view with a container as the first root node', () => { expect( createAndInsertViews(`<ng-template [ngIf]="true">|before</ng-template>`).textContent, ).toBe('insert|before'); }); it('should insert before a view with an empty container as the first root node', () => { expect( createAndInsertViews(`<ng-template [ngIf]="true"></ng-template>|before`).textContent, ).toBe('insert|before'); }); it('should insert before a view with a ng-container where ViewContainerRef is injected', () => { expect( createAndInsertViews(` <ng-container [ngTemplateOutlet]="after">|before</ng-container> <ng-template #after>|after</ng-template> `).textContent, ).toBe('insert|before|after'); }); it('should insert before a view with an element where ViewContainerRef is injected', () => { expect( createAndInsertViews(` <div [ngTemplateOutlet]="after">|before</div> <ng-template #after>|after</ng-template> `).textContent, ).toBe('insert|before|after'); }); it('should insert before a view with an empty projection as the first root node', () => { expect(createAndInsertViews(`<ng-content></ng-content>|before`).textContent).toBe( 'insert|before', ); }); it('should insert before a view with complex node structure', () => { expect( createAndInsertViews(` <ng-template [ngIf]="true"> <ng-container> <ng-container> <ng-template [ngIf]="true">|before</ng-template> </ng-container> </ng-container> </ng-template> `).textContent, ).toBe('insert|before'); }); it('should insert before a ng-container with a ViewContainerRef on it', () => { @Component({ selector: 'app-root', template: ` <div>start|</div> <ng-container [ngTemplateOutlet]="insertTpl ? tpl : null"></ng-container> <ng-container [ngTemplateOutlet]="tpl"></ng-container> <div>|end</div> <ng-template #tpl>test</ng-template> `, standalone: false, }) class AppComponent { insertTpl = false; } TestBed.configureTestingModule({ declarations: [AppComponent], imports: [CommonModule], }); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('start|test|end'); fixture.componentInstance.insertTpl = true; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('start|testtest|end'); }); }); describe('before embedded view with projection', () => { @Component({ selector: 'with-content', template: ` <ng-template #insert>insert</ng-template> <ng-template #before><ng-content></ng-content></ng-template> <div><ng-template #vi="vi" viewInserting></ng-template></div> `, standalone: false, }) class WithContentCmpt { @ViewChild('insert', {static: true}) insertTpl!: TemplateRef<{}>; @ViewChild('before', {static: true}) beforeTpl!: TemplateRef<{}>; @ViewChild('vi', {static: true}) viewInsertingDir!: ViewInsertingDir; insert() { const beforeView = this.beforeTpl.createEmbeddedView({}); // change-detect the "before view" to create all child views beforeView.detectChanges(); this.viewInsertingDir.insert(beforeView, this.insertTpl); } } @Component({ selector: 'test-cmpt', template: '', standalone: false, }) class TestCmpt { @ViewChild('wc', {static: true}) withContentCmpt!: WithContentCmpt; } beforeEach(() => { TestBed.configureTestingModule({ declarations: [ViewInsertingDir, WithContentCmpt, TestCmpt], imports: [CommonModule], }); }); it('should insert before a view with projected text nodes', () => { TestBed.overrideTemplate(TestCmpt, `<with-content #wc>|before</with-content>`); const fixture = TestBed.createComponent(TestCmpt); fixture.detectChanges(); fixture.componentInstance.withContentCmpt.insert(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('insert|before'); }); it('should insert before a view with projected container', () => { TestBed.overrideTemplate( TestCmpt, `<with-content #wc><ng-template [ngIf]="true">|before</ng-template></with-content>`, ); const fixture = TestBed.createComponent(TestCmpt); fixture.detectChanges(); fixture.componentInstance.withContentCmpt.insert(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('insert|before'); }); });
{ "end_byte": 17234, "start_byte": 8962, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_insertion_spec.ts" }
angular/packages/core/test/acceptance/view_insertion_spec.ts_17240_22904
describe('before component view', () => { @Directive({ selector: '[viewInserting]', exportAs: 'vi', standalone: false, }) class ViewInsertingDir { constructor(private _vcRef: ViewContainerRef) {} insert(beforeView: ViewRef, insertTpl: TemplateRef<{}>) { this._vcRef.insert(beforeView, 0); this._vcRef.createEmbeddedView(insertTpl, {}, 0); } } @Component({ selector: 'dynamic-cmpt', template: '|before', standalone: false, }) class DynamicComponent {} it('should insert in front a dynamic component view', () => { @Component({ selector: 'test-cmpt', template: ` <ng-template #insert>insert</ng-template> <div><ng-template #vi="vi" viewInserting></ng-template></div> `, standalone: false, }) class TestCmpt { @ViewChild('insert', {static: true}) insertTpl!: TemplateRef<{}>; @ViewChild('vi', {static: true}) viewInsertingDir!: ViewInsertingDir; constructor( private _vcr: ViewContainerRef, private _injector: Injector, ) {} insert() { // create a dynamic component view to act as an "insert before" view const beforeView = this._vcr.createComponent(DynamicComponent, { injector: this._injector, }).hostView; // change-detect the "before view" to create all child views beforeView.detectChanges(); this.viewInsertingDir.insert(beforeView, this.insertTpl); } } TestBed.configureTestingModule({ declarations: [TestCmpt, ViewInsertingDir, DynamicComponent], }); const fixture = TestBed.createComponent(TestCmpt); fixture.detectChanges(); fixture.componentInstance.insert(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('insert|before'); }); }); }); describe('non-regression', () => { // https://github.com/angular/angular/issues/31971 it('should insert component views into ViewContainerRef injected by querying <ng-container>', () => { @Component({ selector: 'dynamic-cmpt', template: 'dynamic', standalone: false, }) class DynamicComponent {} @Component({ selector: 'app-root', template: ` <div>start|</div> <ng-container #container></ng-container> <div>|end</div> <div (click)="click()" >|click</div> `, standalone: false, }) class AppComponent { @ViewChild('container', {read: ViewContainerRef, static: true}) vcr!: ViewContainerRef; click() { this.vcr.createComponent(DynamicComponent); } } TestBed.configureTestingModule({ declarations: [AppComponent, DynamicComponent], }); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('start||end|click'); fixture.componentInstance.click(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('start|dynamic|end|click'); }); // https://github.com/angular/angular/issues/33679 it('should insert embedded views into ViewContainerRef injected by querying <ng-container>', () => { @Component({ selector: 'app-root', template: ` <div>container start|</div> <ng-container #container></ng-container> <div>|container end</div> <ng-template #template >test</ng-template> <div (click)="click()" >|click</div> `, standalone: false, }) class AppComponent { @ViewChild('container', {read: ViewContainerRef, static: true}) vcr!: ViewContainerRef; @ViewChild('template', {read: TemplateRef, static: true}) template!: TemplateRef<any>; click() { this.vcr.createEmbeddedView(this.template, undefined, 0); } } TestBed.configureTestingModule({ declarations: [AppComponent], }); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('container start||container end|click'); fixture.componentInstance.click(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('container start|test|container end|click'); }); it('should properly insert before views in a ViewContainerRef injected on ng-container', () => { @Component({ selector: 'app-root', template: ` <ng-template #parameterListItem let-parameter="parameter"> {{parameter}} </ng-template> <ng-container *ngFor="let parameter of items;" [ngTemplateOutlet]="parameterListItem" [ngTemplateOutletContext]="{parameter:parameter}"> </ng-container> `, standalone: false, }) class AppComponent { items = [1]; } TestBed.configureTestingModule({ declarations: [AppComponent], imports: [CommonModule], }); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toContain('1'); fixture.componentInstance.items = [2, 1]; fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toContain('2 1'); }); });
{ "end_byte": 22904, "start_byte": 17240, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_insertion_spec.ts" }
angular/packages/core/test/acceptance/view_insertion_spec.ts_22908_30968
describe('create mode error handling', () => { it('should consistently report errors raised a directive constructor', () => { @Directive({ selector: '[failInConstructorAlways]', standalone: false, }) class FailInConstructorAlways { constructor() { throw new Error('Error in a constructor'); } } @Component({ template: `<div failInConstructorAlways></div>`, standalone: false, }) class TestCmpt {} TestBed.configureTestingModule({ declarations: [TestCmpt, FailInConstructorAlways], }); expect(() => { TestBed.createComponent(TestCmpt); }).toThrowError('Error in a constructor'); expect(() => { TestBed.createComponent(TestCmpt); }).toThrowError('Error in a constructor'); }); it('should render even if a directive constructor throws in the first create pass', () => { let firstRun = true; @Directive({ selector: '[failInConstructorOnce]', standalone: false, }) class FailInConstructorOnce { constructor() { if (firstRun) { firstRun = false; throw new Error('Error in a constructor'); } } } @Component({ template: `<div failInConstructorOnce>OK</div>`, standalone: false, }) class TestCmpt {} TestBed.configureTestingModule({ declarations: [TestCmpt, FailInConstructorOnce], }); expect(() => { TestBed.createComponent(TestCmpt); }).toThrowError('Error in a constructor'); const fixture = TestBed.createComponent(TestCmpt); expect(fixture.nativeElement.textContent).toContain('OK'); }); it('should consistently report errors raised a directive input setter', () => { @Directive({ selector: '[failInInputAlways]', standalone: false, }) class FailInInputAlways { @Input() set failInInputAlways(_: string) { throw new Error('Error in an input'); } } @Component({ template: `<div failInInputAlways="static"></div>`, standalone: false, }) class TestCmpt {} TestBed.configureTestingModule({ declarations: [TestCmpt, FailInInputAlways], }); expect(() => { TestBed.createComponent(TestCmpt); }).toThrowError('Error in an input'); expect(() => { TestBed.createComponent(TestCmpt); }).toThrowError('Error in an input'); }); it('should consistently report errors raised a static query setter', () => { @Directive({ selector: '[someDir]', standalone: false, }) class SomeDirective {} @Component({ template: `<div someDir></div>`, standalone: false, }) class TestCmpt { @ViewChild(SomeDirective, {static: true}) set directive(_: SomeDirective) { throw new Error('Error in static query setter'); } } TestBed.configureTestingModule({ declarations: [TestCmpt, SomeDirective], }); expect(() => { TestBed.createComponent(TestCmpt); }).toThrowError('Error in static query setter'); expect(() => { TestBed.createComponent(TestCmpt); }).toThrowError('Error in static query setter'); }); it('should match a static query, even if its setter throws in the first create pass', () => { let hasThrown = false; @Directive({ selector: '[someDir]', standalone: false, }) class SomeDirective {} @Component({ template: `<div someDir></div>`, standalone: false, }) class TestCmpt { @ViewChild(SomeDirective, {static: true}) get directive() { return this._directive; } set directive(directiveInstance: SomeDirective) { if (!hasThrown) { hasThrown = true; throw new Error('Error in static query setter'); } this._directive = directiveInstance; } private _directive!: SomeDirective; } TestBed.configureTestingModule({ declarations: [TestCmpt, SomeDirective], }); expect(() => { TestBed.createComponent(TestCmpt); }).toThrowError('Error in static query setter'); const fixture = TestBed.createComponent(TestCmpt); expect(fixture.componentInstance.directive).toBeInstanceOf(SomeDirective); }); it('should render a recursive component if it throws during the first creation pass', () => { let hasThrown = false; @Component({ selector: 'test', template: `<ng-content></ng-content>OK`, standalone: false, }) class TestCmpt { constructor() { if (!hasThrown) { hasThrown = true; throw new Error('Error in a constructor'); } } } @Component({ template: `<test><test><test></test></test></test>`, standalone: false, }) class App {} TestBed.configureTestingModule({ declarations: [App, TestCmpt], }); expect(() => { TestBed.createComponent(App); }).toThrowError('Error in a constructor'); const fixture = TestBed.createComponent(App); expect(fixture.nativeElement.textContent).toContain('OKOKOK'); }); it('should continue detecting changes if a directive throws in its constructor', () => { let firstRun = true; @Directive({ selector: '[failInConstructorOnce]', standalone: false, }) class FailInConstructorOnce { constructor() { if (firstRun) { firstRun = false; throw new Error('Error in a constructor'); } } } @Component({ template: `<div failInConstructorOnce>{{value}}</div>`, standalone: false, }) class TestCmpt { value = 0; } TestBed.configureTestingModule({ declarations: [TestCmpt, FailInConstructorOnce], }); expect(() => { TestBed.createComponent(TestCmpt); }).toThrowError('Error in a constructor'); const fixture = TestBed.createComponent(TestCmpt); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('0'); fixture.componentInstance.value = 1; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('1'); fixture.componentInstance.value = 2; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('2'); }); it('should consistently report errors raised by createEmbeddedView', () => { // Intentionally hasn't been added to `providers` so that it throws a DI error. @Injectable() class DoesNotExist {} @Directive({ selector: 'dir', standalone: false, }) class Dir { constructor(willCauseError: DoesNotExist) {} } @Component({ template: ` <ng-template #broken> <dir></dir> </ng-template> `, standalone: false, }) class App { @ViewChild('broken') template!: TemplateRef<unknown>; constructor(private _viewContainerRef: ViewContainerRef) {} insertTemplate() { this._viewContainerRef.createEmbeddedView(this.template); } } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); const tryRender = () => { fixture.componentInstance.insertTemplate(); fixture.detectChanges(); }; fixture.detectChanges(); // We try to render the same template twice to ensure that we get consistent error messages. expect(tryRender).toThrowError(/No provider for DoesNotExist/); expect(tryRender).toThrowError(/No provider for DoesNotExist/); }); }); });
{ "end_byte": 30968, "start_byte": 22908, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/view_insertion_spec.ts" }
angular/packages/core/test/acceptance/component_spec.ts_0_8975
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {DOCUMENT, NgIf} from '@angular/common'; import { ApplicationRef, Component, ComponentRef, createComponent, createEnvironmentInjector, Directive, ElementRef, EmbeddedViewRef, EnvironmentInjector, forwardRef, inject, Injectable, InjectionToken, Injector, input, Input, NgModule, OnDestroy, reflectComponentType, Renderer2, Type, ViewChild, ViewContainerRef, ViewEncapsulation, ɵsetClassDebugInfo, ɵsetDocument, ɵɵdefineComponent, } from '@angular/core'; import {stringifyForError} from '@angular/core/src/render3/util/stringify_utils'; import {TestBed} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/src/matchers'; import {global} from '../../src/util/global'; describe('component', () => { describe('view destruction', () => { it('should invoke onDestroy only once when a component is registered as a provider', () => { const testToken = new InjectionToken<ParentWithOnDestroy>('testToken'); let destroyCalls = 0; @Component({ selector: 'comp-with-on-destroy', template: '', providers: [{provide: testToken, useExisting: ParentWithOnDestroy}], standalone: false, }) class ParentWithOnDestroy { ngOnDestroy() { destroyCalls++; } } @Component({ selector: 'child', template: '', standalone: false, }) class ChildComponent { // We need to inject the parent so the provider is instantiated. constructor(_parent: ParentWithOnDestroy) {} } @Component({ template: ` <comp-with-on-destroy> <child></child> </comp-with-on-destroy> `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, ParentWithOnDestroy, ChildComponent]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(destroyCalls).toBe(1, 'Expected `ngOnDestroy` to only be called once.'); }); }); it('should be able to dynamically insert a component into a view container at the root of a component', () => { @Component({ template: 'hello', standalone: false, }) class HelloComponent {} @Component({ selector: 'wrapper', template: '<ng-content></ng-content>', standalone: false, }) class Wrapper {} @Component({ template: ` <wrapper> <div #insertionPoint></div> </wrapper> `, standalone: false, }) class App { @ViewChild('insertionPoint', {read: ViewContainerRef}) viewContainerRef!: ViewContainerRef; } TestBed.configureTestingModule({declarations: [App, Wrapper, HelloComponent]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const instance = fixture.componentInstance; instance.viewContainerRef.createComponent(HelloComponent); expect(fixture.nativeElement.textContent.trim()).toBe('hello'); }); it('should not throw when calling `detectChanges` on the ChangeDetectorRef of a destroyed view', () => { @Component({ template: 'hello', standalone: false, }) class HelloComponent {} @Component({ template: `<div #insertionPoint></div>`, standalone: false, }) class App { @ViewChild('insertionPoint', {read: ViewContainerRef}) viewContainerRef!: ViewContainerRef; } TestBed.configureTestingModule({declarations: [App, HelloComponent]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const componentRef = fixture.componentInstance.viewContainerRef.createComponent(HelloComponent); fixture.detectChanges(); expect(() => { componentRef.destroy(); componentRef.changeDetectorRef.detectChanges(); }).not.toThrow(); }); // TODO: add tests with Native once tests run in real browser (domino doesn't support shadow root) describe('encapsulation', () => { @Component({ selector: 'wrapper', encapsulation: ViewEncapsulation.None, template: `<encapsulated></encapsulated>`, standalone: false, }) class WrapperComponent {} @Component({ selector: 'encapsulated', encapsulation: ViewEncapsulation.Emulated, // styles must be non-empty to trigger `ViewEncapsulation.Emulated` styles: `:host {display: block}`, template: `foo<leaf></leaf>`, standalone: false, }) class EncapsulatedComponent {} @Component({ selector: 'leaf', encapsulation: ViewEncapsulation.None, template: `<span>bar</span>`, standalone: false, }) class LeafComponent {} beforeEach(() => { TestBed.configureTestingModule({ declarations: [WrapperComponent, EncapsulatedComponent, LeafComponent], }); }); it('should encapsulate children, but not host nor grand children', () => { const fixture = TestBed.createComponent(WrapperComponent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toMatch( /<encapsulated _nghost-[a-z\-]+(\d+)="">foo<leaf _ngcontent-[a-z\-]+\1=""><span>bar<\/span><\/leaf><\/encapsulated>/, ); }); it('should encapsulate host', () => { const fixture = TestBed.createComponent(EncapsulatedComponent); fixture.detectChanges(); const html = fixture.nativeElement.outerHTML; const match = html.match(/_nghost-([a-z\-]+\d+)/); expect(match).toBeDefined(); expect(html).toMatch(new RegExp(`<leaf _ngcontent-${match[1]}=""><span>bar</span></leaf>`)); }); it('should encapsulate host and children with different attributes', () => { // styles must be non-empty to trigger `ViewEncapsulation.Emulated` TestBed.overrideComponent(LeafComponent, { set: {encapsulation: ViewEncapsulation.Emulated, styles: [`span {color:red}`]}, }); const fixture = TestBed.createComponent(EncapsulatedComponent); fixture.detectChanges(); const html = fixture.nativeElement.outerHTML; const match = html.match(/_nghost-([a-z\-]+\d+)/g); expect(match).toBeDefined(); expect(match.length).toEqual(2); expect(html).toMatch( `<leaf ${match[0].replace('_nghost', '_ngcontent')}="" ${ match[1] }=""><span ${match[1].replace('_nghost', '_ngcontent')}="">bar</span></leaf></div>`, ); }); it('should be off for a component with no styles', () => { TestBed.overrideComponent(EncapsulatedComponent, { set: {styles: undefined}, }); const fixture = TestBed.createComponent(EncapsulatedComponent); fixture.detectChanges(); const html = fixture.nativeElement.outerHTML; expect(html).not.toContain('<encapsulated _nghost-'); expect(html).not.toContain('<leaf _ngcontent-'); }); it('should be off for a component with empty styles', () => { TestBed.overrideComponent(EncapsulatedComponent, { set: {styles: [` `, '', '/*comment*/']}, }); const fixture = TestBed.createComponent(EncapsulatedComponent); fixture.detectChanges(); const html = fixture.nativeElement.outerHTML; expect(html).not.toContain('<encapsulated _nghost-'); expect(html).not.toContain('<leaf _ngcontent-'); }); }); describe('view destruction', () => { it('should invoke onDestroy when directly destroying a root view', () => { let wasOnDestroyCalled = false; @Component({ selector: 'comp-with-destroy', template: ``, standalone: false, }) class ComponentWithOnDestroy implements OnDestroy { ngOnDestroy() { wasOnDestroyCalled = true; } } // This test asserts that the view tree is set up correctly based on the knowledge that this // tree is used during view destruction. If the child view is not correctly attached as a // child of the root view, then the onDestroy hook on the child view will never be called // when the view tree is torn down following the destruction of that root view. @Component({ selector: `test-app`, template: `<comp-with-destroy></comp-with-destroy>`, standalone: false, }) class TestApp {} TestBed.configureTestingModule({declarations: [ComponentWithOnDestroy, TestApp]}); const fixture = TestBed.createComponent(TestApp); fixture.detectChanges(); fixture.destroy(); expect(wasOnDestroyCalled).toBe( true, 'Expected component onDestroy method to be called when its parent view is destroyed', ); }); });
{ "end_byte": 8975, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/component_spec.ts" }
angular/packages/core/test/acceptance/component_spec.ts_8979_17069
should clear the contents of dynamically created component when it's attached to ApplicationRef", () => { let wasOnDestroyCalled = false; @Component({ selector: '[comp]', template: 'comp content', standalone: false, }) class DynamicComponent { ngOnDestroy() { wasOnDestroyCalled = true; } } @Component({ selector: 'button', template: ` <div class="wrapper"></div> <div id="app-root"></div> <div class="wrapper"></div> `, standalone: false, }) class App { componentRef!: ComponentRef<DynamicComponent>; constructor( private injector: EnvironmentInjector, private appRef: ApplicationRef, private elementRef: ElementRef, ) {} create() { // Component to be bootstrapped into an element with the `app-root` id. this.componentRef = createComponent(DynamicComponent, { environmentInjector: this.injector, hostElement: this.elementRef.nativeElement.querySelector('#app-root')!, }); this.appRef.attachView(this.componentRef.hostView); } destroy() { this.componentRef.destroy(); } } TestBed.configureTestingModule({declarations: [App, DynamicComponent]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); let appRootEl = fixture.nativeElement.querySelector('#app-root'); expect(appRootEl).toBeDefined(); expect(appRootEl.innerHTML).toBe(''); // app container content is empty fixture.componentInstance.create(); appRootEl = fixture.nativeElement.querySelector('#app-root'); expect(appRootEl).toBeDefined(); expect(appRootEl.innerHTML).toBe('comp content'); fixture.componentInstance.destroy(); fixture.detectChanges(); appRootEl = fixture.nativeElement.querySelector('#app-root'); expect(appRootEl).toBeFalsy(); // host element is removed const wrapperEls = fixture.nativeElement.querySelectorAll('.wrapper'); expect(wrapperEls.length).toBe(2); // other elements are preserved }); describe('with ngDevMode', () => { const _global: {ngDevMode: any} = global; let saveNgDevMode!: typeof ngDevMode; beforeEach(() => (saveNgDevMode = ngDevMode)); afterEach(() => (_global.ngDevMode = saveNgDevMode)); // In dev mode we have some additional logic to freeze `TView.cleanup` array // (see `storeCleanupWithContext` function). // The tests below verify that this action doesn't trigger any change in behaviour // for prod mode. See https://github.com/angular/angular/issues/40105. ['ngDevMode off', 'ngDevMode on'].forEach((mode) => { it( 'should invoke `onDestroy` callbacks of dynamically created component with ' + mode, () => { if (mode === 'ngDevMode off') { _global.ngDevMode = false; } let wasOnDestroyCalled = false; @Component({ selector: '[comp]', template: 'comp content', standalone: false, }) class DynamicComponent {} @Component({ selector: 'button', template: '<div id="app-root" #anchor></div>', standalone: false, }) class App { @ViewChild('anchor', {read: ViewContainerRef}) anchor!: ViewContainerRef; constructor( private vcr: ViewContainerRef, private injector: Injector, ) {} create() { const componentRef = this.vcr.createComponent(DynamicComponent, { injector: this.injector, }); componentRef.onDestroy(() => { wasOnDestroyCalled = true; }); this.anchor.insert(componentRef.hostView); } clear() { this.anchor.clear(); } } TestBed.configureTestingModule({declarations: [App, DynamicComponent]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); // Add ComponentRef to ViewContainerRef instance. fixture.componentInstance.create(); // Clear ViewContainerRef to invoke `onDestroy` callbacks on ComponentRef. fixture.componentInstance.clear(); expect(wasOnDestroyCalled).toBeTrue(); }, ); }); }); describe('invalid host element', () => { it('should throw when <ng-container> is used as a host element for a Component', () => { @Component({ selector: 'ng-container', template: '...', standalone: false, }) class Comp {} @Component({ selector: 'root', template: '<ng-container></ng-container>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Comp]}); expect(() => TestBed.createComponent(App)).toThrowError( /"ng-container" tags cannot be used as component hosts. Please use a different tag to activate the Comp component/, ); }); it('should throw when <ng-template> is used as a host element for a Component', () => { @Component({ selector: 'ng-template', template: '...', standalone: false, }) class Comp {} @Component({ selector: 'root', template: '<ng-template></ng-template>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Comp]}); expect(() => TestBed.createComponent(App)).toThrowError( /"ng-template" tags cannot be used as component hosts. Please use a different tag to activate the Comp component/, ); }); it('should throw when multiple components match the same element', () => { @Component({ selector: 'comp', template: '...', standalone: false, }) class CompA {} @Component({ selector: 'comp', template: '...', standalone: false, }) class CompB {} @Component({ template: '<comp></comp>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, CompA, CompB]}); expect(() => TestBed.createComponent(App)).toThrowError( /NG0300: Multiple components match node with tagname comp: CompA and CompB/, ); }); it('should not throw if a standalone component imports itself', () => { @Component({ selector: 'comp', template: '<comp *ngIf="recurse"/>hello', standalone: true, imports: [Comp, NgIf], }) class Comp { @Input() recurse = false; } @Component({ template: '<comp [recurse]="true"/>', standalone: true, imports: [Comp], }) class App {} let textContent = ''; expect(() => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); textContent = fixture.nativeElement.textContent.trim(); }).not.toThrow(); // Ensure that the component actually rendered. expect(textContent).toBe('hellohello'); }); it('should not throw if a standalone component imports itself using a forwardRef', () => { @Component({ selector: 'comp', template: '<comp *ngIf="recurse"/>hello', standalone: true, imports: [forwardRef(() => Comp), NgIf], }) class Comp { @Input() recurse = false; } @Component({ template: '<comp [recurse]="true"/>', standalone: true, imports: [Comp], }) class App {} let textContent = ''; expect(() => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); textContent = fixture.nativeElement.textContent.trim(); }).not.toThrow(); // Ensure that the component actually rendered. expect(textContent).toBe('hellohello'); }); });
{ "end_byte": 17069, "start_byte": 8979, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/component_spec.ts" }
angular/packages/core/test/acceptance/component_spec.ts_17073_24793
should use a new ngcontent attribute for child elements created w/ Renderer2', () => { @Component({ selector: 'app-root', template: '<parent-comp></parent-comp>', styles: [':host { color: red; }'], // `styles` must exist for encapsulation to apply. encapsulation: ViewEncapsulation.Emulated, standalone: false, }) class AppRoot {} @Component({ selector: 'parent-comp', template: '', styles: [':host { color: orange; }'], // `styles` must exist for encapsulation to apply. encapsulation: ViewEncapsulation.Emulated, standalone: false, }) class ParentComponent { constructor(elementRef: ElementRef, renderer: Renderer2) { const elementFromRenderer = renderer.createElement('p'); renderer.appendChild(elementRef.nativeElement, elementFromRenderer); } } TestBed.configureTestingModule({declarations: [AppRoot, ParentComponent]}); const fixture = TestBed.createComponent(AppRoot); fixture.detectChanges(); const secondParentEl: HTMLElement = fixture.nativeElement.querySelector('parent-comp'); const elementFromRenderer: HTMLElement = fixture.nativeElement.querySelector('p'); const getNgContentAttr = (element: HTMLElement) => { return Array.from(element.attributes) .map((a) => a.name) .find((a) => /ngcontent/.test(a)); }; const hostNgContentAttr = getNgContentAttr(secondParentEl); const viewNgContentAttr = getNgContentAttr(elementFromRenderer); expect(hostNgContentAttr).not.toBe( viewNgContentAttr, 'Expected child manually created via Renderer2 to have a different view encapsulation' + 'attribute than its host element', ); }); it('should create a new Renderer2 for each component', () => { @Component({ selector: 'child', template: '', styles: [':host { color: red; }'], encapsulation: ViewEncapsulation.Emulated, standalone: false, }) class Child { constructor(public renderer: Renderer2) {} } @Component({ template: '<child></child>', styles: [':host { color: orange; }'], encapsulation: ViewEncapsulation.Emulated, standalone: false, }) class Parent { @ViewChild(Child) childInstance!: Child; constructor(public renderer: Renderer2) {} } TestBed.configureTestingModule({declarations: [Parent, Child]}); const fixture = TestBed.createComponent(Parent); const componentInstance = fixture.componentInstance; fixture.detectChanges(); // Assert like this, rather than `.not.toBe` so we get a better failure message. expect(componentInstance.renderer !== componentInstance.childInstance.renderer).toBe( true, 'Expected renderers to be different.', ); }); it('components should not share the same context when creating with a root element', () => { const log: string[] = []; @Component({ selector: 'comp-a', template: '<div>{{ a }}</div>', standalone: false, }) class CompA { @Input() a: string = ''; ngDoCheck() { log.push('CompA:ngDoCheck'); } } @Component({ selector: 'comp-b', template: '<div>{{ b }}</div>', standalone: false, }) class CompB { @Input() b: string = ''; ngDoCheck() { log.push('CompB:ngDoCheck'); } } @Component({ template: `<span></span>`, standalone: false, }) class MyCompA { constructor(private _injector: EnvironmentInjector) {} createComponent() { return createComponent(CompA, { environmentInjector: this._injector, hostElement: document.createElement('div'), }); } } @Component({ template: `<span></span>`, standalone: false, }) class MyCompB { constructor(private envInjector: EnvironmentInjector) {} createComponent() { return createComponent(CompB, { environmentInjector: this.envInjector, hostElement: document.createElement('div'), }); } } @NgModule({declarations: [CompA]}) class MyModuleA {} @NgModule({declarations: [CompB]}) class MyModuleB {} TestBed.configureTestingModule({ declarations: [MyCompA, MyCompB], imports: [MyModuleA, MyModuleB], }); const fixtureA = TestBed.createComponent(MyCompA); fixtureA.detectChanges(); const compA = fixtureA.componentInstance.createComponent(); compA.instance.a = 'a'; compA.changeDetectorRef.detectChanges(); expect(log).toEqual(['CompA:ngDoCheck']); log.length = 0; // reset the log const fixtureB = TestBed.createComponent(MyCompB); fixtureB.detectChanges(); const compB = fixtureB.componentInstance.createComponent(); compB.instance.b = 'b'; compB.changeDetectorRef.detectChanges(); expect(log).toEqual(['CompB:ngDoCheck']); }); it('should preserve simple component selector in a component factory', () => { @Component({ selector: '[foo]', template: '', standalone: false, }) class AttSelectorCmp {} const selector = reflectComponentType(AttSelectorCmp)?.selector; expect(selector).toBe('[foo]'); }); it('should preserve complex component selector in a component factory', () => { @Component({ selector: '[foo],div:not(.bar)', template: '', standalone: false, }) class ComplexSelectorCmp {} const selector = reflectComponentType(ComplexSelectorCmp)?.selector; expect(selector).toBe('[foo],div:not(.bar)'); }); it('should clear host element if provided in ComponentFactory.create', () => { @Component({ selector: 'dynamic-comp', template: 'DynamicComponent Content', standalone: false, }) class DynamicComponent {} @Component({ selector: 'app', template: ` <div id="dynamic-comp-root-a"> Existing content in slot A, which <b><i>includes</i> some HTML elements</b>. </div> <div id="dynamic-comp-root-b"> <p> Existing content in slot B, which includes some HTML elements. </p> </div> `, standalone: false, }) class App { constructor(public injector: EnvironmentInjector) {} createDynamicComponent(target: any) { createComponent(DynamicComponent, { hostElement: target, environmentInjector: this.injector, }); } } function _document(): any { // Tell Ivy about the global document ɵsetDocument(document); return document; } TestBed.configureTestingModule({ declarations: [App, DynamicComponent], providers: [{provide: DOCUMENT, useFactory: _document, deps: []}], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); // Create an instance of DynamicComponent and provide host element *reference* let targetEl = document.getElementById('dynamic-comp-root-a')!; fixture.componentInstance.createDynamicComponent(targetEl); fixture.detectChanges(); expect(targetEl.innerHTML).not.toContain('Existing content in slot A'); expect(targetEl.innerHTML).toContain('DynamicComponent Content'); // Create an instance of DynamicComponent and provide host element *selector* targetEl = document.getElementById('dynamic-comp-root-b')!; fixture.componentInstance.createDynamicComponent('#dynamic-comp-root-b'); fixture.detectChanges(); expect(targetEl.innerHTML).not.toContain('Existing content in slot B'); expect(targetEl.innerHTML).toContain('DynamicComponent Content'); }); d
{ "end_byte": 24793, "start_byte": 17073, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/component_spec.ts" }
angular/packages/core/test/acceptance/component_spec.ts_24797_33147
ibe('createComponent', () => { it('should create an instance of a standalone component', () => { @Component({ standalone: true, template: 'Hello {{ name }}!', }) class StandaloneComponent { name = 'Angular'; } const hostElement = document.createElement('div'); const environmentInjector = TestBed.inject(EnvironmentInjector); const componentRef = createComponent(StandaloneComponent, {hostElement, environmentInjector}); componentRef.changeDetectorRef.detectChanges(); expect(hostElement.textContent).toBe('Hello Angular!'); // Verify basic change detection works. componentRef.instance.name = 'ZoneJS'; componentRef.changeDetectorRef.detectChanges(); expect(hostElement.textContent).toBe('Hello ZoneJS!'); componentRef.destroy(); }); it('should create an instance of an NgModule-based component', () => { @Component({ template: 'Hello {{ name }}!', standalone: false, }) class NgModuleBasedComponent { name = 'Angular'; } @NgModule({ declarations: [NgModuleBasedComponent], }) class AppModule {} const hostElement = document.createElement('div'); const environmentInjector = TestBed.inject(EnvironmentInjector); const componentRef = createComponent(NgModuleBasedComponent, { hostElement, environmentInjector, }); componentRef.changeDetectorRef.detectChanges(); expect(hostElement.textContent).toBe('Hello Angular!'); // Verify basic change detection works. componentRef.instance.name = 'ZoneJS'; componentRef.changeDetectorRef.detectChanges(); expect(hostElement.textContent).toBe('Hello ZoneJS!'); }); it('should render projected content', () => { @Component({ standalone: true, template: ` <ng-content></ng-content>| <ng-content></ng-content>| <ng-content></ng-content> `, }) class StandaloneComponent {} // Helper method to create a `<p>` element const p = (content: string): Element => { const element = document.createElement('p'); element.innerHTML = content; return element; }; const hostElement = document.createElement('div'); const environmentInjector = TestBed.inject(EnvironmentInjector); const projectableNodes = [[p('1')], [p('2')], [p('3')]]; const componentRef = createComponent(StandaloneComponent, { hostElement, environmentInjector, projectableNodes, }); componentRef.changeDetectorRef.detectChanges(); expect(hostElement.innerHTML.replace(/\s*/g, '')).toBe('<p>1</p>|<p>2</p>|<p>3</p>'); componentRef.destroy(); }); it('should be able to inject tokens from EnvironmentInjector', () => { const A = new InjectionToken('A'); @Component({ standalone: true, template: 'Token: {{ a }}', }) class StandaloneComponent { a = inject(A); } const hostElement = document.createElement('div'); const parentInjector = TestBed.inject(EnvironmentInjector); const providers = [{provide: A, useValue: 'EnvironmentInjector(A)'}]; const environmentInjector = createEnvironmentInjector(providers, parentInjector); const componentRef = createComponent(StandaloneComponent, {hostElement, environmentInjector}); componentRef.changeDetectorRef.detectChanges(); expect(hostElement.textContent).toBe('Token: EnvironmentInjector(A)'); componentRef.destroy(); }); it('should be able to use NodeInjector from the node hierarchy', () => { const A = new InjectionToken('A'); const B = new InjectionToken('B'); @Component({ standalone: true, template: '{{ a }} and {{ b }}', }) class ChildStandaloneComponent { a = inject(A); b = inject(B); } @Component({ standalone: true, template: 'Tokens: <div #target></div>', providers: [{provide: A, useValue: 'ElementInjector(A)'}], }) class RootStandaloneComponent { @ViewChild('target', {read: ElementRef}) target!: ElementRef; constructor(private injector: Injector) {} createChildComponent() { const hostElement = this.target.nativeElement; const parentInjector = this.injector.get(EnvironmentInjector); const providers = [ {provide: A, useValue: 'EnvironmentInjector(A)'}, {provide: B, useValue: 'EnvironmentInjector(B)'}, ]; const environmentInjector = createEnvironmentInjector(providers, parentInjector); const childComponentRef = createComponent(ChildStandaloneComponent, { hostElement, elementInjector: this.injector, environmentInjector, }); childComponentRef.changeDetectorRef.detectChanges(); } } const fixture = TestBed.createComponent(RootStandaloneComponent); fixture.detectChanges(); fixture.componentInstance.createChildComponent(); const rootEl = fixture.nativeElement; // Token A is coming from the Element Injector, token B - from the Environment Injector. expect(rootEl.textContent).toBe('Tokens: ElementInjector(A) and EnvironmentInjector(B)'); }); it('should create a host element if none provided', () => { const selector = 'standalone-comp'; @Component({ selector, standalone: true, template: 'Hello {{ name }}!', }) class StandaloneComponent { name = 'Angular'; } const environmentInjector = TestBed.inject(EnvironmentInjector); const componentRef = createComponent(StandaloneComponent, {environmentInjector}); componentRef.changeDetectorRef.detectChanges(); const hostElement = (componentRef.hostView as EmbeddedViewRef<StandaloneComponent>) .rootNodes[0]; // A host element that matches component's selector. expect(hostElement.tagName.toLowerCase()).toBe(selector); expect(hostElement.textContent).toBe('Hello Angular!'); componentRef.destroy(); }); it( 'should fall-back to use a `div` as a host element if none provided ' + 'and element selector does not have a tag name', () => { @Component({ selector: '.some-class', standalone: true, template: 'Hello {{ name }}!', }) class StandaloneComponent { name = 'Angular'; } const environmentInjector = TestBed.inject(EnvironmentInjector); const componentRef = createComponent(StandaloneComponent, {environmentInjector}); componentRef.changeDetectorRef.detectChanges(); const hostElement = (componentRef.hostView as EmbeddedViewRef<StandaloneComponent>) .rootNodes[0]; // A host element has the `div` tag name, since component's selector doesn't contain // tag name information (only a class name). expect(hostElement.tagName.toLowerCase()).toBe('div'); expect(hostElement.textContent).toBe('Hello Angular!'); componentRef.destroy(); }, ); describe('error checking', () => { it('should throw when provided class is not a component', () => { class NotAComponent {} @Directive() class ADirective {} @Injectable() class AnInjectiable {} const errorFor = (type: Type<unknown>): string => `NG0906: The ${stringifyForError(type)} is not an Angular component, ` + `make sure it has the \`@Component\` decorator.`; const hostElement = document.createElement('div'); const environmentInjector = TestBed.inject(EnvironmentInjector); expect(() => createComponent(NotAComponent, {hostElement, environmentInjector}), ).toThrowError(errorFor(NotAComponent)); expect(() => createComponent(ADirective, {hostElement, environmentInjector})).toThrowError( errorFor(ADirective), ); expect(() => createComponent(AnInjectiable, {hostElement, environmentInjector}), ).toThrowError(errorFor(AnInjectiable)); }); }); }); d
{ "end_byte": 33147, "start_byte": 24797, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/component_spec.ts" }
angular/packages/core/test/acceptance/component_spec.ts_33151_37498
ibe('reflectComponentType', () => { it('should create an ComponentMirror for a standalone component', () => { function transformFn() {} @Component({ selector: 'standalone-component', standalone: true, template: ` <ng-content></ng-content> <ng-content select="content-selector-a"></ng-content> <ng-content select="content-selector-b"></ng-content> <ng-content></ng-content> `, inputs: ['input-a', 'input-b:input-alias-b'], outputs: ['output-a', 'output-b:output-alias-b'], }) class StandaloneComponent { @Input({alias: 'input-alias-c', transform: transformFn}) inputC: unknown; @Input({isSignal: true} as Input) inputD = input(false); } const mirror = reflectComponentType(StandaloneComponent)!; expect(mirror.selector).toBe('standalone-component'); expect(mirror.type).toBe(StandaloneComponent); expect(mirror.isStandalone).toEqual(true); expect(mirror.inputs).toEqual([ {propName: 'input-a', templateName: 'input-a', isSignal: false}, {propName: 'input-b', templateName: 'input-alias-b', isSignal: false}, { propName: 'inputC', templateName: 'input-alias-c', transform: transformFn, isSignal: false, }, {propName: 'inputD', templateName: 'inputD', isSignal: true}, ]); expect(mirror.outputs).toEqual([ {propName: 'output-a', templateName: 'output-a'}, {propName: 'output-b', templateName: 'output-alias-b'}, ]); expect(mirror.ngContentSelectors).toEqual([ '*', 'content-selector-a', 'content-selector-b', '*', ]); }); it('should create an ComponentMirror for a non-standalone component', () => { function transformFn() {} @Component({ selector: 'non-standalone-component', template: ` <ng-content></ng-content> <ng-content select="content-selector-a"></ng-content> <ng-content select="content-selector-b"></ng-content> <ng-content></ng-content> `, inputs: ['input-a', 'input-b:input-alias-b'], outputs: ['output-a', 'output-b:output-alias-b'], standalone: false, }) class NonStandaloneComponent { @Input({alias: 'input-alias-c', transform: transformFn}) inputC: unknown; } const mirror = reflectComponentType(NonStandaloneComponent)!; expect(mirror.selector).toBe('non-standalone-component'); expect(mirror.type).toBe(NonStandaloneComponent); expect(mirror.isStandalone).toEqual(false); expect(mirror.inputs).toEqual([ {propName: 'input-a', templateName: 'input-a', isSignal: false}, {propName: 'input-b', templateName: 'input-alias-b', isSignal: false}, { propName: 'inputC', templateName: 'input-alias-c', transform: transformFn, isSignal: false, }, ]); expect(mirror.outputs).toEqual([ {propName: 'output-a', templateName: 'output-a'}, {propName: 'output-b', templateName: 'output-alias-b'}, ]); expect(mirror.ngContentSelectors).toEqual([ '*', 'content-selector-a', 'content-selector-b', '*', ]); }); describe('error checking', () => { it('should throw when provided class is not a component', () => { class NotAnnotated {} @Directive() class ADirective {} @Injectable() class AnInjectiable {} expect(reflectComponentType(NotAnnotated)).toBe(null); expect(reflectComponentType(ADirective)).toBe(null); expect(reflectComponentType(AnInjectiable)).toBe(null); }); }); }); it('should attach debug info to component using ɵsetClassDebugInfo runtime', () => { class Comp { static ɵcmp = ɵɵdefineComponent({type: Comp, decls: 0, vars: 0, template: () => ''}); } ɵsetClassDebugInfo(Comp, { className: 'Comp', filePath: 'comp.ts', lineNumber: 11, forbidOrphanRendering: true, }); expect(Comp.ɵcmp.debugInfo).toEqual({ className: 'Comp', filePath: 'comp.ts', lineNumber: 11, forbidOrphanRendering: true, }); }); });
{ "end_byte": 37498, "start_byte": 33151, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/component_spec.ts" }
angular/packages/core/test/acceptance/integration_spec.ts_0_3164
/** * @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 {animate, AnimationEvent, state, style, transition, trigger} from '@angular/animations'; import {AnimationDriver} from '@angular/animations/browser'; import {MockAnimationDriver, MockAnimationPlayer} from '@angular/animations/browser/testing'; import {CommonModule} from '@angular/common'; import { Component, ContentChild, Directive, ElementRef, EventEmitter, HostBinding, HostListener, Input, NgModule, OnInit, Output, Pipe, QueryList, TemplateRef, ViewChild, ViewChildren, ViewContainerRef, } from '@angular/core'; import {Inject} from '@angular/core/src/di'; import {readPatchedLView} from '@angular/core/src/render3/context_discovery'; import {LContainer} from '@angular/core/src/render3/interfaces/container'; import {getLViewById} from '@angular/core/src/render3/interfaces/lview_tracking'; import {isLView} from '@angular/core/src/render3/interfaces/type_checks'; import {ID, LView, PARENT, TVIEW} from '@angular/core/src/render3/interfaces/view'; import {getLView} from '@angular/core/src/render3/state'; import {ngDevModeResetPerfCounters} from '@angular/core/src/util/ng_dev_mode'; import {fakeAsync, flushMicrotasks, TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {expectPerfCounters} from '@angular/private/testing'; describe('acceptance integration tests', () => { function stripHtmlComments(str: string) { return str.replace(/<!--[\s\S]*?-->/g, ''); } describe('render', () => { it('should render basic template', () => { @Component({ template: '<span title="Hello">Greetings</span>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); expect(fixture.nativeElement.innerHTML).toEqual('<span title="Hello">Greetings</span>'); }); it('should render and update basic "Hello, World" template', () => { ngDevModeResetPerfCounters(); @Component({ template: '<h1>Hello, {{name}}!</h1>', standalone: false, }) class App { name = ''; } expectPerfCounters({ tView: 0, tNode: 0, }); TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.componentInstance.name = 'World'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<h1>Hello, World!</h1>'); expectPerfCounters({ tView: 2, // Host view + App tNode: 3, // Host Node + <h1> + #text }); fixture.componentInstance.name = 'New World'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<h1>Hello, New World!</h1>'); // Assert that the tView/tNode count does not increase (they are correctly cached) expectPerfCounters({ tView: 2, tNode: 3, }); }); });
{ "end_byte": 3164, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/integration_spec.ts" }
angular/packages/core/test/acceptance/integration_spec.ts_3168_13788
describe('ng-container', () => { it('should insert as a child of a regular element', () => { @Component({ template: '<div>before|<ng-container>Greetings<span></span></ng-container>|after</div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); // Strip comments since VE and Ivy put them in different places. expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toBe( '<div>before|Greetings<span></span>|after</div>', ); }); it('should add and remove DOM nodes when ng-container is a child of a regular element', () => { @Component({ template: '<ng-template [ngIf]="render"><div><ng-container>content</ng-container></div></ng-template>', standalone: false, }) class App { render = false; } TestBed.configureTestingModule({declarations: [App], imports: [CommonModule]}); const fixture = TestBed.createComponent(App); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toEqual(''); fixture.componentInstance.render = true; fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toEqual('<div>content</div>'); fixture.componentInstance.render = false; fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toEqual(''); }); it('should add and remove DOM nodes when ng-container is a child of an embedded view', () => { @Component({ template: '<ng-container *ngIf="render">content</ng-container>', standalone: false, }) class App { render = false; } TestBed.configureTestingModule({declarations: [App], imports: [CommonModule]}); const fixture = TestBed.createComponent(App); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toEqual(''); fixture.componentInstance.render = true; fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toEqual('content'); fixture.componentInstance.render = false; fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toEqual(''); }); // https://stackblitz.com/edit/angular-tfhcz1?file=src%2Fapp%2Fapp.component.ts it('should add and remove DOM nodes when ng-container is a child of a delayed embedded view', () => { @Directive({ selector: '[testDirective]', standalone: false, }) class TestDirective { constructor( private _tplRef: TemplateRef<any>, private _vcRef: ViewContainerRef, ) {} createAndInsert() { this._vcRef.insert(this._tplRef.createEmbeddedView({})); } clear() { this._vcRef.clear(); } } @Component({ template: '<ng-template testDirective><ng-container>content</ng-container></ng-template>', standalone: false, }) class App { @ViewChild(TestDirective, {static: true}) testDirective!: TestDirective; } TestBed.configureTestingModule({declarations: [App, TestDirective]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toBe(''); fixture.componentInstance.testDirective.createAndInsert(); fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toBe('content'); fixture.componentInstance.testDirective.clear(); fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toBe(''); }); it('should render at the component view root', () => { @Component({ selector: 'test-cmpt', template: '<ng-container>component template</ng-container>', standalone: false, }) class TestCmpt {} @Component({ template: '<test-cmpt></test-cmpt>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, TestCmpt]}); const fixture = TestBed.createComponent(App); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toBe( '<test-cmpt>component template</test-cmpt>', ); }); it('should render inside another ng-container', () => { @Component({ selector: 'test-cmpt', template: '<ng-container><ng-container><ng-container>content</ng-container></ng-container></ng-container>', standalone: false, }) class TestCmpt {} @Component({ template: '<test-cmpt></test-cmpt>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, TestCmpt]}); const fixture = TestBed.createComponent(App); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toBe( '<test-cmpt>content</test-cmpt>', ); }); it('should render inside another ng-container at the root of a delayed view', () => { @Directive({ selector: '[testDirective]', standalone: false, }) class TestDirective { constructor( private _tplRef: TemplateRef<any>, private _vcRef: ViewContainerRef, ) {} createAndInsert() { this._vcRef.insert(this._tplRef.createEmbeddedView({})); } clear() { this._vcRef.clear(); } } @Component({ template: '<ng-template testDirective><ng-container><ng-container><ng-container>content</ng-container></ng-container></ng-container></ng-template>', standalone: false, }) class App { @ViewChild(TestDirective, {static: true}) testDirective!: TestDirective; } TestBed.configureTestingModule({declarations: [App, TestDirective]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toBe(''); fixture.componentInstance.testDirective.createAndInsert(); fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toBe('content'); fixture.componentInstance.testDirective.createAndInsert(); fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toBe('contentcontent'); fixture.componentInstance.testDirective.clear(); fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toBe(''); }); it('should support directives and inject ElementRef', () => { @Directive({ selector: '[dir]', standalone: false, }) class TestDirective { constructor(public elRef: ElementRef) {} } @Component({ template: '<div><ng-container dir></ng-container></div>', standalone: false, }) class App { @ViewChild(TestDirective) testDirective!: TestDirective; } TestBed.configureTestingModule({declarations: [App, TestDirective]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toEqual('<div></div>'); expect(fixture.componentInstance.testDirective.elRef.nativeElement.nodeType).toBe( Node.COMMENT_NODE, ); }); it('should support ViewContainerRef when ng-container is at the root of a view', () => { @Directive({ selector: '[dir]', standalone: false, }) class TestDirective { @Input() contentTpl: TemplateRef<{}> | null = null; constructor(private _vcRef: ViewContainerRef) {} insertView() { this._vcRef.createEmbeddedView(this.contentTpl as TemplateRef<{}>); } clear() { this._vcRef.clear(); } } @Component({ template: '<ng-container dir [contentTpl]="content"><ng-template #content>Content</ng-template></ng-container>', standalone: false, }) class App { @ViewChild(TestDirective) testDirective!: TestDirective; } TestBed.configureTestingModule({declarations: [App, TestDirective]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toEqual(''); fixture.componentInstance.testDirective.insertView(); fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toEqual('Content'); fixture.componentInstance.testDirective.clear(); fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toEqual(''); }); it('should support ViewContainerRef on <ng-template> inside <ng-container>', () => { @Directive({ selector: '[dir]', standalone: false, }) class TestDirective { constructor( private _tplRef: TemplateRef<{}>, private _vcRef: ViewContainerRef, ) {} insertView() { this._vcRef.createEmbeddedView(this._tplRef); } clear() { this._vcRef.clear(); } } @Component({ template: '<ng-container><ng-template dir>Content</ng-template></ng-container>', standalone: false, }) class App { @ViewChild(TestDirective) testDirective!: TestDirective; } TestBed.configureTestingModule({declarations: [App, TestDirective]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toEqual(''); fixture.componentInstance.testDirective.insertView(); fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toEqual('Content'); fixture.componentInstance.testDirective.clear(); fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toEqual(''); }); it('should not set any attributes', () => { @Component({ template: '<div><ng-container id="foo"></ng-container></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(stripHtmlComments(fixture.nativeElement.innerHTML)).toEqual('<div></div>'); }); });
{ "end_byte": 13788, "start_byte": 3168, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/integration_spec.ts" }
angular/packages/core/test/acceptance/integration_spec.ts_13792_21531
describe('text bindings', () => { it('should render "undefined" as ""', () => { @Component({ template: '{{name}}', standalone: false, }) class App { name: string | undefined = 'benoit'; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('benoit'); fixture.componentInstance.name = undefined; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual(''); }); it('should render "null" as ""', () => { @Component({ template: '{{name}}', standalone: false, }) class App { name: string | null = 'benoit'; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('benoit'); fixture.componentInstance.name = null; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual(''); }); it('should be able to render the result of a function called $any by using this', () => { @Component({ template: '{{this.$any(1, 2)}}', standalone: false, }) class App { $any(value: number, multiplier: number) { return value * multiplier; } } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('2'); }); }); describe('ngNonBindable handling', () => { function stripNgNonBindable(str: string) { return str.replace(/ ngnonbindable=""/i, ''); } it('should keep local ref for host element', () => { @Component({ template: ` <b ngNonBindable #myRef id="my-id"> <i>Hello {{ name }}!</i> </b> {{ myRef.id }} `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(stripNgNonBindable(fixture.nativeElement.innerHTML)).toEqual( '<b id="my-id"><i>Hello {{ name }}!</i></b> my-id ', ); }); it('should invoke directives for host element', () => { let directiveInvoked: boolean = false; @Directive({ selector: '[directive]', standalone: false, }) class TestDirective implements OnInit { ngOnInit() { directiveInvoked = true; } } @Component({ template: ` <b ngNonBindable directive> <i>Hello {{ name }}!</i> </b> `, standalone: false, }) class App { name = 'World'; } TestBed.configureTestingModule({declarations: [App, TestDirective]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(stripNgNonBindable(fixture.nativeElement.innerHTML)).toEqual( '<b directive=""><i>Hello {{ name }}!</i></b>', ); expect(directiveInvoked).toEqual(true); }); it('should not invoke directives for nested elements', () => { let directiveInvoked: boolean = false; @Directive({ selector: '[directive]', standalone: false, }) class TestDirective implements OnInit { ngOnInit() { directiveInvoked = true; } } @Component({ template: ` <b ngNonBindable> <i directive>Hello {{ name }}!</i> </b> `, standalone: false, }) class App { name = 'World'; } TestBed.configureTestingModule({declarations: [App, TestDirective]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(stripNgNonBindable(fixture.nativeElement.innerHTML)).toEqual( '<b><i directive="">Hello {{ name }}!</i></b>', ); expect(directiveInvoked).toEqual(false); }); }); describe('Siblings update', () => { it('should handle a flat list of static/bound text nodes', () => { @Component({ template: 'Hello {{name}}!', standalone: false, }) class App { name = ''; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.componentInstance.name = 'world'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('Hello world!'); fixture.componentInstance.name = 'monde'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('Hello monde!'); }); it('should handle a list of static/bound text nodes as element children', () => { @Component({ template: '<b>Hello {{name}}!</b>', standalone: false, }) class App { name = ''; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.componentInstance.name = 'world'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<b>Hello world!</b>'); fixture.componentInstance.name = 'mundo'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<b>Hello mundo!</b>'); }); it('should render/update text node as a child of a deep list of elements', () => { @Component({ template: '<b><b><b><b>Hello {{name}}!</b></b></b></b>', standalone: false, }) class App { name = ''; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.componentInstance.name = 'world'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<b><b><b><b>Hello world!</b></b></b></b>'); fixture.componentInstance.name = 'mundo'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<b><b><b><b>Hello mundo!</b></b></b></b>'); }); it('should update 2 sibling elements', () => { @Component({ template: '<b><span></span><span class="foo" [id]="id"></span></b>', standalone: false, }) class App { id = ''; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.componentInstance.id = 'foo'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( '<b><span></span><span class="foo" id="foo"></span></b>', ); fixture.componentInstance.id = 'bar'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( '<b><span></span><span class="foo" id="bar"></span></b>', ); }); it('should handle sibling text node after element with child text node', () => { @Component({ template: '<p>hello</p>{{name}}', standalone: false, }) class App { name = ''; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.componentInstance.name = 'world'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<p>hello</p>world'); fixture.componentInstance.name = 'mundo'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<p>hello</p>mundo'); }); });
{ "end_byte": 21531, "start_byte": 13792, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/integration_spec.ts" }
angular/packages/core/test/acceptance/integration_spec.ts_21535_26165
describe('basic components', () => { @Component({ selector: 'todo', template: '<p>Todo{{value}}</p>', standalone: false, }) class TodoComponent { value = ' one'; } it('should support a basic component template', () => { @Component({ template: '<todo></todo>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, TodoComponent]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<todo><p>Todo one</p></todo>'); }); it('should support a component template with sibling', () => { @Component({ template: '<todo></todo>two', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, TodoComponent]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<todo><p>Todo one</p></todo>two'); }); it('should support a component template with component sibling', () => { @Component({ template: '<todo></todo><todo></todo>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, TodoComponent]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( '<todo><p>Todo one</p></todo><todo><p>Todo one</p></todo>', ); }); it('should support a component with binding on host element', () => { @Component({ selector: 'todo', template: '{{title}}', standalone: false, }) class TodoComponentHostBinding { @HostBinding() title = 'one'; } @Component({ template: '<todo></todo>', standalone: false, }) class App { @ViewChild(TodoComponentHostBinding) todoComponentHostBinding!: TodoComponentHostBinding; } TestBed.configureTestingModule({declarations: [App, TodoComponentHostBinding]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<todo title="one">one</todo>'); fixture.componentInstance.todoComponentHostBinding.title = 'two'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<todo title="two">two</todo>'); }); it('should support root component with host attribute', () => { @Component({ selector: 'host-attr-comp', template: '', host: {'role': 'button'}, standalone: false, }) class HostAttributeComp {} TestBed.configureTestingModule({declarations: [HostAttributeComp]}); const fixture = TestBed.createComponent(HostAttributeComp); fixture.detectChanges(); expect(fixture.nativeElement.getAttribute('role')).toEqual('button'); }); it('should support component with bindings in template', () => { @Component({ selector: 'comp', template: '<p>{{ name }}</p>', standalone: false, }) class MyComp { name = 'Bess'; } @Component({ template: '<comp></comp>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, MyComp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<comp><p>Bess</p></comp>'); }); it('should support a component with sub-views', () => { @Component({ selector: 'comp', template: '<div *ngIf="condition">text</div>', standalone: false, }) class MyComp { @Input() condition!: boolean; } @Component({ template: '<comp [condition]="condition"></comp>', standalone: false, }) class App { condition = false; } TestBed.configureTestingModule({declarations: [App, MyComp], imports: [CommonModule]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const compElement = fixture.nativeElement.querySelector('comp'); fixture.componentInstance.condition = true; fixture.detectChanges(); expect(stripHtmlComments(compElement.innerHTML)).toEqual('<div>text</div>'); fixture.componentInstance.condition = false; fixture.detectChanges(); expect(stripHtmlComments(compElement.innerHTML)).toEqual(''); }); });
{ "end_byte": 26165, "start_byte": 21535, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/integration_spec.ts" }
angular/packages/core/test/acceptance/integration_spec.ts_26169_33288
describe('element bindings', () => { describe('elementAttribute', () => { it('should support attribute bindings', () => { @Component({ template: '<button [attr.title]="title"></button>', standalone: false, }) class App { title: string | null = ''; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.componentInstance.title = 'Hello'; fixture.detectChanges(); // initial binding expect(fixture.nativeElement.innerHTML).toEqual('<button title="Hello"></button>'); // update binding fixture.componentInstance.title = 'Hi!'; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<button title="Hi!"></button>'); // remove attribute fixture.componentInstance.title = null; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<button></button>'); }); it('should stringify values used attribute bindings', () => { @Component({ template: '<button [attr.title]="title"></button>', standalone: false, }) class App { title: any; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.componentInstance.title = NaN; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<button title="NaN"></button>'); fixture.componentInstance.title = {toString: () => 'Custom toString'}; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual( '<button title="Custom toString"></button>', ); }); it('should update bindings', () => { @Component({ template: [ 'a:{{c[0]}}{{c[1]}}{{c[2]}}{{c[3]}}{{c[4]}}{{c[5]}}{{c[6]}}{{c[7]}}{{c[8]}}{{c[9]}}{{c[10]}}{{c[11]}}{{c[12]}}{{c[13]}}{{c[14]}}{{c[15]}}{{c[16]}}', 'a0:{{c[1]}}', 'a1:{{c[0]}}{{c[1]}}{{c[16]}}', 'a2:{{c[0]}}{{c[1]}}{{c[2]}}{{c[3]}}{{c[16]}}', 'a3:{{c[0]}}{{c[1]}}{{c[2]}}{{c[3]}}{{c[4]}}{{c[5]}}{{c[16]}}', 'a4:{{c[0]}}{{c[1]}}{{c[2]}}{{c[3]}}{{c[4]}}{{c[5]}}{{c[6]}}{{c[7]}}{{c[16]}}', 'a5:{{c[0]}}{{c[1]}}{{c[2]}}{{c[3]}}{{c[4]}}{{c[5]}}{{c[6]}}{{c[7]}}{{c[8]}}{{c[9]}}{{c[16]}}', 'a6:{{c[0]}}{{c[1]}}{{c[2]}}{{c[3]}}{{c[4]}}{{c[5]}}{{c[6]}}{{c[7]}}{{c[8]}}{{c[9]}}{{c[10]}}{{c[11]}}{{c[16]}}', 'a7:{{c[0]}}{{c[1]}}{{c[2]}}{{c[3]}}{{c[4]}}{{c[5]}}{{c[6]}}{{c[7]}}{{c[8]}}{{c[9]}}{{c[10]}}{{c[11]}}{{c[12]}}{{c[13]}}{{c[16]}}', 'a8:{{c[0]}}{{c[1]}}{{c[2]}}{{c[3]}}{{c[4]}}{{c[5]}}{{c[6]}}{{c[7]}}{{c[8]}}{{c[9]}}{{c[10]}}{{c[11]}}{{c[12]}}{{c[13]}}{{c[14]}}{{c[15]}}{{c[16]}}', ].join('\n'), standalone: false, }) class App { c = ['(', 0, 'a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5, 'f', 6, 'g', 7, ')']; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toEqual( [ 'a:(0a1b2c3d4e5f6g7)', 'a0:0', 'a1:(0)', 'a2:(0a1)', 'a3:(0a1b2)', 'a4:(0a1b2c3)', 'a5:(0a1b2c3d4)', 'a6:(0a1b2c3d4e5)', 'a7:(0a1b2c3d4e5f6)', 'a8:(0a1b2c3d4e5f6g7)', ].join('\n'), ); fixture.componentInstance.c.reverse(); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toEqual( [ 'a:)7g6f5e4d3c2b1a0(', 'a0:7', 'a1:)7(', 'a2:)7g6(', 'a3:)7g6f5(', 'a4:)7g6f5e4(', 'a5:)7g6f5e4d3(', 'a6:)7g6f5e4d3c2(', 'a7:)7g6f5e4d3c2b1(', 'a8:)7g6f5e4d3c2b1a0(', ].join('\n'), ); fixture.componentInstance.c.reverse(); fixture.detectChanges(); expect(fixture.nativeElement.textContent.trim()).toEqual( [ 'a:(0a1b2c3d4e5f6g7)', 'a0:0', 'a1:(0)', 'a2:(0a1)', 'a3:(0a1b2)', 'a4:(0a1b2c3)', 'a5:(0a1b2c3d4)', 'a6:(0a1b2c3d4e5)', 'a7:(0a1b2c3d4e5f6)', 'a8:(0a1b2c3d4e5f6g7)', ].join('\n'), ); }); it('should not update DOM if context has not changed', () => { @Component({ template: ` <span [attr.title]="title"> <b [attr.title]="title" *ngIf="shouldRender"></b> </span> `, standalone: false, }) class App { title: string | null = ''; shouldRender = true; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const span: HTMLSpanElement = fixture.nativeElement.querySelector('span'); const bold: HTMLElement = span.querySelector('b')!; fixture.componentInstance.title = 'Hello'; fixture.detectChanges(); // initial binding expect(span.getAttribute('title')).toBe('Hello'); expect(bold.getAttribute('title')).toBe('Hello'); // update DOM manually bold.setAttribute('title', 'Goodbye'); // refresh with same binding fixture.detectChanges(); expect(span.getAttribute('title')).toBe('Hello'); expect(bold.getAttribute('title')).toBe('Goodbye'); // refresh again with same binding fixture.detectChanges(); expect(span.getAttribute('title')).toBe('Hello'); expect(bold.getAttribute('title')).toBe('Goodbye'); }); it('should support host attribute bindings', () => { @Directive({ selector: '[hostBindingDir]', standalone: false, }) class HostBindingDir { @HostBinding('attr.aria-label') label = 'some label'; } @Component({ template: '<div hostBindingDir></div>', standalone: false, }) class App { @ViewChild(HostBindingDir) hostBindingDir!: HostBindingDir; } TestBed.configureTestingModule({declarations: [App, HostBindingDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const hostBindingEl = fixture.nativeElement.querySelector('div'); // Needs `toLowerCase`, because different browsers produce // attributes either in camel case or lower case. expect(hostBindingEl.getAttribute('aria-label')).toBe('some label'); fixture.componentInstance.hostBindingDir.label = 'other label'; fixture.detectChanges(); expect(hostBindingEl.getAttribute('aria-label')).toBe('other label'); }); });
{ "end_byte": 33288, "start_byte": 26169, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/integration_spec.ts" }
angular/packages/core/test/acceptance/integration_spec.ts_33294_35183
describe('elementStyle', () => { it('should support binding to styles', () => { @Component({ template: '<span [style.font-size]="size"></span>', standalone: false, }) class App { size: string | null = ''; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.componentInstance.size = '10px'; fixture.detectChanges(); const span: HTMLElement = fixture.nativeElement.querySelector('span'); expect(span.style.fontSize).toBe('10px'); fixture.componentInstance.size = '16px'; fixture.detectChanges(); expect(span.style.fontSize).toBe('16px'); fixture.componentInstance.size = null; fixture.detectChanges(); expect(span.style.fontSize).toBeFalsy(); }); it('should support binding to styles with suffix', () => { @Component({ template: '<span [style.font-size.px]="size"></span>', standalone: false, }) class App { size: string | number | null = ''; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.componentInstance.size = '100'; fixture.detectChanges(); const span: HTMLElement = fixture.nativeElement.querySelector('span'); expect(span.style.fontSize).toEqual('100px'); fixture.componentInstance.size = 200; fixture.detectChanges(); expect(span.style.fontSize).toEqual('200px'); fixture.componentInstance.size = 0; fixture.detectChanges(); expect(span.style.fontSize).toEqual('0px'); fixture.componentInstance.size = null; fixture.detectChanges(); expect(span.style.fontSize).toBeFalsy(); }); });
{ "end_byte": 35183, "start_byte": 33294, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/integration_spec.ts" }
angular/packages/core/test/acceptance/integration_spec.ts_35189_44794
describe('class-based styling', () => { it('should support CSS class toggle', () => { @Component({ template: '<span [class.active]="value"></span>', standalone: false, }) class App { value: any; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.componentInstance.value = true; fixture.detectChanges(); const span = fixture.nativeElement.querySelector('span'); expect(span.getAttribute('class')).toEqual('active'); fixture.componentInstance.value = false; fixture.detectChanges(); expect(span.getAttribute('class')).toBeFalsy(); // truthy values fixture.componentInstance.value = 'a_string'; fixture.detectChanges(); expect(span.getAttribute('class')).toEqual('active'); fixture.componentInstance.value = 10; fixture.detectChanges(); expect(span.getAttribute('class')).toEqual('active'); // falsy values fixture.componentInstance.value = ''; fixture.detectChanges(); expect(span.getAttribute('class')).toBeFalsy(); fixture.componentInstance.value = 0; fixture.detectChanges(); expect(span.getAttribute('class')).toBeFalsy(); }); it('should work correctly with existing static classes', () => { @Component({ template: '<span class="existing" [class.active]="value"></span>', standalone: false, }) class App { value: any; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.componentInstance.value = true; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<span class="existing active"></span>'); fixture.componentInstance.value = false; fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toEqual('<span class="existing"></span>'); }); it('should apply classes properly when nodes are components', () => { @Component({ selector: 'my-comp', template: 'Comp Content', standalone: false, }) class MyComp {} @Component({ template: '<my-comp [class.active]="value"></my-comp>', standalone: false, }) class App { value: any; } TestBed.configureTestingModule({declarations: [App, MyComp]}); const fixture = TestBed.createComponent(App); fixture.componentInstance.value = true; fixture.detectChanges(); const compElement = fixture.nativeElement.querySelector('my-comp'); expect(fixture.nativeElement.textContent).toContain('Comp Content'); expect(compElement.getAttribute('class')).toBe('active'); fixture.componentInstance.value = false; fixture.detectChanges(); expect(compElement.getAttribute('class')).toBeFalsy(); }); it('should apply classes properly when nodes have containers', () => { @Component({ selector: 'structural-comp', template: 'Comp Content', standalone: false, }) class StructuralComp { @Input() tmp!: TemplateRef<any>; constructor(public vcr: ViewContainerRef) {} create() { this.vcr.createEmbeddedView(this.tmp); } } @Component({ template: ` <ng-template #foo>Temp Content</ng-template> <structural-comp [class.active]="value" [tmp]="foo"></structural-comp> `, standalone: false, }) class App { @ViewChild(StructuralComp) structuralComp!: StructuralComp; value: any; } TestBed.configureTestingModule({declarations: [App, StructuralComp]}); const fixture = TestBed.createComponent(App); fixture.componentInstance.value = true; fixture.detectChanges(); const structuralCompEl = fixture.nativeElement.querySelector('structural-comp'); expect(structuralCompEl.getAttribute('class')).toEqual('active'); fixture.componentInstance.structuralComp.create(); fixture.detectChanges(); expect(structuralCompEl.getAttribute('class')).toEqual('active'); fixture.componentInstance.value = false; fixture.detectChanges(); expect(structuralCompEl.getAttribute('class')).toBeFalsy(); }); @Directive({ selector: '[DirWithClass]', standalone: false, }) class DirWithClassDirective { public classesVal: string = ''; @Input('class') set klass(value: string) { this.classesVal = value; } } @Directive({ selector: '[DirWithStyle]', standalone: false, }) class DirWithStyleDirective { public stylesVal: any = ''; @Input() set style(value: any) { this.stylesVal = value; } } it('should delegate initial classes to a [class] input binding if present on a directive on the same element', () => { @Component({ template: '<div class="apple orange banana" DirWithClass></div>', standalone: false, }) class App { @ViewChild(DirWithClassDirective) mockClassDirective!: DirWithClassDirective; } TestBed.configureTestingModule({declarations: [App, DirWithClassDirective]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); // the initial values always get sorted in non VE code // but there is no sorting guarantee within VE code expect(fixture.componentInstance.mockClassDirective.classesVal.split(/\s+/).sort()).toEqual( ['apple', 'banana', 'orange'], ); }); it('should delegate initial styles to a [style] input binding if present on a directive on the same element', () => { @Component({ template: '<div style="width: 100px; height: 200px" DirWithStyle></div>', standalone: false, }) class App { @ViewChild(DirWithStyleDirective) mockStyleDirective!: DirWithStyleDirective; } TestBed.configureTestingModule({declarations: [App, DirWithStyleDirective]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const styles = fixture.componentInstance.mockStyleDirective.stylesVal; expect(styles).toEqual('width: 100px; height: 200px;'); }); it('should update `[class]` and bindings in the provided directive if the input is matched', () => { @Component({ template: '<div DirWithClass [class]="value"></div>', standalone: false, }) class App { @ViewChild(DirWithClassDirective) mockClassDirective!: DirWithClassDirective; value = ''; } TestBed.configureTestingModule({declarations: [App, DirWithClassDirective]}); const fixture = TestBed.createComponent(App); fixture.componentInstance.value = 'cucumber grape'; fixture.detectChanges(); expect(fixture.componentInstance.mockClassDirective.classesVal).toEqual('cucumber grape'); }); it('should update `[style]` and bindings in the provided directive if the input is matched', () => { @Component({ template: '<div DirWithStyle [style]="value"></div>', standalone: false, }) class App { @ViewChild(DirWithStyleDirective) mockStyleDirective!: DirWithStyleDirective; value!: {[key: string]: string}; } TestBed.configureTestingModule({declarations: [App, DirWithStyleDirective]}); const fixture = TestBed.createComponent(App); fixture.componentInstance.value = {width: '200px', height: '500px'}; fixture.detectChanges(); expect(fixture.componentInstance.mockStyleDirective.stylesVal).toEqual({ width: '200px', height: '500px', }); }); it('should apply initial styling to the element that contains the directive with host styling', () => { @Directive({ selector: '[DirWithInitialStyling]', host: { 'title': 'foo', 'class': 'heavy golden', 'style': 'color: purple', '[style.font-weight]': '"bold"', }, standalone: false, }) class DirWithInitialStyling {} @Component({ template: ` <div DirWithInitialStyling class="big" style="color:black; font-size:200px"></div> `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, DirWithInitialStyling]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const target: HTMLDivElement = fixture.nativeElement.querySelector('div'); const classes = target.getAttribute('class')!.split(/\s+/).sort(); expect(classes).toEqual(['big', 'golden', 'heavy']); expect(target.getAttribute('title')).toEqual('foo'); expect(target.style.getPropertyValue('color')).toEqual('black'); expect(target.style.getPropertyValue('font-size')).toEqual('200px'); expect(target.style.getPropertyValue('font-weight')).toEqual('bold'); });
{ "end_byte": 44794, "start_byte": 35189, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/integration_spec.ts" }
angular/packages/core/test/acceptance/integration_spec.ts_44802_54316
it("should apply single styling bindings present within a directive onto the same element and defer the element's initial styling values when missing", () => { @Directive({ selector: '[DirWithSingleStylingBindings]', host: { 'class': 'def', '[class.xyz]': 'activateXYZClass', '[style.width]': 'width', '[style.height]': 'height', }, standalone: false, }) class DirWithSingleStylingBindings { width: string | null | undefined = undefined; height: string | null | undefined = undefined; activateXYZClass: boolean = false; } @Component({ template: ` <div DirWithSingleStylingBindings class="abc" style="width:100px;"></div> `, standalone: false, }) class App { @ViewChild(DirWithSingleStylingBindings) dirInstance!: DirWithSingleStylingBindings; } TestBed.configureTestingModule({declarations: [App, DirWithSingleStylingBindings]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const dirInstance = fixture.componentInstance.dirInstance; const target: HTMLDivElement = fixture.nativeElement.querySelector('div'); expect(target.style.getPropertyValue('width')).toEqual('100px'); expect(target.style.getPropertyValue('height')).toEqual(''); expect(target.classList.contains('abc')).toBeTruthy(); expect(target.classList.contains('def')).toBeTruthy(); expect(target.classList.contains('xyz')).toBeFalsy(); dirInstance.width = '444px'; dirInstance.height = '999px'; dirInstance.activateXYZClass = true; fixture.detectChanges(); expect(target.style.getPropertyValue('width')).toEqual('100px'); expect(target.style.getPropertyValue('height')).toEqual('999px'); expect(target.classList.contains('abc')).toBeTruthy(); expect(target.classList.contains('def')).toBeTruthy(); expect(target.classList.contains('xyz')).toBeTruthy(); dirInstance.width = undefined; dirInstance.height = undefined; fixture.detectChanges(); expect(target.style.getPropertyValue('width')).toEqual('100px'); expect(target.style.getPropertyValue('height')).toEqual(''); expect(target.classList.contains('abc')).toBeTruthy(); expect(target.classList.contains('def')).toBeTruthy(); expect(target.classList.contains('xyz')).toBeTruthy(); }); it('should properly prioritize single style binding collisions when they exist on multiple directives', () => { @Directive({ selector: '[Dir1WithStyle]', host: {'[style.width]': 'width'}, standalone: false, }) class Dir1WithStyle { width: null | string | undefined = undefined; } @Directive({ selector: '[Dir2WithStyle]', host: {'style': 'width: 111px', '[style.width]': 'width'}, standalone: false, }) class Dir2WithStyle { width: null | string | undefined = undefined; } @Component({ template: '<div Dir1WithStyle Dir2WithStyle [style.width]="width"></div>', standalone: false, }) class App { @ViewChild(Dir1WithStyle) dir1Instance!: Dir1WithStyle; @ViewChild(Dir2WithStyle) dir2Instance!: Dir2WithStyle; width: string | null | undefined = undefined; } TestBed.configureTestingModule({declarations: [App, Dir2WithStyle, Dir1WithStyle]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const {dir1Instance, dir2Instance} = fixture.componentInstance; const target: HTMLDivElement = fixture.nativeElement.querySelector('div'); expect(target.style.getPropertyValue('width')).toEqual('111px'); fixture.componentInstance.width = '999px'; dir1Instance.width = '222px'; dir2Instance.width = '333px'; fixture.detectChanges(); expect(target.style.getPropertyValue('width')).toEqual('999px'); fixture.componentInstance.width = undefined; fixture.detectChanges(); expect(target.style.getPropertyValue('width')).toEqual('222px'); dir1Instance.width = undefined; fixture.detectChanges(); expect(target.style.getPropertyValue('width')).toEqual('333px'); dir2Instance.width = undefined; fixture.detectChanges(); expect(target.style.getPropertyValue('width')).toEqual('111px'); dir1Instance.width = '666px'; fixture.detectChanges(); expect(target.style.getPropertyValue('width')).toEqual('666px'); fixture.componentInstance.width = '777px'; fixture.detectChanges(); expect(target.style.getPropertyValue('width')).toEqual('777px'); }); it('should properly prioritize multi style binding collisions when they exist on multiple directives', () => { @Directive({ selector: '[Dir1WithStyling]', host: {'[style]': 'stylesExp', '[class]': 'classesExp'}, standalone: false, }) class Dir1WithStyling { classesExp: any = {}; stylesExp: any = {}; } @Directive({ selector: '[Dir2WithStyling]', host: {'style': 'width: 111px', '[style]': 'stylesExp'}, standalone: false, }) class Dir2WithStyling { stylesExp: any = {}; } @Component({ template: '<div Dir1WithStyling Dir2WithStyling [style]="stylesExp" [class]="classesExp"></div>', standalone: false, }) class App { @ViewChild(Dir1WithStyling) dir1Instance!: Dir1WithStyling; @ViewChild(Dir2WithStyling) dir2Instance!: Dir2WithStyling; stylesExp: any = {}; classesExp: any = {}; } TestBed.configureTestingModule({declarations: [App, Dir2WithStyling, Dir1WithStyling]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const {dir1Instance, dir2Instance} = fixture.componentInstance; const target = fixture.nativeElement.querySelector('div')!; expect(target.style.getPropertyValue('width')).toEqual('111px'); const compInstance = fixture.componentInstance; compInstance.stylesExp = {width: '999px', height: undefined}; compInstance.classesExp = {one: true, two: false}; dir1Instance.stylesExp = {width: '222px'}; dir1Instance.classesExp = {two: true, three: false}; dir2Instance.stylesExp = {width: '333px', height: '100px'}; fixture.detectChanges(); expect(target.style.getPropertyValue('width')).toEqual('999px'); expect(target.style.getPropertyValue('height')).toEqual('100px'); expect(target.classList.contains('one')).toBeTruthy(); expect(target.classList.contains('two')).toBeFalsy(); expect(target.classList.contains('three')).toBeFalsy(); compInstance.stylesExp = {}; compInstance.classesExp = {}; dir1Instance.stylesExp = {width: '222px', height: '200px'}; fixture.detectChanges(); expect(target.style.getPropertyValue('width')).toEqual('222px'); expect(target.style.getPropertyValue('height')).toEqual('200px'); expect(target.classList.contains('one')).toBeFalsy(); expect(target.classList.contains('two')).toBeTruthy(); expect(target.classList.contains('three')).toBeFalsy(); dir1Instance.stylesExp = {}; dir1Instance.classesExp = {}; fixture.detectChanges(); expect(target.style.getPropertyValue('width')).toEqual('333px'); expect(target.style.getPropertyValue('height')).toEqual('100px'); expect(target.classList.contains('one')).toBeFalsy(); expect(target.classList.contains('two')).toBeFalsy(); expect(target.classList.contains('three')).toBeFalsy(); dir2Instance.stylesExp = {}; compInstance.stylesExp = {height: '900px'}; fixture.detectChanges(); expect(target.style.getPropertyValue('width')).toEqual('111px'); expect(target.style.getPropertyValue('height')).toEqual('900px'); dir1Instance.stylesExp = {width: '666px', height: '600px'}; dir1Instance.classesExp = {four: true, one: true}; fixture.detectChanges(); expect(target.style.getPropertyValue('width')).toEqual('666px'); expect(target.style.getPropertyValue('height')).toEqual('900px'); expect(target.classList.contains('one')).toBeTruthy(); expect(target.classList.contains('two')).toBeFalsy(); expect(target.classList.contains('three')).toBeFalsy(); expect(target.classList.contains('four')).toBeTruthy(); compInstance.stylesExp = {width: '777px'}; compInstance.classesExp = {four: false}; fixture.detectChanges(); expect(target.style.getPropertyValue('width')).toEqual('777px'); expect(target.style.getPropertyValue('height')).toEqual('600px'); expect(target.classList.contains('one')).toBeTruthy(); expect(target.classList.contains('two')).toBeFalsy(); expect(target.classList.contains('three')).toBeFalsy(); expect(target.classList.contains('four')).toBeFalsy(); }); });
{ "end_byte": 54316, "start_byte": 44802, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/integration_spec.ts" }
angular/packages/core/test/acceptance/integration_spec.ts_54322_63807
it('should properly handle and render interpolation for class attribute bindings', () => { @Component({ template: '<div class="-{{name}}-{{age}}-"></div>', standalone: false, }) class App { name = ''; age = ''; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); const target = fixture.nativeElement.querySelector('div')!; expect(target.classList.contains('-fred-36-')).toBeFalsy(); fixture.componentInstance.name = 'fred'; fixture.componentInstance.age = '36'; fixture.detectChanges(); expect(target.classList.contains('-fred-36-')).toBeTruthy(); }); }); describe('NgModule assertions', () => { it('should throw with descriptive error message when a module imports itself', () => { @Component({ template: '', standalone: false, }) class FixtureComponent {} @NgModule({imports: [SomeModule], declarations: [FixtureComponent]}) class SomeModule {} expect(() => { TestBed.configureTestingModule({imports: [SomeModule]}).createComponent(FixtureComponent); }).toThrowError(`'SomeModule' module can't import itself`); }); it('should throw with descriptive error message when a directive is passed to imports', () => { @Component({ template: '', standalone: false, }) class SomeComponent {} @NgModule({imports: [SomeComponent]}) class ModuleWithImportedComponent {} expect(() => { TestBed.configureTestingModule({imports: [ModuleWithImportedComponent]}).createComponent( SomeComponent, ); }).toThrowError( /^Unexpected directive 'SomeComponent' imported by the module 'ModuleWithImportedComponent'\. Please add an @NgModule annotation\.$/, ); }); it('should throw with descriptive error message when a pipe is passed to imports', () => { @Component({ template: '', standalone: false, }) class FixtureComponent {} @Pipe({ name: 'somePipe', standalone: false, }) class SomePipe {} @NgModule({imports: [SomePipe], declarations: [FixtureComponent]}) class ModuleWithImportedPipe {} expect(() => { TestBed.configureTestingModule({imports: [ModuleWithImportedPipe]}).createComponent( FixtureComponent, ); }).toThrowError( /^Unexpected pipe 'SomePipe' imported by the module 'ModuleWithImportedPipe'\. Please add an @NgModule annotation\.$/, ); }); it('should throw with descriptive error message when a module is passed to declarations', () => { @Component({ template: '', standalone: false, }) class FixtureComponent {} @NgModule({}) class SomeModule {} @NgModule({declarations: [SomeModule, FixtureComponent]}) class ModuleWithDeclaredModule {} const expectedErrorMessage = `Unexpected value 'SomeModule' declared by the module 'ModuleWithDeclaredModule'. Please add a @Pipe/@Directive/@Component annotation.`; expect(() => { TestBed.configureTestingModule({imports: [ModuleWithDeclaredModule]}).createComponent( FixtureComponent, ); }).toThrowError(expectedErrorMessage); }); it('should throw with descriptive error message when a declaration is missing annotation', () => { @Component({ template: '', standalone: false, }) class FixtureComponent {} class SomeClass {} @NgModule({declarations: [SomeClass, FixtureComponent]}) class SomeModule {} expect(() => { TestBed.configureTestingModule({imports: [SomeModule]}).createComponent(FixtureComponent); }).toThrowError( `Unexpected value 'SomeClass' declared by the module 'SomeModule'. Please add a @Pipe/@Directive/@Component annotation.`, ); }); it('should throw with descriptive error message when an imported module is missing annotation', () => { @Component({ template: '', standalone: false, }) class FixtureComponent {} class SomeModule {} @NgModule({imports: [SomeModule], declarations: [FixtureComponent]}) class ModuleWithImportedModule {} expect(() => { TestBed.configureTestingModule({imports: [ModuleWithImportedModule]}).createComponent( FixtureComponent, ); }).toThrowError( /^Unexpected value 'SomeModule' imported by the module 'ModuleWithImportedModule'\. Please add an @NgModule annotation\.$/, ); }); }); describe('self-closing tags', () => { it('should allow a self-closing tag for a custom tag name', () => { @Component({ selector: 'my-comp', template: 'hello', standalone: false, }) class MyComp {} @Component({ template: '<my-comp/>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, MyComp]}); const fixture = TestBed.createComponent(App); expect(fixture.nativeElement.innerHTML).toEqual('<my-comp>hello</my-comp>'); }); it('should not confuse self-closing tag for an end tag', () => { @Component({ selector: 'my-comp', template: '<ng-content/>', standalone: false, }) class MyComp {} @Component({ template: '<my-comp title="a">Before<my-comp title="b"/>After</my-comp>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, MyComp]}); const fixture = TestBed.createComponent(App); expect(fixture.nativeElement.innerHTML).toEqual( '<my-comp title="a">Before<my-comp title="b"></my-comp>After</my-comp>', ); }); }); it('should only call inherited host listeners once', () => { let clicks = 0; @Component({ template: '', standalone: false, }) class ButtonSuperClass { @HostListener('click') clicked() { clicks++; } } @Component({ selector: 'button[custom-button]', template: '', standalone: false, }) class ButtonSubClass extends ButtonSuperClass {} @Component({ template: '<button custom-button></button>', standalone: false, }) class MyApp {} TestBed.configureTestingModule({declarations: [MyApp, ButtonSuperClass, ButtonSubClass]}); const fixture = TestBed.createComponent(MyApp); const button = fixture.debugElement.query(By.directive(ButtonSubClass)); fixture.detectChanges(); button.nativeElement.click(); fixture.detectChanges(); expect(clicks).toBe(1); }); it('should support inherited view queries', () => { @Directive({ selector: '[someDir]', standalone: false, }) class SomeDir {} @Component({ template: '<div someDir></div>', standalone: false, }) class SuperComp { @ViewChildren(SomeDir) dirs!: QueryList<SomeDir>; } @Component({ selector: 'button[custom-button]', template: '<div someDir></div>', standalone: false, }) class SubComp extends SuperComp {} @Component({ template: '<button custom-button></button>', standalone: false, }) class MyApp {} TestBed.configureTestingModule({declarations: [MyApp, SuperComp, SubComp, SomeDir]}); const fixture = TestBed.createComponent(MyApp); const subInstance = fixture.debugElement.query(By.directive(SubComp)).componentInstance; fixture.detectChanges(); expect(subInstance.dirs.length).toBe(1); expect(subInstance.dirs.first).toBeInstanceOf(SomeDir); }); it('should not set inputs after destroy', () => { @Directive({ selector: '[no-assign-after-destroy]', standalone: false, }) class NoAssignAfterDestroy { private _isDestroyed = false; @Input() get value() { return this._value; } set value(newValue: any) { if (this._isDestroyed) { throw Error('Cannot assign to value after destroy.'); } this._value = newValue; } private _value: any; ngOnDestroy() { this._isDestroyed = true; } } @Component({ template: '<div no-assign-after-destroy [value]="directiveValue"></div>', standalone: false, }) class App { directiveValue = 'initial-value'; } TestBed.configureTestingModule({declarations: [NoAssignAfterDestroy, App]}); let fixture = TestBed.createComponent(App); fixture.destroy(); expect(() => { fixture = TestBed.createComponent(App); fixture.detectChanges(); }).not.toThrow(); }); it('should support host attribute and @ContentChild on the same component', () => { @Component({ selector: 'test-component', template: `foo`, host: {'[attr.aria-disabled]': 'true'}, standalone: false, }) class TestComponent { @ContentChild(TemplateRef, {static: true}) tpl!: TemplateRef<any>; } TestBed.configureTestingModule({declarations: [TestComponent]}); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.componentInstance.tpl).not.toBeNull(); expect(fixture.debugElement.nativeElement.getAttribute('aria-disabled')).toBe('true'); });
{ "end_byte": 63807, "start_byte": 54322, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/integration_spec.ts" }
angular/packages/core/test/acceptance/integration_spec.ts_63811_72487
it('should inherit inputs from undecorated superclasses', () => { class ButtonSuperClass { @Input() isDisabled!: boolean; } @Component({ selector: 'button[custom-button]', template: '', standalone: false, }) class ButtonSubClass extends ButtonSuperClass {} @Component({ template: '<button custom-button [isDisabled]="disableButton"></button>', standalone: false, }) class MyApp { disableButton = false; } TestBed.configureTestingModule({declarations: [MyApp, ButtonSubClass]}); const fixture = TestBed.createComponent(MyApp); const button = fixture.debugElement.query(By.directive(ButtonSubClass)).componentInstance; fixture.detectChanges(); expect(button.isDisabled).toBe(false); fixture.componentInstance.disableButton = true; fixture.detectChanges(); expect(button.isDisabled).toBe(true); }); it('should inherit outputs from undecorated superclasses', () => { let clicks = 0; class ButtonSuperClass { @Output() clicked = new EventEmitter<void>(); emitClick() { this.clicked.emit(); } } @Component({ selector: 'button[custom-button]', template: '', standalone: false, }) class ButtonSubClass extends ButtonSuperClass {} @Component({ template: '<button custom-button (clicked)="handleClick()"></button>', standalone: false, }) class MyApp { handleClick() { clicks++; } } TestBed.configureTestingModule({declarations: [MyApp, ButtonSubClass]}); const fixture = TestBed.createComponent(MyApp); const button = fixture.debugElement.query(By.directive(ButtonSubClass)).componentInstance; button.emitClick(); fixture.detectChanges(); expect(clicks).toBe(1); }); it('should inherit host bindings from undecorated superclasses', () => { class BaseButton { @HostBinding('attr.tabindex') tabindex = -1; } @Component({ selector: '[sub-button]', template: '<ng-content></ng-content>', standalone: false, }) class SubButton extends BaseButton {} @Component({ template: '<button sub-button>Click me</button>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [SubButton, App]}); const fixture = TestBed.createComponent(App); const button = fixture.debugElement.query(By.directive(SubButton)); fixture.detectChanges(); expect(button.nativeElement.getAttribute('tabindex')).toBe('-1'); button.componentInstance.tabindex = 2; fixture.detectChanges(); expect(button.nativeElement.getAttribute('tabindex')).toBe('2'); }); it('should inherit host bindings from undecorated grand superclasses', () => { class SuperBaseButton { @HostBinding('attr.tabindex') tabindex = -1; } class BaseButton extends SuperBaseButton {} @Component({ selector: '[sub-button]', template: '<ng-content></ng-content>', standalone: false, }) class SubButton extends BaseButton {} @Component({ template: '<button sub-button>Click me</button>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [SubButton, App]}); const fixture = TestBed.createComponent(App); const button = fixture.debugElement.query(By.directive(SubButton)); fixture.detectChanges(); expect(button.nativeElement.getAttribute('tabindex')).toBe('-1'); button.componentInstance.tabindex = 2; fixture.detectChanges(); expect(button.nativeElement.getAttribute('tabindex')).toBe('2'); }); it('should inherit host listeners from undecorated superclasses', () => { let clicks = 0; class BaseButton { @HostListener('click') handleClick() { clicks++; } } @Component({ selector: '[sub-button]', template: '<ng-content></ng-content>', standalone: false, }) class SubButton extends BaseButton {} @Component({ template: '<button sub-button>Click me</button>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [SubButton, App]}); const fixture = TestBed.createComponent(App); const button = fixture.debugElement.query(By.directive(SubButton)).nativeElement; button.click(); fixture.detectChanges(); expect(clicks).toBe(1); }); it('should inherit host listeners from superclasses once', () => { let clicks = 0; @Directive({ selector: '[baseButton]', standalone: false, }) class BaseButton { @HostListener('click') handleClick() { clicks++; } } @Component({ selector: '[subButton]', template: '<ng-content></ng-content>', standalone: false, }) class SubButton extends BaseButton {} @Component({ template: '<button subButton>Click me</button>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [SubButton, BaseButton, App]}); const fixture = TestBed.createComponent(App); const button = fixture.debugElement.query(By.directive(SubButton)).nativeElement; button.click(); fixture.detectChanges(); expect(clicks).toBe(1); }); it('should inherit host listeners from grand superclasses once', () => { let clicks = 0; @Directive({ selector: '[superBaseButton]', standalone: false, }) class SuperBaseButton { @HostListener('click') handleClick() { clicks++; } } @Directive({ selector: '[baseButton]', standalone: false, }) class BaseButton extends SuperBaseButton {} @Component({ selector: '[subButton]', template: '<ng-content></ng-content>', standalone: false, }) class SubButton extends BaseButton {} @Component({ template: '<button subButton>Click me</button>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [SubButton, SuperBaseButton, BaseButton, App]}); const fixture = TestBed.createComponent(App); const button = fixture.debugElement.query(By.directive(SubButton)).nativeElement; button.click(); fixture.detectChanges(); expect(clicks).toBe(1); }); it('should inherit host listeners from grand grand superclasses once', () => { let clicks = 0; @Directive({ selector: '[superSuperBaseButton]', standalone: false, }) class SuperSuperBaseButton { @HostListener('click') handleClick() { clicks++; } } @Directive({ selector: '[superBaseButton]', standalone: false, }) class SuperBaseButton extends SuperSuperBaseButton {} @Directive({ selector: '[baseButton]', standalone: false, }) class BaseButton extends SuperBaseButton {} @Component({ selector: '[subButton]', template: '<ng-content></ng-content>', standalone: false, }) class SubButton extends BaseButton {} @Component({ template: '<button subButton>Click me</button>', standalone: false, }) class App {} TestBed.configureTestingModule({ declarations: [SubButton, SuperBaseButton, SuperSuperBaseButton, BaseButton, App], }); const fixture = TestBed.createComponent(App); const button = fixture.debugElement.query(By.directive(SubButton)).nativeElement; button.click(); fixture.detectChanges(); expect(clicks).toBe(1); }); it('should not mask errors thrown during lifecycle hooks', () => { @Directive({ selector: '[dir]', inputs: ['dir'], standalone: false, }) class Dir { get dir(): any { return null; } set dir(value: any) { throw new Error('this error is expected'); } } @Component({ template: '<div [dir]="3"></div>', standalone: false, }) class Cmp { ngAfterViewInit(): void { // This lifecycle hook should never run, since attempting to bind to Dir's input will throw // an error. If the runtime continues to run lifecycle hooks after that error, then it will // execute this hook and throw this error, which will mask the real problem. This test // verifies this don't happen. throw new Error('this error is unexpected'); } } TestBed.configureTestingModule({ declarations: [Cmp, Dir], }); const fixture = TestBed.createComponent(Cmp); expect(() => fixture.detectChanges()).toThrowError('this error is expected'); });
{ "end_byte": 72487, "start_byte": 63811, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/integration_spec.ts" }
angular/packages/core/test/acceptance/integration_spec.ts_72491_79345
it('should handle nullish coalescing inside templates', () => { @Component({ template: ` <span [title]="'Your last name is ' + (lastName ?? lastNameFallback ?? 'unknown')"> Hello, {{ firstName ?? 'Frodo' }}! You are a Balrog: {{ falsyValue ?? true }} </span> `, standalone: false, }) class App { firstName: string | null = null; lastName: string | null = null; lastNameFallback = 'Baggins'; falsyValue = false; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const content = fixture.nativeElement.innerHTML; expect(content).toContain('Hello, Frodo!'); expect(content).toContain('You are a Balrog: false'); expect(content).toContain(`<span title="Your last name is Baggins">`); }); it('should handle safe keyed reads inside templates', () => { @Component({ template: ` <span [title]="'Your last name is ' + (unknownNames?.[0] || 'unknown')"> Hello, {{ knownNames?.[0]?.[1] }}! You are a Balrog: {{ species?.[0]?.[1]?.[2]?.[3]?.[4]?.[5] || 'unknown' }} You are an Elf: {{ speciesMap?.[keys?.[0] ?? 'key'] }} You are an Orc: {{ speciesMap?.['key'] }} </span> `, standalone: false, }) class App { unknownNames: string[] | null = null; knownNames: string[][] = [['Frodo', 'Bilbo']]; species = null; keys = null; speciesMap: Record<string, string> = {key: 'unknown'}; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const content = fixture.nativeElement.innerHTML; expect(content).toContain('Hello, Bilbo!'); expect(content).toContain('You are a Balrog: unknown'); expect(content).toContain('You are an Elf: unknown'); expect(content).toContain(`<span title="Your last name is unknown">`); }); it('should handle safe keyed reads inside templates', () => { @Component({ template: ` <span [title]="'Your last name is ' + (person.getLastName?.() ?? 'unknown')"> Hello, {{ person.getName?.() }}! You are a Balrog: {{ person.getSpecies?.()?.()?.()?.()?.() || 'unknown' }} </span> `, standalone: false, }) class App { person: { getName: () => string; getLastName?: () => string; getSpecies?: () => () => () => () => () => string; } = {getName: () => 'Bilbo'}; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const content = fixture.nativeElement.innerHTML; expect(content).toContain('Hello, Bilbo!'); expect(content).toContain('You are a Balrog: unknown'); expect(content).toContain(`<span title="Your last name is unknown">`); }); it('should not invoke safe calls more times than plain calls', () => { const returnValue = () => () => () => () => 'hi'; let plainCalls = 0; let safeCalls = 0; @Component({ template: `{{ safe?.()?.()?.()?.()?.() }} {{ plain()()()()() }}`, standalone: false, }) class App { plain() { plainCalls++; return returnValue; } safe() { safeCalls++; return returnValue; } } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(safeCalls).toBeGreaterThan(0); expect(safeCalls).toBe(plainCalls); }); it('should handle nullish coalescing inside host bindings', () => { const logs: string[] = []; @Directive({ selector: '[some-dir]', host: { '[attr.first-name]': `'Hello, ' + (firstName ?? 'Frodo') + '!'`, '(click)': `logLastName(lastName ?? lastNameFallback ?? 'unknown')`, }, standalone: false, }) class Dir { firstName: string | null = null; lastName: string | null = null; lastNameFallback = 'Baggins'; logLastName(name: string) { logs.push(name); } } @Component({ template: `<button some-dir>Click me</button>`, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); button.click(); fixture.detectChanges(); expect(button.getAttribute('first-name')).toBe('Hello, Frodo!'); expect(logs).toEqual(['Baggins']); }); it('should render SVG nodes placed inside ng-template', () => { @Component({ template: ` <svg> <ng-template [ngIf]="condition"> <text>Hello</text> </ng-template> </svg> `, standalone: false, }) class MyComp { condition = true; } TestBed.configureTestingModule({declarations: [MyComp], imports: [CommonModule]}); const fixture = TestBed.createComponent(MyComp); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toContain('<text>Hello</text>'); }); it('should handle shorthand property declarations in templates', () => { @Directive({ selector: '[my-dir]', standalone: false, }) class Dir { @Input('my-dir') value: any; } @Component({ template: `<div [my-dir]="{a, b: 2, someProp}"></div>`, standalone: false, }) class App { @ViewChild(Dir) directive!: Dir; a = 1; someProp = 3; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.directive.value).toEqual({a: 1, b: 2, someProp: 3}); }); it('should handle numeric separators in templates', () => { @Component({ template: 'Balance: ${{ 1_000_000 * multiplier }}', standalone: false, }) class App { multiplier = 5; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Balance: $5000000'); }); it('should handle calls to a safe access in templates', () => { @Component({ template: ` <span>Hello, {{ (person?.getName() || 'unknown') }}!</span> `, standalone: false, }) class App { person = null; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Hello, unknown!'); });
{ "end_byte": 79345, "start_byte": 72491, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/integration_spec.ts" }
angular/packages/core/test/acceptance/integration_spec.ts_79349_86206
it('should handle nested calls to a safe access methods in templates', () => { const log: string[] = []; class Person { constructor( public name: string, public title: string, ) {} getName(includeTitle: boolean | undefined) { log.push(`person.getName(${includeTitle})`); return includeTitle ? `${this.title} ${this.name}` : this.name; } } @Component({ template: ` <span>Hello, {{ (person?.getName(getConfig('showTitle')?.enabled ?? getDefaultShowTitle()) ?? getFallbackName()) }}!</span> `, standalone: false, }) class App { person: Person | null = null; showTitle: boolean | null = null; getConfig(name: string): {enabled: boolean} | null { log.push(`getConfig(${name})`); return this.showTitle !== null ? {enabled: this.showTitle} : null; } getDefaultShowTitle(): boolean { log.push(`getDefaultShowTitle()`); return false; } getFallbackName(): string { log.push(`getFallbackName()`); return 'unknown'; } } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(/* checkNoChanges */ false); expect(fixture.nativeElement.textContent).toContain('Hello, unknown!'); expect(log).toEqual(['getFallbackName()']); log.length = 0; fixture.componentInstance.person = new Person('Penelope', 'Lady'); fixture.detectChanges(/* checkNoChanges */ false); expect(fixture.nativeElement.textContent).toContain('Hello, Penelope!'); expect(log).toEqual(['getConfig(showTitle)', 'getDefaultShowTitle()', 'person.getName(false)']); log.length = 0; fixture.componentInstance.showTitle = true; fixture.detectChanges(/* checkNoChanges */ false); expect(fixture.nativeElement.textContent).toContain('Hello, Lady Penelope!'); expect(log).toEqual(['getConfig(showTitle)', 'person.getName(true)']); log.length = 0; fixture.componentInstance.showTitle = false; fixture.detectChanges(/* checkNoChanges */ false); expect(fixture.nativeElement.textContent).toContain('Hello, Penelope!'); expect(log).toEqual(['getConfig(showTitle)', 'person.getName(false)']); log.length = 0; }); it('should remove child LView from the registry when the root view is destroyed', () => { @Component({ template: '<child></child>', standalone: false, }) class App {} @Component({ selector: 'child', template: '<grand-child></grand-child>', standalone: false, }) class Child {} @Component({ selector: 'grand-child', template: '', standalone: false, }) class GrandChild {} TestBed.configureTestingModule({declarations: [App, Child, GrandChild]}); const fixture = TestBed.createComponent(App); const grandChild = fixture.debugElement.query(By.directive(GrandChild)).componentInstance; fixture.detectChanges(); const leafLView = readPatchedLView(grandChild)!; const lViewIds: number[] = []; let current: LView | LContainer | null = leafLView; while (current) { isLView(current) && lViewIds.push(current[ID]); current = current[PARENT]; } // We expect 3 views: `GrandChild`, `Child` and `App`. expect(lViewIds).toEqual([leafLView[ID], leafLView[ID] - 1, leafLView[ID] - 2]); expect(lViewIds.every((id) => getLViewById(id) !== null)).toBe(true); fixture.destroy(); // Expect all 3 views to be removed from the registry once the root is destroyed. expect(lViewIds.map(getLViewById)).toEqual([null, null, null]); }); it('should handle content inside <template> elements', () => { @Component({ template: '<template><strong>Hello</strong><em>World</em></template>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const template: HTMLTemplateElement = fixture.nativeElement.querySelector('template'); // `content` won't exist in browsers that don't support `template`. const root = template.content || template; expect(root.childNodes.length).toBe(2); expect(root.childNodes[0].textContent).toBe('Hello'); expect((root.childNodes[0] as HTMLElement).tagName).toBe('STRONG'); expect(root.childNodes[1].textContent).toBe('World'); expect((root.childNodes[1] as HTMLElement).tagName).toBe('EM'); }); it('should be able to insert and remove elements inside <template>', () => { @Component({ template: '<template><strong *ngIf="render">Hello</strong></template>', standalone: false, }) class App { render = true; } TestBed.configureTestingModule({declarations: [App], imports: [CommonModule]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const template: HTMLTemplateElement = fixture.nativeElement.querySelector('template'); // `content` won't exist in browsers that don't support `template`. const root = template.content || template; expect(root.querySelector('strong')).toBeTruthy(); fixture.componentInstance.render = false; fixture.detectChanges(); expect(root.querySelector('strong')).toBeFalsy(); fixture.componentInstance.render = true; fixture.detectChanges(); expect(root.querySelector('strong')).toBeTruthy(); }); it('should handle data binding inside <template> elements', () => { @Component({ template: '<template><strong>Hello {{name}}</strong></template>', standalone: false, }) class App { name = 'Bilbo'; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const template: HTMLTemplateElement = fixture.nativeElement.querySelector('template'); // `content` won't exist in browsers that don't support `template`. const root = template.content || template; const strong = root.querySelector('strong')!; expect(strong.textContent).toBe('Hello Bilbo'); fixture.componentInstance.name = 'Frodo'; fixture.detectChanges(); expect(strong.textContent).toBe('Hello Frodo'); }); it('should not throw for a non-null assertion after a safe access', () => { @Component({ template: ` {{ val?.foo!.bar }} {{ val?.[0].foo!.bar }} {{ foo(val)?.foo!.bar }} {{ $any(val)?.foo!.bar }} `, standalone: false, }) class Comp { val: any = null; foo(val: unknown) { return val; } } TestBed.configureTestingModule({declarations: [Comp]}); expect(() => TestBed.createComponent(Comp).detectChanges()).not.toThrow(); });
{ "end_byte": 86206, "start_byte": 79349, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/integration_spec.ts" }
angular/packages/core/test/acceptance/integration_spec.ts_86210_95060
describe('tView.firstUpdatePass', () => { function isFirstUpdatePass() { const lView = getLView(); const tView = lView[TVIEW]; return tView.firstUpdatePass; } function assertAttrValues(element: Element, value: string) { expect(element.getAttribute('data-comp')).toEqual(value); expect(element.getAttribute('data-dir')).toEqual(value); } it('should be marked with `firstUpdatePass` up until the template and host bindings are evaluated', () => { @Directive({ selector: '[dir]', standalone: false, }) class Dir { @HostBinding('attr.data-dir') get text() { return isFirstUpdatePass() ? 'first-update-pass' : 'post-update-pass'; } } @Component({ template: '<div [attr.data-comp]="text" dir></div>', standalone: false, }) class Cmp { get text() { return isFirstUpdatePass() ? 'first-update-pass' : 'post-update-pass'; } } TestBed.configureTestingModule({ declarations: [Cmp, Dir], }); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(false); const element = fixture.nativeElement.querySelector('div')!; assertAttrValues(element, 'first-update-pass'); fixture.detectChanges(false); assertAttrValues(element, 'post-update-pass'); }); it('tView.firstUpdatePass should be applied immediately after the first embedded view is processed', () => { @Directive({ selector: '[dir]', standalone: false, }) class Dir { @HostBinding('attr.data-dir') get text() { return isFirstUpdatePass() ? 'first-update-pass' : 'post-update-pass'; } } @Component({ template: ` <div *ngFor="let item of items" dir [attr.data-comp]="text"> ... </div> `, standalone: false, }) class Cmp { items = [1, 2, 3]; get text() { return isFirstUpdatePass() ? 'first-update-pass' : 'post-update-pass'; } } TestBed.configureTestingModule({ declarations: [Cmp, Dir], }); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(false); const elements = fixture.nativeElement.querySelectorAll('div'); assertAttrValues(elements[0], 'first-update-pass'); assertAttrValues(elements[1], 'post-update-pass'); assertAttrValues(elements[2], 'post-update-pass'); fixture.detectChanges(false); assertAttrValues(elements[0], 'post-update-pass'); assertAttrValues(elements[1], 'post-update-pass'); assertAttrValues(elements[2], 'post-update-pass'); }); }); describe('animations', () => { it('should apply triggers for a list of items when they are sorted and reSorted', fakeAsync(() => { interface Item { value: any; id: number; } @Component({ template: ` <div *ngIf="showWarningMessage; else listOfItems"> Nooo! </div> <ng-template #listOfItems> <animation-comp *ngFor="let item of items; trackBy: itemTrackFn"> {{ item.value }} </animation-comp> </ng-template> `, standalone: false, }) class Cmp { showWarningMessage = false; items: Item[] = [ {value: 1, id: 1}, {value: 2, id: 2}, {value: 3, id: 3}, {value: 4, id: 4}, {value: 5, id: 5}, ]; itemTrackFn(value: Item) { return value.id; } } @Component({ selector: 'animation-comp', animations: [ trigger('host', [ state('void', style({height: '0px'})), transition('* => *', [animate('1s')]), ]), ], template: ` <ng-content></ng-content> `, standalone: false, }) class AnimationComp { @HostBinding('@host') public hostState = ''; @HostListener('@host.start', ['$event']) onLeaveStart(event: AnimationEvent) { // we just want to register the listener } } TestBed.configureTestingModule({ declarations: [Cmp, AnimationComp], providers: [{provide: AnimationDriver, useClass: MockAnimationDriver}], }); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); let elements = queryAll(fixture.nativeElement, 'animation-comp'); expect(elements.length).toEqual(5); expect(elements.map((e) => e.textContent?.trim())).toEqual(['1', '2', '3', '4', '5']); const items = fixture.componentInstance.items; arraySwap(items, 2, 0); // 3 2 1 4 5 arraySwap(items, 2, 1); // 3 1 2 4 5 const first = items.shift()!; items.push(first); // 1 2 4 5 3 fixture.detectChanges(); elements = queryAll(fixture.nativeElement, 'animation-comp'); expect(elements.length).toEqual(5); expect(elements.map((e) => e.textContent?.trim())).toEqual(['1', '2', '4', '5', '3']); completeAnimations(); fixture.componentInstance.showWarningMessage = true; fixture.detectChanges(); completeAnimations(); elements = queryAll(fixture.nativeElement, 'animation-comp'); expect(elements.length).toEqual(0); expect(fixture.nativeElement.textContent.trim()).toEqual('Nooo!'); fixture.componentInstance.showWarningMessage = false; fixture.detectChanges(); elements = queryAll(fixture.nativeElement, 'animation-comp'); expect(elements.length).toEqual(5); })); it('should insert and remove views in the correct order when animations are present', fakeAsync(() => { @Component({ animations: [ trigger('root', [transition('* => *', [])]), trigger('outer', [transition('* => *', [])]), trigger('inner', [transition('* => *', [])]), ], template: ` <div *ngIf="showRoot" (@root.start)="track('root', $event)" @root> <div *ngIf="showIfContents; else innerCompList" (@outer.start)="track('outer', $event)" @outer> Nooo! </div> <ng-template #innerCompList> <inner-comp *ngFor="let item of items; trackBy: itemTrackFn" (@inner.start)="track('inner', $event)" @inner> {{ item.value }} </inner-comp> </ng-template> </div> `, standalone: false, }) class Cmp { showRoot = true; showIfContents = true; items = [1]; log: string[] = []; track(name: string, event: AnimationEvent) { this.log.push(name); } } @Component({ selector: 'inner-comp', animations: [trigger('host', [transition('* => *', [])])], template: ` <ng-content></ng-content> `, standalone: false, }) class InnerComp { @HostBinding('@host') public hostState = ''; constructor(@Inject(Cmp) private parent: Cmp) {} @HostListener('@host.start', ['$event']) onLeaveStart(event: AnimationEvent) { this.parent.log.push('host'); } } TestBed.configureTestingModule({ declarations: [Cmp, InnerComp], providers: [{provide: AnimationDriver, useClass: MockAnimationDriver}], }); const fixture = TestBed.createComponent(Cmp); fixture.detectChanges(); completeAnimations(); const comp = fixture.componentInstance; expect(comp.log).toEqual([ 'root', // insertion of the inner-comp content 'outer', // insertion of the default ngIf ]); comp.log = []; comp.showIfContents = false; fixture.detectChanges(); completeAnimations(); expect(comp.log).toEqual([ 'host', // insertion of the inner-comp content 'outer', // insertion of the template into the ngIf 'inner', // insertion of the inner comp element ]); comp.log = []; comp.showRoot = false; fixture.detectChanges(); completeAnimations(); expect(comp.log).toEqual([ 'root', // removal the root div container 'host', // removal of the inner-comp content 'inner', // removal of the inner comp element ]); })); }); }); function completeAnimations() { flushMicrotasks(); const log = MockAnimationDriver.log as MockAnimationPlayer[]; log.forEach((player) => player.finish()); flushMicrotasks(); } function arraySwap(arr: any[], indexA: number, indexB: number): void { const item = arr[indexA]; arr[indexA] = arr[indexB]; arr[indexB] = item; }
{ "end_byte": 95060, "start_byte": 86210, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/integration_spec.ts" }
angular/packages/core/test/acceptance/integration_spec.ts_95062_95317
/** * Queries the provided `root` element for sub elements by the selector and casts the result as an * array of elements */ function queryAll(root: HTMLElement, selector: string): HTMLElement[] { return Array.from(root.querySelectorAll(selector)); }
{ "end_byte": 95317, "start_byte": 95062, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/integration_spec.ts" }
angular/packages/core/test/acceptance/property_binding_spec.ts_0_5952
/** * @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 {state, style, trigger} from '@angular/animations'; import {CommonModule} from '@angular/common'; import {Component, Directive, EventEmitter, Input, Output, ViewContainerRef} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By, DomSanitizer, SafeUrl} from '@angular/platform-browser'; describe('property bindings', () => { it('should support bindings to properties', () => { @Component({ template: `<span [id]="id"></span>`, standalone: false, }) class Comp { id: string | undefined; } TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); const spanEl = fixture.nativeElement.querySelector('span'); expect(spanEl.id).toBeFalsy(); fixture.componentInstance.id = 'testId'; fixture.detectChanges(); expect(spanEl.id).toBe('testId'); }); it('should update bindings when value changes', () => { @Component({ template: `<a [title]="title"></a>`, standalone: false, }) class Comp { title = 'Hello'; } TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); let a = fixture.debugElement.query(By.css('a')).nativeElement; expect(a.title).toBe('Hello'); fixture.componentInstance.title = 'World'; fixture.detectChanges(); expect(a.title).toBe('World'); }); it('should not update bindings when value does not change', () => { @Component({ template: `<a [title]="title"></a>`, standalone: false, }) class Comp { title = 'Hello'; } TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); let a = fixture.debugElement.query(By.css('a')).nativeElement; expect(a.title).toBe('Hello'); fixture.detectChanges(); expect(a.title).toBe('Hello'); }); it('should bind to properties whose names do not correspond to their attribute names', () => { @Component({ template: '<label [for]="forValue"></label>', standalone: false, }) class MyComp { forValue?: string; } TestBed.configureTestingModule({declarations: [MyComp]}); const fixture = TestBed.createComponent(MyComp); const labelNode = fixture.debugElement.query(By.css('label')); fixture.componentInstance.forValue = 'some-input'; fixture.detectChanges(); expect(labelNode.nativeElement.getAttribute('for')).toBe('some-input'); fixture.componentInstance.forValue = 'some-textarea'; fixture.detectChanges(); expect(labelNode.nativeElement.getAttribute('for')).toBe('some-textarea'); }); it( 'should not map properties whose names do not correspond to their attribute names, ' + 'if they correspond to inputs', () => { @Component({ template: '', selector: 'my-comp', standalone: false, }) class MyComp { @Input() for!: string; } @Component({ template: '<my-comp [for]="forValue"></my-comp>', standalone: false, }) class App { forValue?: string; } TestBed.configureTestingModule({declarations: [App, MyComp]}); const fixture = TestBed.createComponent(App); const myCompNode = fixture.debugElement.query(By.directive(MyComp)); fixture.componentInstance.forValue = 'hello'; fixture.detectChanges(); expect(myCompNode.nativeElement.getAttribute('for')).toBeFalsy(); expect(myCompNode.componentInstance.for).toBe('hello'); fixture.componentInstance.forValue = 'hej'; fixture.detectChanges(); expect(myCompNode.nativeElement.getAttribute('for')).toBeFalsy(); expect(myCompNode.componentInstance.for).toBe('hej'); }, ); it('should use the sanitizer in bound properties', () => { @Component({ template: ` <a [href]="url"> `, standalone: false, }) class App { url: string | SafeUrl = 'javascript:alert("haha, I am taking over your computer!!!");'; } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const a = fixture.nativeElement.querySelector('a'); expect(a.href.indexOf('unsafe:')).toBe(0); const domSanitzer: DomSanitizer = TestBed.inject(DomSanitizer); fixture.componentInstance.url = domSanitzer.bypassSecurityTrustUrl( 'javascript:alert("the developer wanted this");', ); fixture.detectChanges(); expect(a.href.indexOf('unsafe:')).toBe(-1); }); it('should not stringify non-string values', () => { @Component({ template: `<input [required]="isRequired"/>`, standalone: false, }) class Comp { isRequired = false; } TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); expect(fixture.debugElement.query(By.css('input')).nativeElement.required).toBe(false); }); it('should support interpolation for properties', () => { @Component({ template: `<span id="{{'_' + id + '_'}}"></span>`, standalone: false, }) class Comp { id: string | undefined; } TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); const spanEl = fixture.nativeElement.querySelector('span'); fixture.componentInstance.id = 'testId'; fixture.detectChanges(); expect(spanEl.id).toBe('_testId_'); fixture.componentInstance.id = 'otherId'; fixture.detectChanges(); expect(spanEl.id).toBe('_otherId_'); });
{ "end_byte": 5952, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/property_binding_spec.ts" }
angular/packages/core/test/acceptance/property_binding_spec.ts_5956_14091
describe('input properties', () => { @Directive({ selector: '[myButton]', standalone: false, }) class MyButton { @Input() disabled: boolean | undefined; } @Directive({ selector: '[otherDir]', standalone: false, }) class OtherDir { @Input() id: number | undefined; @Output('click') clickStream = new EventEmitter<void>(); } @Directive({ selector: '[otherDisabledDir]', standalone: false, }) class OtherDisabledDir { @Input() disabled: boolean | undefined; } @Directive({ selector: '[idDir]', standalone: false, }) class IdDir { @Input('id') idNumber: string | undefined; } it('should check input properties before setting (directives)', () => { @Component({ template: `<button myButton otherDir [id]="id" [disabled]="isDisabled">Click me</button>`, standalone: false, }) class App { id = 0; isDisabled = true; } TestBed.configureTestingModule({declarations: [App, MyButton, OtherDir]}); const fixture = TestBed.createComponent(App); const button = fixture.debugElement.query(By.directive(MyButton)).injector.get(MyButton); const otherDir = fixture.debugElement.query(By.directive(OtherDir)).injector.get(OtherDir); const buttonEl = fixture.nativeElement.children[0]; fixture.detectChanges(); expect(buttonEl.getAttribute('mybutton')).toBe(''); expect(buttonEl.getAttribute('otherdir')).toBe(''); expect(buttonEl.hasAttribute('id')).toBe(false); expect(buttonEl.hasAttribute('disabled')).toBe(false); expect(button.disabled).toEqual(true); expect(otherDir.id).toEqual(0); fixture.componentInstance.isDisabled = false; fixture.componentInstance.id = 1; fixture.detectChanges(); expect(buttonEl.getAttribute('mybutton')).toBe(''); expect(buttonEl.getAttribute('otherdir')).toBe(''); expect(buttonEl.hasAttribute('id')).toBe(false); expect(buttonEl.hasAttribute('disabled')).toBe(false); expect(button.disabled).toEqual(false); expect(otherDir.id).toEqual(1); }); it('should support mixed element properties and input properties', () => { @Component({ template: `<button myButton [id]="id" [disabled]="isDisabled">Click me</button>`, standalone: false, }) class App { isDisabled = true; id = 0; } TestBed.configureTestingModule({declarations: [App, MyButton]}); const fixture = TestBed.createComponent(App); const button = fixture.debugElement.query(By.directive(MyButton)).injector.get(MyButton); const buttonEl = fixture.nativeElement.children[0]; fixture.detectChanges(); expect(buttonEl.getAttribute('id')).toBe('0'); expect(buttonEl.hasAttribute('disabled')).toBe(false); expect(button.disabled).toEqual(true); fixture.componentInstance.isDisabled = false; fixture.componentInstance.id = 1; fixture.detectChanges(); expect(buttonEl.getAttribute('id')).toBe('1'); expect(buttonEl.hasAttribute('disabled')).toBe(false); expect(button.disabled).toEqual(false); }); it('should check that property is not an input property before setting (component)', () => { @Component({ selector: 'comp', template: '', standalone: false, }) class Comp { @Input() id: number | undefined; } @Component({ template: `<comp [id]="id"></comp>`, standalone: false, }) class App { id = 1; } TestBed.configureTestingModule({declarations: [App, Comp]}); const fixture = TestBed.createComponent(App); const compDebugEl = fixture.debugElement.query(By.directive(Comp)); fixture.detectChanges(); expect(compDebugEl.nativeElement.hasAttribute('id')).toBe(false); expect(compDebugEl.componentInstance.id).toEqual(1); fixture.componentInstance.id = 2; fixture.detectChanges(); expect(compDebugEl.nativeElement.hasAttribute('id')).toBe(false); expect(compDebugEl.componentInstance.id).toEqual(2); }); it('should support two input properties with the same name', () => { @Component({ template: `<button myButton otherDisabledDir [disabled]="isDisabled">Click me</button>`, standalone: false, }) class App { isDisabled = true; } TestBed.configureTestingModule({declarations: [App, MyButton, OtherDisabledDir]}); const fixture = TestBed.createComponent(App); const button = fixture.debugElement.query(By.directive(MyButton)).injector.get(MyButton); const otherDisabledDir = fixture.debugElement .query(By.directive(OtherDisabledDir)) .injector.get(OtherDisabledDir); const buttonEl = fixture.nativeElement.children[0]; fixture.detectChanges(); expect(buttonEl.hasAttribute('disabled')).toBe(false); expect(button.disabled).toEqual(true); expect(otherDisabledDir.disabled).toEqual(true); fixture.componentInstance.isDisabled = false; fixture.detectChanges(); expect(buttonEl.hasAttribute('disabled')).toBe(false); expect(button.disabled).toEqual(false); expect(otherDisabledDir.disabled).toEqual(false); }); it('should set input property if there is an output first', () => { @Component({ template: `<button otherDir [id]="id" (click)="onClick()">Click me</button>`, standalone: false, }) class App { id = 1; counter = 0; onClick = () => this.counter++; } TestBed.configureTestingModule({declarations: [App, OtherDir]}); const fixture = TestBed.createComponent(App); const otherDir = fixture.debugElement.query(By.directive(OtherDir)).injector.get(OtherDir); const buttonEl = fixture.nativeElement.children[0]; fixture.detectChanges(); expect(buttonEl.hasAttribute('id')).toBe(false); expect(otherDir.id).toEqual(1); otherDir.clickStream.next(); expect(fixture.componentInstance.counter).toEqual(1); fixture.componentInstance.id = 2; fixture.detectChanges(); expect(otherDir.id).toEqual(2); }); it('should support unrelated element properties at same index in if-else block', () => { @Component({ template: ` <button idDir [id]="id1">Click me</button> <button *ngIf="condition" [id]="id2">Click me too (2)</button> <button *ngIf="!condition" otherDir [id]="id3">Click me too (3)</button> `, standalone: false, }) class App { condition = true; id1 = 'one'; id2 = 'two'; id3 = 3; } TestBed.configureTestingModule({ declarations: [App, IdDir, OtherDir], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); let buttonElements = fixture.nativeElement.querySelectorAll('button'); const idDir = fixture.debugElement.query(By.directive(IdDir)).injector.get(IdDir); expect(buttonElements.length).toBe(2); expect(buttonElements[0].hasAttribute('id')).toBe(false); expect(buttonElements[1].getAttribute('id')).toBe('two'); expect(buttonElements[1].textContent).toBe('Click me too (2)'); expect(idDir.idNumber).toBe('one'); fixture.componentInstance.condition = false; fixture.componentInstance.id1 = 'four'; fixture.detectChanges(); const otherDir = fixture.debugElement.query(By.directive(OtherDir)).injector.get(OtherDir); buttonElements = fixture.nativeElement.querySelectorAll('button'); expect(buttonElements.length).toBe(2); expect(buttonElements[0].hasAttribute('id')).toBe(false); expect(buttonElements[1].hasAttribute('id')).toBe(false); expect(buttonElements[1].textContent).toBe('Click me too (3)'); expect(idDir.idNumber).toBe('four'); expect(otherDir.id).toBe(3); }); });
{ "end_byte": 14091, "start_byte": 5956, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/property_binding_spec.ts" }
angular/packages/core/test/acceptance/property_binding_spec.ts_14095_22446
describe('attributes and input properties', () => { @Directive({ selector: '[myDir]', exportAs: 'myDir', standalone: false, }) class MyDir { @Input() role: string | undefined; @Input('dir') direction: string | undefined; @Output('change') changeStream = new EventEmitter<void>(); } @Directive({ selector: '[myDirB]', standalone: false, }) class MyDirB { @Input('role') roleB: string | undefined; } it('should set input property based on attribute if existing', () => { @Component({ template: `<div role="button" myDir></div>`, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, MyDir]}); const fixture = TestBed.createComponent(App); const myDir = fixture.debugElement.query(By.directive(MyDir)).injector.get(MyDir); const divElement = fixture.nativeElement.children[0]; fixture.detectChanges(); expect(divElement.getAttribute('role')).toBe('button'); expect(divElement.getAttribute('mydir')).toBe(''); expect(myDir.role).toEqual('button'); }); it('should set input property and attribute if both defined', () => { @Component({ template: `<div role="button" [role]="role" myDir></div>`, standalone: false, }) class App { role = 'listbox'; } TestBed.configureTestingModule({declarations: [App, MyDir]}); const fixture = TestBed.createComponent(App); const myDir = fixture.debugElement.query(By.directive(MyDir)).injector.get(MyDir); const divElement = fixture.nativeElement.children[0]; fixture.detectChanges(); expect(divElement.getAttribute('role')).toBe('button'); expect(myDir.role).toEqual('listbox'); fixture.componentInstance.role = 'button'; fixture.detectChanges(); expect(myDir.role).toEqual('button'); }); it('should set two directive input properties based on same attribute', () => { @Component({ template: `<div role="button" myDir myDirB></div>`, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, MyDir, MyDirB]}); const fixture = TestBed.createComponent(App); const myDir = fixture.debugElement.query(By.directive(MyDir)).injector.get(MyDir); const myDirB = fixture.debugElement.query(By.directive(MyDirB)).injector.get(MyDirB); const divElement = fixture.nativeElement.children[0]; fixture.detectChanges(); expect(divElement.getAttribute('role')).toBe('button'); expect(myDir.role).toEqual('button'); expect(myDirB.roleB).toEqual('button'); }); it('should process two attributes on same directive', () => { @Component({ template: `<div role="button" dir="rtl" myDir></div>`, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, MyDir]}); const fixture = TestBed.createComponent(App); const myDir = fixture.debugElement.query(By.directive(MyDir)).injector.get(MyDir); const divElement = fixture.nativeElement.children[0]; fixture.detectChanges(); expect(divElement.getAttribute('role')).toBe('button'); expect(divElement.getAttribute('dir')).toBe('rtl'); expect(myDir.role).toEqual('button'); expect(myDir.direction).toEqual('rtl'); }); it('should process attributes and outputs properly together', () => { @Component({ template: `<div role="button" (change)="onChange()" myDir></div>`, standalone: false, }) class App { counter = 0; onChange = () => this.counter++; } TestBed.configureTestingModule({declarations: [App, MyDir]}); const fixture = TestBed.createComponent(App); const myDir = fixture.debugElement.query(By.directive(MyDir)).injector.get(MyDir); const divElement = fixture.nativeElement.children[0]; fixture.detectChanges(); expect(divElement.getAttribute('role')).toBe('button'); expect(myDir.role).toEqual('button'); myDir.changeStream.next(); expect(fixture.componentInstance.counter).toEqual(1); }); it('should process attributes properly for directives with later indices', () => { @Component({ template: ` <div role="button" dir="rtl" myDir></div> <div role="listbox" myDirB></div> `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, MyDir, MyDirB]}); const fixture = TestBed.createComponent(App); const myDir = fixture.debugElement.query(By.directive(MyDir)).injector.get(MyDir); const myDirB = fixture.debugElement.query(By.directive(MyDirB)).injector.get(MyDirB); const fixtureElements = fixture.nativeElement.children; // TODO: Use destructuring once Domino supports native ES2015, or when jsdom is used. const buttonEl = fixtureElements[0]; const listboxEl = fixtureElements[1]; fixture.detectChanges(); expect(buttonEl.getAttribute('role')).toBe('button'); expect(buttonEl.getAttribute('dir')).toBe('rtl'); expect(listboxEl.getAttribute('role')).toBe('listbox'); expect(myDir.role).toEqual('button'); expect(myDir.direction).toEqual('rtl'); expect(myDirB.roleB).toEqual('listbox'); }); it('should support attributes at same index inside an if-else block', () => { @Component({ template: ` <div role="listbox" myDir></div> <div role="button" myDirB *ngIf="condition"></div> <div role="menu" *ngIf="!condition"></div> `, standalone: false, }) class App { condition = true; } TestBed.configureTestingModule({declarations: [App, MyDir, MyDirB], imports: [CommonModule]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const myDir = fixture.debugElement.query(By.directive(MyDir)).injector.get(MyDir); const myDirB = fixture.debugElement.query(By.directive(MyDirB)).injector.get(MyDirB); let divElements = fixture.nativeElement.querySelectorAll('div'); expect(divElements.length).toBe(2); expect(divElements[0].getAttribute('role')).toBe('listbox'); expect(divElements[1].getAttribute('role')).toBe('button'); expect(myDir.role).toEqual('listbox'); expect(myDirB.roleB).toEqual('button'); expect((myDirB as any).role).toBeUndefined(); fixture.componentInstance.condition = false; fixture.detectChanges(); divElements = fixture.nativeElement.querySelectorAll('div'); expect(divElements.length).toBe(2); expect(divElements[0].getAttribute('role')).toBe('listbox'); expect(divElements[1].getAttribute('role')).toBe('menu'); expect(myDir.role).toEqual('listbox'); expect(myDirB.roleB).toEqual('button'); }); it('should process attributes properly inside a for loop', () => { @Component({ selector: 'comp', template: `<div role="button" myDir #dir="myDir"></div>role: {{dir.role}}`, standalone: false, }) class Comp {} @Component({ template: ` <comp *ngFor="let i of [0, 1]"></comp> `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, MyDir, Comp], imports: [CommonModule]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.children.length).toBe(2); const compElements = fixture.nativeElement.children; // TODO: Use destructuring once Domino supports native ES2015, or when jsdom is used. const comp1 = compElements[0]; const comp2 = compElements[1]; expect(comp1.tagName).toBe('COMP'); expect(comp2.tagName).toBe('COMP'); expect(comp1.children[0].tagName).toBe('DIV'); expect(comp1.children[0].getAttribute('role')).toBe('button'); expect(comp1.textContent).toBe('role: button'); expect(comp2.children[0].tagName).toBe('DIV'); expect(comp2.children[0].getAttribute('role')).toBe('button'); expect(comp2.textContent).toBe('role: button'); }); });
{ "end_byte": 22446, "start_byte": 14095, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/property_binding_spec.ts" }
angular/packages/core/test/acceptance/property_binding_spec.ts_22450_24150
it('should not throw on synthetic property bindings when a directive on the same element injects ViewContainerRef', () => { @Component({ selector: 'my-comp', template: '', animations: [trigger('trigger', [state('void', style({opacity: 0}))])], host: {'[@trigger]': '"void"'}, standalone: false, }) class MyComp {} @Directive({ selector: '[my-dir]', standalone: false, }) class MyDir { constructor(public viewContainerRef: ViewContainerRef) {} } @Component({ template: '<my-comp my-dir></my-comp>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, MyDir, MyComp]}); expect(() => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); }).not.toThrow(); }); it('should allow quoted binding syntax inside property binding', () => { @Component({ template: `<span [id]="'{{ id }}'"></span>`, standalone: false, }) class Comp {} TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('span').id).toBe('{{ id }}'); }); it('should allow quoted binding syntax with escaped quotes inside property binding', () => { @Component({ template: `<span [id]="'{{ \\' }}'"></span>`, standalone: false, }) class Comp {} TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('span').id).toBe("{{ ' }}"); }); });
{ "end_byte": 24150, "start_byte": 22450, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/property_binding_spec.ts" }
angular/packages/core/test/acceptance/di_forward_ref_spec.ts_0_2639
/** * @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, forwardRef, Host, Inject, ViewChild} from '@angular/core'; import {TestBed} from '@angular/core/testing'; // **NOTE**: More details on why tests relying on `forwardRef` are put into this // file can be found in the `BUILD.bazel` file declaring the forward ref test target. describe('di with forwardRef', () => { describe('directive injection', () => { it('should throw if directives try to inject each other', () => { @Directive({ selector: '[dirB]', standalone: false, }) class DirectiveB { constructor(@Inject(forwardRef(() => DirectiveA)) siblingDir: DirectiveA) {} } @Directive({ selector: '[dirA]', standalone: false, }) class DirectiveA { constructor(siblingDir: DirectiveB) {} } @Component({ template: '<div dirA dirB></div>', standalone: false, }) class MyComp {} TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp]}); expect(() => TestBed.createComponent(MyComp)).toThrowError( 'NG0200: Circular dependency in DI detected for DirectiveA. Find more at https://angular.dev/errors/NG0200', ); }); describe('flags', () => { describe('@Host', () => { it('should find host component on the host itself', () => { @Directive({ selector: '[dirComp]', standalone: false, }) class DirectiveComp { constructor(@Inject(forwardRef(() => MyComp)) @Host() public comp: MyComp) {} } @Component({ selector: 'my-comp', template: '<div dirComp></div>', standalone: false, }) class MyComp { @ViewChild(DirectiveComp) dirComp!: DirectiveComp; } @Component({ template: '<my-comp></my-comp>', jit: true, standalone: false, }) class MyApp { @ViewChild(MyComp) myComp!: MyComp; } TestBed.configureTestingModule({declarations: [DirectiveComp, MyComp, MyApp]}); const fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); const myComp = fixture.componentInstance.myComp; const dirComp = myComp.dirComp; expect(dirComp.comp).toBe(myComp); }); }); }); }); });
{ "end_byte": 2639, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_forward_ref_spec.ts" }
angular/packages/core/test/acceptance/destroy_ref_spec.ts_0_8477
/** * @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, createEnvironmentInjector, DestroyRef, Directive, EnvironmentInjector, inject, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; describe('DestroyRef', () => { describe('for environnement injector', () => { it('should inject cleanup context in services', () => { let destroyed = false; const envInjector = createEnvironmentInjector([], TestBed.inject(EnvironmentInjector)); envInjector.get(DestroyRef).onDestroy(() => (destroyed = true)); expect(destroyed).toBe(false); envInjector.destroy(); expect(destroyed).toBe(true); }); it('should allow removal of destroy callbacks', () => { let destroyed = false; const envInjector = createEnvironmentInjector([], TestBed.inject(EnvironmentInjector)); const unRegFn = envInjector.get(DestroyRef).onDestroy(() => (destroyed = true)); expect(destroyed).toBe(false); // explicitly unregister before destroy unRegFn(); envInjector.destroy(); expect(destroyed).toBe(false); }); it('should removal single destroy callback if many identical ones are registered', () => { let onDestroyCalls = 0; const onDestroyCallback = () => onDestroyCalls++; const envInjector = createEnvironmentInjector([], TestBed.inject(EnvironmentInjector)); const destroyRef = envInjector.get(DestroyRef); // Register the same fn 3 times: const unregFn = destroyRef.onDestroy(onDestroyCallback); destroyRef.onDestroy(onDestroyCallback); destroyRef.onDestroy(onDestroyCallback); // Unregister the fn 1 time: unregFn(); envInjector.destroy(); // Check that the callback was invoked only 2 times // (since we've unregistered one of the callbacks) expect(onDestroyCalls).toBe(2); }); it('should throw when trying to register destroy callback on destroyed injector', () => { const envInjector = createEnvironmentInjector([], TestBed.inject(EnvironmentInjector)); const destroyRef = envInjector.get(DestroyRef); envInjector.destroy(); expect(() => { destroyRef.onDestroy(() => {}); }).toThrowError('NG0205: Injector has already been destroyed.'); }); }); describe('for node injector', () => { it('should inject cleanup context in components', () => { let destroyed = false; @Component({ selector: 'test', standalone: true, template: ``, }) class TestCmp { constructor(destroyCtx: DestroyRef) { destroyCtx.onDestroy(() => (destroyed = true)); } } const fixture = TestBed.createComponent(TestCmp); expect(destroyed).toBe(false); fixture.componentRef.destroy(); expect(destroyed).toBe(true); }); it('should allow using cleanup context with views that store cleanup internally', () => { let destroyed = false; @Directive({ selector: '[withCleanup]', standalone: true, }) class WithCleanupDirective { constructor() { inject(DestroyRef).onDestroy(() => (destroyed = true)); } } @Component({ selector: 'test', standalone: true, imports: [WithCleanupDirective], // note: we are trying to register a LView-level cleanup _before_ TView-level one (event // listener) template: `<div withCleanup></div><button (click)="noop()"></button>`, }) class TestCmp { noop() {} } const fixture = TestBed.createComponent(TestCmp); fixture.detectChanges(); expect(destroyed).toBe(false); fixture.componentRef.destroy(); expect(destroyed).toBe(true); }); it('should scope destroy context to a view level', () => { let destroyed = false; @Directive({ selector: '[withCleanup]', standalone: true, }) class WithCleanupDirective { constructor() { inject(DestroyRef).onDestroy(() => (destroyed = true)); } } @Component({ selector: 'test', standalone: true, imports: [WithCleanupDirective, NgIf], template: `<ng-template [ngIf]="show"><div withCleanup></div></ng-template>`, }) class TestCmp { show = true; } const fixture = TestBed.createComponent(TestCmp); fixture.detectChanges(); expect(destroyed).toBe(false); fixture.componentInstance.show = false; fixture.detectChanges(); expect(destroyed).toBe(true); }); it('can inject into a child component', () => { const onDestroySpy = jasmine.createSpy('destroy spy'); @Component({ selector: 'child', standalone: true, template: '', }) class Child { constructor() { inject(DestroyRef).onDestroy(onDestroySpy); } } @Component({ standalone: true, imports: [Child, NgIf], template: '<child *ngIf="showChild"></child>', }) class Parent { showChild = true; } const fixture = TestBed.createComponent(Parent); fixture.detectChanges(); expect(onDestroySpy).not.toHaveBeenCalled(); fixture.componentInstance.showChild = false; fixture.detectChanges(); expect(onDestroySpy).toHaveBeenCalled(); }); }); it('should allow removal of view-scoped destroy callbacks', () => { let destroyed = false; @Component({ selector: 'test', standalone: true, template: ``, }) class TestCmp { unRegFn: () => void; constructor(destroyCtx: DestroyRef) { this.unRegFn = destroyCtx.onDestroy(() => (destroyed = true)); } } const fixture = TestBed.createComponent(TestCmp); expect(destroyed).toBe(false); // explicitly unregister before destroy fixture.componentInstance.unRegFn(); fixture.componentRef.destroy(); expect(destroyed).toBe(false); }); it('should removal single destroy callback if many identical ones are registered', () => { let onDestroyCalls = 0; const onDestroyCallback = () => onDestroyCalls++; @Component({ selector: 'test', standalone: true, template: ``, }) class TestCmp { unRegFn: () => void; constructor(destroyCtx: DestroyRef) { // Register the same fn 3 times: this.unRegFn = destroyCtx.onDestroy(onDestroyCallback); this.unRegFn = destroyCtx.onDestroy(onDestroyCallback); this.unRegFn = destroyCtx.onDestroy(onDestroyCallback); } } const fixture = TestBed.createComponent(TestCmp); expect(onDestroyCalls).toBe(0); // explicitly unregister 1-time before destroy fixture.componentInstance.unRegFn(); fixture.componentRef.destroy(); // Check that the callback was invoked only 2 times // (since we've unregistered one of the callbacks) expect(onDestroyCalls).toBe(2); }); it('should throw when trying to register destroy callback on destroyed LView', () => { @Component({ selector: 'test', standalone: true, template: ``, }) class TestCmp { constructor(public destroyRef: DestroyRef) {} } const fixture = TestBed.createComponent(TestCmp); const destroyRef = fixture.componentRef.instance.destroyRef; fixture.componentRef.destroy(); expect(() => { destroyRef.onDestroy(() => {}); }).toThrowError('NG0911: View has already been destroyed.'); }); it('should allow unregistration while destroying', () => { const destroyedLog: string[] = []; @Component({ selector: 'test', standalone: true, template: ``, }) class TestCmp { constructor(destroyCtx: DestroyRef) { const unregister = destroyCtx.onDestroy(() => { destroyedLog.push('first'); unregister(); }); destroyCtx.onDestroy(() => { destroyedLog.push('second'); }); } } const fixture = TestBed.createComponent(TestCmp); expect(destroyedLog).toEqual([]); fixture.componentRef.destroy(); expect(destroyedLog).toEqual(['first', 'second']); }); });
{ "end_byte": 8477, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/destroy_ref_spec.ts" }
angular/packages/core/test/acceptance/pure_function_spec.ts_0_7217
/** * @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, Input, QueryList, ViewChild, ViewChildren} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; describe('components using pure function instructions internally', () => { describe('with array literals', () => { @Component({ selector: 'my-comp', template: ``, standalone: false, }) class MyComp { @Input() names: string[] = []; } it('should support an array literal with a binding', () => { @Component({ template: ` <my-comp [names]="['Nancy', customName, 'Bess']"></my-comp> `, standalone: false, }) class App { showing = true; customName = 'Carson'; } TestBed.configureTestingModule({ declarations: [App, MyComp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const myComp = fixture.debugElement.query(By.directive(MyComp)).componentInstance; const firstArray = myComp.names; expect(firstArray).toEqual(['Nancy', 'Carson', 'Bess']); fixture.detectChanges(); expect(myComp.names).toEqual(['Nancy', 'Carson', 'Bess']); expect(firstArray).toBe(myComp.names); fixture.componentInstance.customName = 'Hannah'; fixture.detectChanges(); expect(myComp.names).toEqual(['Nancy', 'Hannah', 'Bess']); // Identity must change if binding changes expect(firstArray).not.toBe(myComp.names); // The property should not be set if the exp value is the same, so artificially // setting the property to ensure it's not overwritten. myComp.names = ['should not be overwritten']; fixture.detectChanges(); expect(myComp!.names).toEqual(['should not be overwritten']); }); it('should support array literals in dynamic views', () => { @Component({ template: ` <my-comp *ngIf="showing" [names]="['Nancy', customName, 'Bess']"></my-comp> `, standalone: false, }) class App { showing = true; customName = 'Carson'; } TestBed.configureTestingModule({ declarations: [App, MyComp], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const myComp = fixture.debugElement.query(By.directive(MyComp)).componentInstance; expect(myComp.names).toEqual(['Nancy', 'Carson', 'Bess']); }); it('should support multiple array literals passed through to one node', () => { @Component({ selector: 'many-prop-comp', template: ``, standalone: false, }) class ManyPropComp { @Input() names1: string[] = []; @Input() names2: string[] = []; } @Component({ template: ` <many-prop-comp [names1]="['Nancy', customName]" [names2]="[customName2]"> </many-prop-comp> `, standalone: false, }) class App { showing = true; customName = 'Carson'; customName2 = 'George'; } TestBed.configureTestingModule({ declarations: [App, ManyPropComp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const manyPropComp = fixture.debugElement.query(By.directive(ManyPropComp)).componentInstance; expect(manyPropComp!.names1).toEqual(['Nancy', 'Carson']); expect(manyPropComp!.names2).toEqual(['George']); fixture.componentInstance.customName = 'George'; fixture.componentInstance.customName2 = 'Carson'; fixture.detectChanges(); expect(manyPropComp!.names1).toEqual(['Nancy', 'George']); expect(manyPropComp!.names2).toEqual(['Carson']); }); it('should support an array literals inside fn calls', () => { @Component({ selector: 'parent-comp', template: ` <my-comp [names]="someFn(['Nancy', customName])"></my-comp> `, standalone: false, }) class ParentComp { customName = 'Bess'; someFn(arr: string[]): string[] { arr[0] = arr[0].toUpperCase(); return arr; } } @Component({ template: ` <parent-comp></parent-comp> <parent-comp></parent-comp> `, standalone: false, }) class App {} TestBed.configureTestingModule({ declarations: [App, MyComp, ParentComp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const myComps = fixture.debugElement .queryAll(By.directive(MyComp)) .map((f) => f.componentInstance); const firstArray = myComps[0].names; const secondArray = myComps[1].names; expect(firstArray).toEqual(['NANCY', 'Bess']); expect(secondArray).toEqual(['NANCY', 'Bess']); expect(firstArray).not.toBe(secondArray); fixture.detectChanges(); expect(firstArray).toEqual(['NANCY', 'Bess']); expect(secondArray).toEqual(['NANCY', 'Bess']); expect(firstArray).toBe(myComps[0].names); expect(secondArray).toBe(myComps[1].names); }); it('should support an array literal with more than 1 binding', () => { @Component({ template: ` <my-comp *ngIf="showing" [names]="['Nancy', customName, 'Bess', customName2]"></my-comp> `, standalone: false, }) class App { showing = true; customName = 'Carson'; customName2 = 'Hannah'; } TestBed.configureTestingModule({ declarations: [App, MyComp], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const myComp = fixture.debugElement.query(By.directive(MyComp)).componentInstance; const firstArray = myComp.names; expect(firstArray).toEqual(['Nancy', 'Carson', 'Bess', 'Hannah']); fixture.detectChanges(); expect(myComp.names).toEqual(['Nancy', 'Carson', 'Bess', 'Hannah']); expect(firstArray).toBe(myComp.names); fixture.componentInstance.customName = 'George'; fixture.detectChanges(); expect(myComp.names).toEqual(['Nancy', 'George', 'Bess', 'Hannah']); expect(firstArray).not.toBe(myComp.names); fixture.componentInstance.customName = 'Frank'; fixture.componentInstance.customName2 = 'Ned'; fixture.detectChanges(); expect(myComp.names).toEqual(['Nancy', 'Frank', 'Bess', 'Ned']); // The property should not be set if the exp value is the same, so artificially // setting the property to ensure it's not overwritten. myComp.names = ['should not be overwritten']; fixture.detectChanges(); expect(myComp.names).toEqual(['should not be overwritten']); });
{ "end_byte": 7217, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/pure_function_spec.ts" }
angular/packages/core/test/acceptance/pure_function_spec.ts_7223_11824
it('should work up to 8 bindings', () => { @Component({ template: ` <my-comp [names]="['a', 'b', 'c', 'd', 'e', 'f', 'g', v8]"></my-comp> <my-comp [names]="['a', 'b', 'c', 'd', 'e', 'f', v7, v8]"></my-comp> <my-comp [names]="['a', 'b', 'c', 'd', 'e', v6, v7, v8]"></my-comp> <my-comp [names]="['a', 'b', 'c', 'd', v5, v6, v7, v8]"></my-comp> <my-comp [names]="['a', 'b', 'c', v4, v5, v6, v7, v8]"></my-comp> <my-comp [names]="['a', 'b', v3, v4, v5, v6, v7, v8]"></my-comp> <my-comp [names]="['a', v2, v3, v4, v5, v6, v7, v8]"></my-comp> <my-comp [names]="[v1, v2, v3, v4, v5, v6, v7, v8]"></my-comp> `, standalone: false, }) class App { v1 = 'a'; v2 = 'b'; v3 = 'c'; v4 = 'd'; v5 = 'e'; v6 = 'f'; v7 = 'g'; v8 = 'h'; } TestBed.configureTestingModule({ declarations: [App, MyComp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const myComps = fixture.debugElement .queryAll(By.directive(MyComp)) .map((f) => f.componentInstance); myComps.forEach((myComp) => { expect(myComp.names).toEqual(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']); }); const app = fixture.componentInstance; app.v1 = 'a1'; app.v2 = 'b1'; app.v3 = 'c1'; app.v4 = 'd1'; app.v5 = 'e1'; app.v6 = 'f1'; app.v7 = 'g1'; app.v8 = 'h1'; fixture.detectChanges(); expect(myComps[0].names).toEqual(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h1']); expect(myComps[1].names).toEqual(['a', 'b', 'c', 'd', 'e', 'f', 'g1', 'h1']); expect(myComps[2].names).toEqual(['a', 'b', 'c', 'd', 'e', 'f1', 'g1', 'h1']); expect(myComps[3].names).toEqual(['a', 'b', 'c', 'd', 'e1', 'f1', 'g1', 'h1']); expect(myComps[4].names).toEqual(['a', 'b', 'c', 'd1', 'e1', 'f1', 'g1', 'h1']); expect(myComps[5].names).toEqual(['a', 'b', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1']); expect(myComps[6].names).toEqual(['a', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1']); expect(myComps[7].names).toEqual(['a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1']); app.v8 = 'h2'; fixture.detectChanges(); expect(myComps[0].names).toEqual(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h2']); expect(myComps[1].names).toEqual(['a', 'b', 'c', 'd', 'e', 'f', 'g1', 'h2']); expect(myComps[2].names).toEqual(['a', 'b', 'c', 'd', 'e', 'f1', 'g1', 'h2']); expect(myComps[3].names).toEqual(['a', 'b', 'c', 'd', 'e1', 'f1', 'g1', 'h2']); expect(myComps[4].names).toEqual(['a', 'b', 'c', 'd1', 'e1', 'f1', 'g1', 'h2']); expect(myComps[5].names).toEqual(['a', 'b', 'c1', 'd1', 'e1', 'f1', 'g1', 'h2']); expect(myComps[6].names).toEqual(['a', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h2']); expect(myComps[7].names).toEqual(['a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h2']); }); it('should work with pureFunctionV for 9+ bindings', () => { @Component({ template: ` <my-comp [names]="['start', v0, v1, v2, v3, 'modified_' + v4, v5, v6, v7, v8, 'end']"> </my-comp> `, standalone: false, }) class App { v0 = 'a'; v1 = 'b'; v2 = 'c'; v3 = 'd'; v4 = 'e'; v5 = 'f'; v6 = 'g'; v7 = 'h'; v8 = 'i'; } TestBed.configureTestingModule({ declarations: [App, MyComp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const myComp = fixture.debugElement.query(By.directive(MyComp)).componentInstance; const app = fixture.componentInstance; expect(myComp.names).toEqual([ 'start', 'a', 'b', 'c', 'd', 'modified_e', 'f', 'g', 'h', 'i', 'end', ]); app.v0 = 'a1'; fixture.detectChanges(); expect(myComp.names).toEqual([ 'start', 'a1', 'b', 'c', 'd', 'modified_e', 'f', 'g', 'h', 'i', 'end', ]); app.v4 = 'e5'; fixture.detectChanges(); expect(myComp.names).toEqual([ 'start', 'a1', 'b', 'c', 'd', 'modified_e5', 'f', 'g', 'h', 'i', 'end', ]); }); });
{ "end_byte": 11824, "start_byte": 7223, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/pure_function_spec.ts" }
angular/packages/core/test/acceptance/pure_function_spec.ts_11828_16638
describe('with object literals', () => { @Component({ selector: 'object-comp', template: ``, standalone: false, }) class ObjectComp { @Input() config: any = []; } it('should support an object literal', () => { @Component({ template: '<object-comp [config]="{duration: 500, animation: name}"></object-comp>', standalone: false, }) class App { name = 'slide'; } TestBed.configureTestingModule({ declarations: [App, ObjectComp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const objectComp = fixture.debugElement.query(By.directive(ObjectComp)).componentInstance; const firstObj = objectComp.config; expect(objectComp.config).toEqual({duration: 500, animation: 'slide'}); fixture.detectChanges(); expect(objectComp.config).toEqual({duration: 500, animation: 'slide'}); expect(firstObj).toBe(objectComp.config); fixture.componentInstance.name = 'tap'; fixture.detectChanges(); expect(objectComp.config).toEqual({duration: 500, animation: 'tap'}); // Identity must change if binding changes expect(firstObj).not.toBe(objectComp.config); }); it('should support expressions nested deeply in object/array literals', () => { @Component({ template: ` <object-comp [config]="{animation: name, actions: [{ opacity: 0, duration: 0}, {opacity: 1, duration: duration }]}"> </object-comp> `, standalone: false, }) class App { name = 'slide'; duration = 100; } TestBed.configureTestingModule({ declarations: [App, ObjectComp], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const objectComp = fixture.debugElement.query(By.directive(ObjectComp)).componentInstance; expect(objectComp.config).toEqual({ animation: 'slide', actions: [ {opacity: 0, duration: 0}, {opacity: 1, duration: 100}, ], }); const firstConfig = objectComp.config; fixture.detectChanges(); expect(objectComp.config).toEqual({ animation: 'slide', actions: [ {opacity: 0, duration: 0}, {opacity: 1, duration: 100}, ], }); expect(objectComp.config).toBe(firstConfig); fixture.componentInstance.duration = 50; fixture.detectChanges(); expect(objectComp.config).toEqual({ animation: 'slide', actions: [ {opacity: 0, duration: 0}, {opacity: 1, duration: 50}, ], }); expect(objectComp.config).not.toBe(firstConfig); fixture.componentInstance.name = 'tap'; fixture.detectChanges(); expect(objectComp.config).toEqual({ animation: 'tap', actions: [ {opacity: 0, duration: 0}, {opacity: 1, duration: 50}, ], }); fixture.componentInstance.name = 'drag'; fixture.componentInstance.duration = 500; fixture.detectChanges(); expect(objectComp.config).toEqual({ animation: 'drag', actions: [ {opacity: 0, duration: 0}, {opacity: 1, duration: 500}, ], }); // The property should not be set if the exp value is the same, so artificially // setting the property to ensure it's not overwritten. objectComp.config = ['should not be overwritten']; fixture.detectChanges(); expect(objectComp.config).toEqual(['should not be overwritten']); }); it('should support multiple view instances with multiple bindings', () => { @Component({ template: ` <object-comp *ngFor="let config of configs" [config]="config"> </object-comp> `, standalone: false, }) class App { configs = [ {opacity: 0, duration: 500}, {opacity: 1, duration: 600}, ]; } TestBed.configureTestingModule({ declarations: [App, ObjectComp], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const app = fixture.componentInstance; const objectComps = fixture.debugElement .queryAll(By.directive(ObjectComp)) .map((f) => f.componentInstance); expect(objectComps[0].config).toEqual({opacity: 0, duration: 500}); expect(objectComps[1].config).toEqual({opacity: 1, duration: 600}); app.configs[0].duration = 1000; fixture.detectChanges(); expect(objectComps[0].config).toEqual({opacity: 0, duration: 1000}); expect(objectComps[1].config).toEqual({opacity: 1, duration: 600}); }); });
{ "end_byte": 16638, "start_byte": 11828, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/pure_function_spec.ts" }
angular/packages/core/test/acceptance/pure_function_spec.ts_16642_21299
describe('identical literals', () => { @Directive({ selector: '[dir]', standalone: false, }) class Dir { @Input('dir') value: any; } it('should not share object literals across elements', () => { @Component({ template: ` <div [dir]="{}"></div> <div [dir]="{}"></div> `, standalone: false, }) class App { @ViewChildren(Dir) directives!: QueryList<Dir>; } TestBed.configureTestingModule({declarations: [Dir, App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const directives = fixture.componentInstance.directives.toArray(); expect(directives[0].value).not.toBe(directives[1].value); }); it('should not share array literals across elements', () => { @Component({ template: ` <div [dir]="[]"></div> <div [dir]="[]"></div> `, standalone: false, }) class App { @ViewChildren(Dir) directives!: QueryList<Dir>; } TestBed.configureTestingModule({declarations: [Dir, App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const directives = fixture.componentInstance.directives.toArray(); expect(directives[0].value).not.toBe(directives[1].value); }); it('should not share object literals across component instances', () => { @Component({ template: `<div [dir]="{}"></div>`, standalone: false, }) class App { @ViewChild(Dir) directive!: Dir; } TestBed.configureTestingModule({declarations: [Dir, App]}); const firstFixture = TestBed.createComponent(App); firstFixture.detectChanges(); const secondFixture = TestBed.createComponent(App); secondFixture.detectChanges(); expect(firstFixture.componentInstance.directive.value).not.toBe( secondFixture.componentInstance.directive.value, ); }); it('should not share array literals across component instances', () => { @Component({ template: `<div [dir]="[]"></div>`, standalone: false, }) class App { @ViewChild(Dir) directive!: Dir; } TestBed.configureTestingModule({declarations: [Dir, App]}); const firstFixture = TestBed.createComponent(App); firstFixture.detectChanges(); const secondFixture = TestBed.createComponent(App); secondFixture.detectChanges(); expect(firstFixture.componentInstance.directive.value).not.toBe( secondFixture.componentInstance.directive.value, ); }); it('should not confuse object literals and null inside of a literal', () => { @Component({ template: ` <div [dir]="{foo: null}"></div> <div [dir]="{foo: {}}"></div> `, standalone: false, }) class App { @ViewChildren(Dir) directives!: QueryList<Dir>; } TestBed.configureTestingModule({declarations: [Dir, App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const values = fixture.componentInstance.directives.map((directive) => directive.value); expect(values).toEqual([{foo: null}, {foo: {}}]); }); it('should not confuse array literals and null inside of a literal', () => { @Component({ template: ` <div [dir]="{foo: null}"></div> <div [dir]="{foo: []}"></div> `, standalone: false, }) class App { @ViewChildren(Dir) directives!: QueryList<Dir>; } TestBed.configureTestingModule({declarations: [Dir, App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const values = fixture.componentInstance.directives.map((directive) => directive.value); expect(values).toEqual([{foo: null}, {foo: []}]); }); it('should not confuse function calls and null inside of a literal', () => { @Component({ template: ` <div [dir]="{foo: null}"></div> <div [dir]="{foo: getFoo()}"></div> `, standalone: false, }) class App { @ViewChildren(Dir) directives!: QueryList<Dir>; getFoo() { return 'foo!'; } } TestBed.configureTestingModule({declarations: [Dir, App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const values = fixture.componentInstance.directives.map((directive) => directive.value); expect(values).toEqual([{foo: null}, {foo: 'foo!'}]); }); }); });
{ "end_byte": 21299, "start_byte": 16642, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/pure_function_spec.ts" }
angular/packages/core/test/acceptance/change_detection_transplanted_view_spec.ts_0_8437
/** * @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 {AsyncPipe, CommonModule, NgTemplateOutlet} from '@angular/common'; import { AfterViewChecked, ApplicationRef, ChangeDetectionStrategy, ChangeDetectorRef, Component, computed, createComponent, Directive, DoCheck, EmbeddedViewRef, EnvironmentInjector, ErrorHandler, inject, Input, signal, TemplateRef, Type, ViewChild, ViewContainerRef, } from '@angular/core'; import {provideExperimentalCheckNoChangesForDebug} from '@angular/core/src/change_detection/scheduling/exhaustive_check_no_changes'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/src/matchers'; import {of} from 'rxjs'; describe('change detection for transplanted views', () => { describe('when declaration appears before insertion', () => { @Component({ selector: 'onpush-insert-comp', changeDetection: ChangeDetectionStrategy.OnPush, template: ` OnPushInsertComp({{greeting}}) <div *ngIf="true"> <!-- Add extra level of embedded view to ensure we can handle nesting --> <ng-container [ngTemplateOutlet]="template" [ngTemplateOutletContext]="{$implicit: greeting}"> </ng-container> </div> `, standalone: false, }) abstract class OnPushInsertComp implements DoCheck, AfterViewChecked { get template(): TemplateRef<any> { return templateRef; } greeting: string = 'Hello'; constructor(public changeDetectorRef: ChangeDetectorRef) { onPushInsertComp = this; } ngDoCheck(): void { logValue = 'Insert'; } ngAfterViewChecked(): void { logValue = null; } } @Directive({ standalone: false, }) abstract class DeclareComp implements DoCheck, AfterViewChecked { @ViewChild('myTmpl') myTmpl!: TemplateRef<any>; name: string = 'world'; constructor(readonly changeDetector: ChangeDetectorRef) {} ngDoCheck(): void { logValue = 'Declare'; } logName() { // This will log when the embedded view gets CD. The `logValue` will show if the CD was // from `Insert` or from `Declare` component. viewExecutionLog.push(logValue!); return this.name; } ngAfterViewChecked(): void { logValue = null; } ngAfterViewInit() { templateRef = this.myTmpl; } } @Component({ selector: `check-always-declare-comp`, template: ` DeclareComp({{name}}) <ng-template #myTmpl let-greeting> {{greeting}} {{logName()}}! </ng-template> `, standalone: false, }) class CheckAlwaysDeclareComp extends DeclareComp { constructor(changeDetector: ChangeDetectorRef) { super(changeDetector); declareComp = this; } } @Component({ selector: `onpush-declare-comp`, template: ` OnPushDeclareComp({{name}}) <ng-template #myTmpl let-greeting> {{greeting}} {{logName()}}! </ng-template>`, changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class OnPushDeclareComp extends DeclareComp { constructor(changeDetector: ChangeDetectorRef) { super(changeDetector); onPushDeclareComp = this; } } @Component({ selector: `signal-onpush-declare-comp`, template: ` SignalOnPushDeclareComp({{name()}}) <ng-template #myTmpl let-greeting> {{greeting}} {{surname()}}{{logExecutionContext()}}! </ng-template> `, changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class SignalOnPushDeclareComp { @ViewChild('myTmpl') myTmpl!: TemplateRef<any>; name = signal('world'); templateName = signal('templateName'); surname = computed(() => { const name = this.templateName(); return name; }); logExecutionContext() { viewExecutionLog.push(logValue); return ''; } constructor() { signalDeclareComp = this; } ngAfterViewChecked() { logValue = null; } ngAfterViewInit() { templateRef = this.myTmpl; } } @Component({ template: ` <check-always-declare-comp *ngIf="showCheckAlwaysDeclare" /> <onpush-declare-comp *ngIf="showOnPushDeclare" /> <signal-onpush-declare-comp *ngIf="showSignalOnPushDeclare" /> <onpush-insert-comp *ngIf="showOnPushInsert" /> `, standalone: false, }) class AppComp { showCheckAlwaysDeclare = false; showSignalOnPushDeclare = false; showOnPushDeclare = false; showOnPushInsert = false; constructor() { appComp = this; } } let viewExecutionLog!: Array<string | null>; let logValue!: string | null; let fixture!: ComponentFixture<AppComp>; let appComp!: AppComp; let onPushInsertComp!: OnPushInsertComp; let declareComp!: CheckAlwaysDeclareComp; let templateRef: TemplateRef<any>; let onPushDeclareComp!: OnPushDeclareComp; let signalDeclareComp!: SignalOnPushDeclareComp; beforeEach(() => { TestBed.configureTestingModule({ declarations: [ OnPushInsertComp, SignalOnPushDeclareComp, CheckAlwaysDeclareComp, OnPushDeclareComp, AppComp, ], imports: [CommonModule], }); viewExecutionLog = []; fixture = TestBed.createComponent(AppComp); }); describe('and declaration component is Onpush with signals and insertion is OnPush', () => { beforeEach(() => { fixture.componentInstance.showSignalOnPushDeclare = true; fixture.componentInstance.showOnPushInsert = true; fixture.detectChanges(false); viewExecutionLog.length = 0; }); it('should set up the component under test correctly', () => { expect(viewExecutionLog.length).toEqual(0); expect(trim(fixture.nativeElement.textContent)).toEqual( 'SignalOnPushDeclareComp(world) OnPushInsertComp(Hello) Hello templateName!', ); }); it('should CD at insertion and declaration', () => { signalDeclareComp.name.set('Angular'); fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)) .withContext( 'CD did not run on the transplanted template because it is inside an OnPush component and no signal changed', ) .toEqual('SignalOnPushDeclareComp(Angular) OnPushInsertComp(Hello) Hello templateName!'); onPushInsertComp.greeting = 'Hi'; fixture.detectChanges(false); expect(viewExecutionLog).toEqual([]); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)) .withContext('Insertion component is OnPush.') .toEqual('SignalOnPushDeclareComp(Angular) OnPushInsertComp(Hello) Hello templateName!'); onPushInsertComp.changeDetectorRef.markForCheck(); fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'SignalOnPushDeclareComp(Angular) OnPushInsertComp(Hi) Hi templateName!', ); // Destroy insertion should also destroy declaration appComp.showOnPushInsert = false; fixture.detectChanges(false); expect(viewExecutionLog).toEqual([]); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual('SignalOnPushDeclareComp(Angular)'); // Restore both appComp.showOnPushInsert = true; fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'SignalOnPushDeclareComp(Angular) OnPushInsertComp(Hello) Hello templateName!', ); }); });
{ "end_byte": 8437, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_transplanted_view_spec.ts" }
angular/packages/core/test/acceptance/change_detection_transplanted_view_spec.ts_8443_16552
describe('and declaration component is CheckAlways', () => { beforeEach(() => { fixture.componentInstance.showCheckAlwaysDeclare = true; fixture.componentInstance.showOnPushInsert = true; fixture.detectChanges(false); viewExecutionLog.length = 0; }); it('should set up the component under test correctly', () => { expect(viewExecutionLog.length).toEqual(0); expect(trim(fixture.nativeElement.textContent)).toEqual( 'DeclareComp(world) OnPushInsertComp(Hello) Hello world!', ); }); it('should CD at insertion point only', () => { declareComp.name = 'Angular'; fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'DeclareComp(Angular) OnPushInsertComp(Hello) Hello Angular!', 'Expect transplanted LView to be CD because the declaration is CD.', ); onPushInsertComp.greeting = 'Hi'; fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'DeclareComp(Angular) OnPushInsertComp(Hello) Hello Angular!', 'expect no change because it is on push.', ); onPushInsertComp.changeDetectorRef.markForCheck(); fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'DeclareComp(Angular) OnPushInsertComp(Hi) Hi Angular!', ); // Destroy insertion should also destroy declaration appComp.showOnPushInsert = false; fixture.detectChanges(false); expect(viewExecutionLog).toEqual([]); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual('DeclareComp(Angular)'); // Restore both appComp.showOnPushInsert = true; fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'DeclareComp(Angular) OnPushInsertComp(Hello) Hello Angular!', ); // Destroy declaration, But we should still be able to see updates in insertion appComp.showCheckAlwaysDeclare = false; onPushInsertComp.greeting = 'Hello'; onPushInsertComp.changeDetectorRef.markForCheck(); fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'OnPushInsertComp(Hello) Hello Angular!', ); }); it('is not checked if detectChanges is called in declaration component', () => { declareComp.name = 'Angular'; declareComp.changeDetector.detectChanges(); expect(viewExecutionLog).toEqual([]); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'DeclareComp(Angular) OnPushInsertComp(Hello) Hello world!', ); }); it('is checked as part of CheckNoChanges pass', () => { fixture.detectChanges(true); expect(viewExecutionLog).toEqual([ 'Insert', null /* logName set to null afterViewChecked */, ]); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'DeclareComp(world) OnPushInsertComp(Hello) Hello world!', ); }); }); describe('and declaration and insertion components are OnPush', () => { beforeEach(() => { fixture.componentInstance.showOnPushDeclare = true; fixture.componentInstance.showOnPushInsert = true; fixture.detectChanges(false); viewExecutionLog.length = 0; }); it('should set up component under test correctly', () => { expect(viewExecutionLog.length).toEqual(0); expect(trim(fixture.nativeElement.textContent)).toEqual( 'OnPushDeclareComp(world) OnPushInsertComp(Hello) Hello world!', ); }); it('should not check anything when no views are dirty', () => { fixture.detectChanges(false); expect(viewExecutionLog).toEqual([]); }); it('should CD at insertion point only', () => { onPushDeclareComp.name = 'Angular'; onPushInsertComp.greeting = 'Hi'; // mark declaration point dirty onPushDeclareComp.changeDetector.markForCheck(); fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'OnPushDeclareComp(Angular) OnPushInsertComp(Hello) Hello Angular!', ); // mark insertion point dirty onPushInsertComp.changeDetectorRef.markForCheck(); fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; expect(trim(fixture.nativeElement.textContent)).toEqual( 'OnPushDeclareComp(Angular) OnPushInsertComp(Hi) Hi Angular!', ); // mark both insertion and declaration point dirty onPushInsertComp.changeDetectorRef.markForCheck(); onPushDeclareComp.changeDetector.markForCheck(); fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert']); viewExecutionLog.length = 0; }); it('is checked if detectChanges is called in declaration component', () => { onPushDeclareComp.name = 'Angular'; onPushDeclareComp.changeDetector.detectChanges(); expect(trim(fixture.nativeElement.textContent)).toEqual( 'OnPushDeclareComp(Angular) OnPushInsertComp(Hello) Hello world!', ); }); // TODO(FW-1774): blocked by https://github.com/angular/angular/pull/34443 xit('is checked as part of CheckNoChanges pass', () => { // mark declaration point dirty onPushDeclareComp.changeDetector.markForCheck(); fixture.detectChanges(false); expect(viewExecutionLog).toEqual([ 'Insert', null /* logName set to null in afterViewChecked */, ]); viewExecutionLog.length = 0; // mark insertion point dirty onPushInsertComp.changeDetectorRef.markForCheck(); fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert', null]); viewExecutionLog.length = 0; // mark both insertion and declaration point dirty onPushInsertComp.changeDetectorRef.markForCheck(); onPushDeclareComp.changeDetector.markForCheck(); fixture.detectChanges(false); expect(viewExecutionLog).toEqual(['Insert', null]); viewExecutionLog.length = 0; }); it('does not cause infinite change detection if transplanted view is dirty and destroyed before refresh', () => { // mark declaration point dirty onPushDeclareComp.changeDetector.markForCheck(); // detach insertion so the transplanted view doesn't get refreshed when CD runs onPushInsertComp.changeDetectorRef.detach(); // run CD, which will set the `RefreshView` flag on the transplanted view fixture.detectChanges(false); // reattach insertion so the DESCENDANT_VIEWS counters update onPushInsertComp.changeDetectorRef.reattach(); // make it so the insertion is destroyed before getting refreshed fixture.componentInstance.showOnPushInsert = false; // run CD again. If we didn't clear the flag/counters when destroying the view, this // would cause an infinite CD because the counters will be >1 but we will never reach a // view to refresh and decrement the counters. fixture.detectChanges(false); }); }); });
{ "end_byte": 16552, "start_byte": 8443, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_transplanted_view_spec.ts" }
angular/packages/core/test/acceptance/change_detection_transplanted_view_spec.ts_16556_26234
describe('backwards references', () => { @Component({ selector: 'insertion', template: ` <div>Insertion({{name}})</div> <ng-container [ngTemplateOutlet]="template" [ngTemplateOutletContext]="{$implicit: name}"> </ng-container>`, changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class Insertion { @Input() template!: TemplateRef<{}>; name = 'initial'; constructor(readonly changeDetectorRef: ChangeDetectorRef) {} } @Component({ selector: 'declaration', template: ` <div>Declaration({{name}})</div> <ng-template #template let-contextName> <div>{{incrementChecks()}}</div> <div>TemplateDeclaration({{name}})</div> <div>TemplateContext({{contextName}})</div> </ng-template> `, changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class Declaration { @ViewChild('template') template?: TemplateRef<{}>; name = 'initial'; transplantedViewRefreshCount = 0; constructor(readonly changeDetectorRef: ChangeDetectorRef) {} incrementChecks() { this.transplantedViewRefreshCount++; } } let fixture: ComponentFixture<App>; let appComponent: App; @Component({ template: ` <insertion *ngIf="showInsertion" [template]="declaration?.template"> </insertion> <declaration></declaration> `, standalone: false, }) class App { @ViewChild(Declaration) declaration!: Declaration; @ViewChild(Insertion) insertion!: Insertion; template?: TemplateRef<{}>; showInsertion = false; } beforeEach(() => { fixture = TestBed.configureTestingModule({ declarations: [App, Declaration, Insertion], }).createComponent(App); appComponent = fixture.componentInstance; fixture.detectChanges(false); appComponent.showInsertion = true; fixture.detectChanges(false); appComponent.declaration.transplantedViewRefreshCount = 0; }); it('should set up component under test correctly', () => { expect(fixture.nativeElement.textContent).toEqual( 'Insertion(initial)TemplateDeclaration(initial)TemplateContext(initial)Declaration(initial)', ); expect(appComponent.declaration.transplantedViewRefreshCount).toEqual(0); }); it('should update declaration view when there is a change in the declaration and insertion is marked dirty', () => { appComponent.declaration.name = 'new name'; appComponent.insertion.changeDetectorRef.markForCheck(); fixture.detectChanges(false); expect(fixture.nativeElement.textContent).toEqual( 'Insertion(initial)TemplateDeclaration(new name)TemplateContext(initial)Declaration(initial)', 'Name should not update in declaration view because only insertion was marked dirty', ); expect(appComponent.declaration.transplantedViewRefreshCount).toEqual(1); }); it('updates the declaration view when there is a change to either declaration or insertion', () => { appComponent.declaration.name = 'new name'; appComponent.declaration.changeDetectorRef.markForCheck(); fixture.detectChanges(false); const expectedContent = 'Insertion(initial)TemplateDeclaration(new name)TemplateContext(initial)Declaration(new name)'; expect(fixture.nativeElement.textContent).toEqual(expectedContent); expect(appComponent.declaration.transplantedViewRefreshCount).toEqual(1); }); it('should update when there is a change to insertion and declaration is marked dirty', () => { appComponent.insertion.name = 'new name'; appComponent.declaration.changeDetectorRef.markForCheck(); fixture.detectChanges(false); expect(fixture.nativeElement.textContent).toEqual( 'Insertion(initial)TemplateDeclaration(initial)TemplateContext(initial)Declaration(initial)', ); expect(appComponent.declaration.transplantedViewRefreshCount).toEqual(1); }); it('should update insertion view and template when there is a change to insertion and insertion marked dirty', () => { appComponent.insertion.name = 'new name'; appComponent.insertion.changeDetectorRef.markForCheck(); fixture.detectChanges(false); expect(fixture.nativeElement.textContent).toEqual( 'Insertion(new name)TemplateDeclaration(initial)TemplateContext(new name)Declaration(initial)', ); expect(appComponent.declaration.transplantedViewRefreshCount).toEqual(1); }); it('should not refresh the template if nothing is marked dirty', () => { fixture.detectChanges(false); expect(appComponent.declaration.transplantedViewRefreshCount).toEqual(0); }); it('should refresh template when declaration and insertion are marked dirty', () => { appComponent.declaration.changeDetectorRef.markForCheck(); appComponent.insertion.changeDetectorRef.markForCheck(); fixture.detectChanges(false); expect(appComponent.declaration.transplantedViewRefreshCount) .withContext( 'Should refresh twice because insertion executes and then declaration marks transplanted view dirty again', ) .toEqual(2); }); }); describe('transplanted views shielded by OnPush', () => { @Component({ selector: 'check-always-insertion', template: `<ng-container [ngTemplateOutlet]="template"></ng-container>`, standalone: false, }) class CheckAlwaysInsertion { @Input() template!: TemplateRef<{}>; } @Component({ selector: 'on-push-insertion-host', template: `<check-always-insertion [template]="template"></check-always-insertion>`, changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class OnPushInsertionHost { @Input() template!: TemplateRef<{}>; constructor(readonly cdr: ChangeDetectorRef) {} } @Component({ template: ` <ng-template #template>{{value}}</ng-template> <on-push-insertion-host [template]="template"></on-push-insertion-host> `, changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class OnPushDeclaration { @ViewChild(OnPushInsertionHost) onPushInsertionHost?: OnPushInsertionHost; private _value = 'initial'; throwErrorInView = false; get value() { if (this.throwErrorInView) { throw new Error('error getting value in transplanted view'); } return this._value; } set value(v: string) { this._value = v; } constructor(readonly cdr: ChangeDetectorRef) {} } @Component({ template: ` <ng-template #template>{{value}}</ng-template> <on-push-insertion-host [template]="template"></on-push-insertion-host> `, standalone: false, }) class CheckAlwaysDeclaration { @ViewChild(OnPushInsertionHost) onPushInsertionHost?: OnPushInsertionHost; value = 'initial'; } function getFixture<T>(componentUnderTest: Type<T>): ComponentFixture<T> { return TestBed.configureTestingModule({ declarations: [ CheckAlwaysDeclaration, OnPushDeclaration, CheckAlwaysInsertion, OnPushInsertionHost, ], }).createComponent(componentUnderTest); } it('can recover from errors thrown during change detection', () => { const fixture = getFixture(OnPushDeclaration); fixture.detectChanges(); fixture.componentInstance.value = 'new'; fixture.componentInstance.cdr.markForCheck(); fixture.componentInstance.throwErrorInView = true; expect(() => { fixture.detectChanges(); }).toThrow(); // Ensure that the transplanted view can still get refreshed if we rerun change detection // without the error fixture.componentInstance.throwErrorInView = false; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('new'); }); it('refresh when transplanted view is declared in CheckAlways component', () => { const fixture = getFixture(CheckAlwaysDeclaration); fixture.detectChanges(); fixture.componentInstance.value = 'new'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('new'); }); it('refresh when transplanted view is declared in OnPush component', () => { const fixture = getFixture(OnPushDeclaration); fixture.detectChanges(); fixture.componentInstance.value = 'new'; fixture.componentInstance.cdr.markForCheck(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('new'); }); describe('when insertion is detached', () => { it('does not refresh CheckAlways transplants', () => { const fixture = getFixture(CheckAlwaysDeclaration); fixture.detectChanges(); fixture.componentInstance.onPushInsertionHost!.cdr.detach(); fixture.componentInstance.value = 'new'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('initial'); }); it('does not refresh OnPush transplants', () => { const fixture = getFixture(OnPushDeclaration); fixture.detectChanges(); fixture.componentInstance.onPushInsertionHost!.cdr.detach(); fixture.componentInstance.value = 'new'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('initial'); }); }); });
{ "end_byte": 26234, "start_byte": 16556, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_transplanted_view_spec.ts" }
angular/packages/core/test/acceptance/change_detection_transplanted_view_spec.ts_26238_31942
it('refreshes transplanted views used as template in ngForTemplate', () => { @Component({ selector: 'triple', template: '<div *ngFor="let unused of [1,2,3]; template: template"></div>', changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class TripleTemplate { @Input() template!: TemplateRef<{}>; } @Component({ template: ` <ng-template #template>{{name}}</ng-template> <triple [template]="template"></triple> `, standalone: false, }) class App { name = 'Penny'; } const fixture = TestBed.configureTestingModule({ declarations: [App, TripleTemplate], }).createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('PennyPennyPenny'); fixture.componentInstance.name = 'Sheldon'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual( 'SheldonSheldonSheldon', 'Expected transplanted view to be refreshed even when insertion is not dirty', ); }); describe('ViewRef and ViewContainerRef operations', () => { @Component({ template: '<ng-template>{{incrementChecks()}}</ng-template>', standalone: false, }) class AppComponent { @ViewChild(TemplateRef) templateRef!: TemplateRef<{}>; constructor( readonly rootViewContainerRef: ViewContainerRef, readonly cdr: ChangeDetectorRef, ) {} checks = 0; incrementChecks() { this.checks++; } } let fixture: ComponentFixture<AppComponent>; let component: AppComponent; let viewRef: EmbeddedViewRef<{}>; beforeEach(() => { fixture = TestBed.configureTestingModule({declarations: [AppComponent]}).createComponent( AppComponent, ); component = fixture.componentInstance; fixture.detectChanges(); viewRef = component.templateRef.createEmbeddedView({}); component.rootViewContainerRef.insert(viewRef); }); it('should not fail when change detecting detached transplanted view', () => { // This `ViewContainerRef` is for the root view // `detectChanges` on this `ChangeDetectorRef` will refresh this view and children, not the // root view that has the transplanted `viewRef` inserted. component.cdr.detectChanges(); // The template should not have been refreshed because it was inserted "above" the component // so `detectChanges` will not refresh it. expect(component.checks).toEqual(0); // Detach view, manually call `detectChanges`, and verify the template was refreshed component.rootViewContainerRef.detach(); viewRef.detectChanges(); expect(component.checks).toEqual(1); }); it('should work when change detecting detached transplanted view already marked for refresh', () => { // detach the viewRef only. This just removes the LViewFlags.Attached rather than actually // detaching the view from the container. viewRef.detach(); // Calling detectChanges marks transplanted views for check component.cdr.detectChanges(); expect(() => { // Calling detectChanges on the transplanted view itself will clear the refresh flag. It // _should not_ also attempt to update the parent counters because it's detached and // should not affect parent counters. viewRef.detectChanges(); }).not.toThrow(); expect(component.checks).toEqual(1); }); it('should work when re-inserting a previously detached transplanted view marked for refresh', () => { // Test case for inserting a view with refresh flag viewRef.detach(); // mark transplanted views for check but does not refresh transplanted view because it is // detached component.cdr.detectChanges(); // reattach view itself viewRef.reattach(); expect(() => { // detach and reattach view from ViewContainerRef component.rootViewContainerRef.detach(); component.rootViewContainerRef.insert(viewRef); // calling detectChanges will clear the refresh flag. If the above operations messed up // the counter, this would fail when attempted to decrement. fixture.detectChanges(false); }).not.toThrow(); // The transplanted view gets refreshed twice because it's actually inserted "backwards" // The view is defined in AppComponent but inserted in its ViewContainerRef (as an // embedded view in AppComponent's host view). expect(component.checks).toEqual(2); }); it('should work when detaching an attached transplanted view with the refresh flag', () => { viewRef.detach(); // mark transplanted views for check but does not refresh transplanted view because it is // detached component.cdr.detectChanges(); // reattach view with refresh flag should increment parent counters viewRef.reattach(); expect(() => { // detach view with refresh flag should decrement parent counters viewRef.detach(); // detectChanges on parent should not cause infinite loop if the above counters were updated // correctly both times. fixture.detectChanges(); }).not.toThrow(); }); it('should work when destroying a view with the refresh flag', () => { viewRef.detach(); // mark transplanted views for check but does not refresh transplanted view because it is // detached component.cdr.detectChanges(); viewRef.reattach(); expect(() => { viewRef.destroy(); fixture.detectChanges(); }).not.toThrow(); }); });
{ "end_byte": 31942, "start_byte": 26238, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_transplanted_view_spec.ts" }
angular/packages/core/test/acceptance/change_detection_transplanted_view_spec.ts_31946_41367
describe('when detached', () => { @Component({ selector: 'on-push-component', template: ` <ng-container #vc></ng-container> `, changeDetection: ChangeDetectionStrategy.OnPush, standalone: false, }) class OnPushComponent { @ViewChild('vc', {read: ViewContainerRef}) viewContainer!: ViewContainerRef; @Input() template!: TemplateRef<{}>; createTemplate() { return this.viewContainer.createEmbeddedView(this.template); } } @Component({ selector: 'check-always-component', template: ` <ng-container #vc></ng-container> `, standalone: false, }) class CheckAlwaysComponent { @ViewChild('vc', {read: ViewContainerRef}) viewContainer!: ViewContainerRef; @Input() template!: TemplateRef<{}>; createTemplate() { return this.viewContainer.createEmbeddedView(this.template); } } let fixture: ComponentFixture<App>; let appComponent: App; let onPushComponent: OnPushComponent; let checkAlwaysComponent: CheckAlwaysComponent; @Component({ template: ` <ng-template #transplantedTemplate>{{ incrementChecks() }}</ng-template> <on-push-component [template]="transplantedTemplate"></on-push-component> <check-always-component [template]="transplantedTemplate"></check-always-component> `, standalone: false, }) class App { @ViewChild(OnPushComponent) onPushComponent!: OnPushComponent; @ViewChild(CheckAlwaysComponent) checkAlwaysComponent!: CheckAlwaysComponent; transplantedViewRefreshCount = 0; incrementChecks() { this.transplantedViewRefreshCount++; } } beforeEach(() => { TestBed.configureTestingModule({declarations: [App, OnPushComponent, CheckAlwaysComponent]}); fixture = TestBed.createComponent(App); fixture.detectChanges(); appComponent = fixture.componentInstance; onPushComponent = appComponent.onPushComponent; checkAlwaysComponent = appComponent.checkAlwaysComponent; }); describe('inside OnPush components', () => { it('should detect changes when attached', () => { onPushComponent.createTemplate(); fixture.detectChanges(false); expect(appComponent.transplantedViewRefreshCount).toEqual(1); }); it('should not detect changes', () => { const viewRef = onPushComponent.createTemplate(); viewRef.detach(); fixture.detectChanges(false); expect(appComponent.transplantedViewRefreshCount).toEqual(0); viewRef.reattach(); fixture.detectChanges(false); expect(appComponent.transplantedViewRefreshCount).toEqual(1); }); it('should not detect changes on mixed detached/attached refs', () => { onPushComponent.createTemplate(); const viewRef = onPushComponent.createTemplate(); viewRef.detach(); fixture.detectChanges(false); expect(appComponent.transplantedViewRefreshCount).toEqual(1); viewRef.reattach(); fixture.detectChanges(false); expect(appComponent.transplantedViewRefreshCount).toEqual(3); }); }); describe('inside CheckAlways component', () => { it('should detect changes when attached', () => { checkAlwaysComponent.createTemplate(); fixture.detectChanges(false); expect(appComponent.transplantedViewRefreshCount).toEqual(1); }); it('should not detect changes', () => { const viewRef = checkAlwaysComponent.createTemplate(); viewRef.detach(); fixture.detectChanges(false); expect(appComponent.transplantedViewRefreshCount).toEqual(0); viewRef.reattach(); fixture.detectChanges(false); expect(appComponent.transplantedViewRefreshCount).toEqual(1); }); it('should not detect changes on mixed detached/attached refs', () => { checkAlwaysComponent.createTemplate(); const viewRef = checkAlwaysComponent.createTemplate(); viewRef.detach(); fixture.detectChanges(false); expect(appComponent.transplantedViewRefreshCount).toEqual(1); viewRef.reattach(); fixture.detectChanges(false); expect(appComponent.transplantedViewRefreshCount).toEqual(3); }); }); it('does not cause error if running change detection on detached view', () => { @Component({ standalone: true, selector: 'insertion', template: `<ng-container #vc></ng-container>`, }) class Insertion { @ViewChild('vc', {read: ViewContainerRef, static: true}) viewContainer!: ViewContainerRef; @Input() template!: TemplateRef<{}>; ngOnChanges() { return this.viewContainer.createEmbeddedView(this.template); } } @Component({ standalone: true, template: ` <ng-template #transplantedTemplate></ng-template> <insertion [template]="transplantedTemplate"></insertion> `, imports: [Insertion], }) class Root { readonly cdr = inject(ChangeDetectorRef); } const fixture = TestBed.createComponent(Root); fixture.componentInstance.cdr.detach(); fixture.componentInstance.cdr.detectChanges(); }); it('backwards reference still updated if detaching root during change detection', () => { @Component({ standalone: true, selector: 'insertion', template: `<ng-container #vc></ng-container>`, changeDetection: ChangeDetectionStrategy.OnPush, }) class Insertion { @ViewChild('vc', {read: ViewContainerRef, static: true}) viewContainer!: ViewContainerRef; @Input() template!: TemplateRef<{}>; ngOnChanges() { return this.viewContainer.createEmbeddedView(this.template); } } @Component({ template: '<ng-template #template>{{value}}</ng-template>', selector: 'declaration', standalone: true, }) class Declaration { @ViewChild('template', {static: true}) transplantedTemplate!: TemplateRef<{}>; @Input() value?: string; } @Component({ standalone: true, template: ` <insertion [template]="declaration?.transplantedTemplate"></insertion> <declaration [value]="value"></declaration> {{incrementChecks()}} `, imports: [Insertion, Declaration], }) class Root { @ViewChild(Declaration, {static: true}) declaration!: Declaration; readonly cdr = inject(ChangeDetectorRef); value = 'initial'; templateExecutions = 0; incrementChecks() { this.templateExecutions++; } } const fixture = TestBed.createComponent(Root); fixture.detectChanges(false); expect(fixture.nativeElement.innerText).toEqual('initial'); expect(fixture.componentInstance.templateExecutions).toEqual(1); // Root is detached and value in transplanted view updates during CD. Because it is inserted // backwards, this requires a rerun of the traversal at the root. This test ensures we still // get the rerun even when the root is detached. fixture.componentInstance.cdr.detach(); fixture.componentInstance.value = 'new'; fixture.componentInstance.cdr.detectChanges(); expect(fixture.componentInstance.templateExecutions).toEqual(2); expect(fixture.nativeElement.innerText).toEqual('new'); }); }); it('can use AsyncPipe on new Observable in insertion tree when used as backwards reference', () => { @Component({ selector: 'insertion', imports: [NgTemplateOutlet], standalone: true, template: ` <ng-container [ngTemplateOutlet]="template"> </ng-container>`, }) class Insertion { @Input() template!: TemplateRef<{}>; constructor(readonly changeDetectorRef: ChangeDetectorRef) {} } @Component({ imports: [Insertion, AsyncPipe], template: `<ng-template #myTmpl> {{newObservable() | async}} </ng-template>`, standalone: true, selector: 'declaration', }) class Declaration { @ViewChild('myTmpl', {static: true}) template!: TemplateRef<{}>; newObservable() { return of(''); } } @Component({ standalone: true, imports: [Declaration, Insertion], template: '<insertion [template]="declaration.template"/><declaration #declaration/>', }) class App {} TestBed.configureTestingModule({ providers: [ { provide: ErrorHandler, useClass: class extends ErrorHandler { override handleError(e: any) { throw e; } }, }, ], }); const app = createComponent(App, {environmentInjector: TestBed.inject(EnvironmentInjector)}); const appRef = TestBed.inject(ApplicationRef); appRef.attachView(app.hostView); // ApplicationRef has a loop to continue refreshing dirty views. If done incorrectly, // refreshing the backwards reference transplanted view can cause an infinite loop because it // goes and marks the root view dirty, which then starts the process all over again by // checking the declaration. expect(() => appRef.tick()).not.toThrow(); app.destroy(); });
{ "end_byte": 41367, "start_byte": 31946, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_transplanted_view_spec.ts" }
angular/packages/core/test/acceptance/change_detection_transplanted_view_spec.ts_41370_42880
it('does not cause infinite loops with exhaustive checkNoChanges', async () => { TestBed.configureTestingModule({ providers: [provideExperimentalCheckNoChangesForDebug({interval: 1})], }); const errorSpy = spyOn(console, 'error').and.callFake((...v) => { fail('console errored with ' + v); }); @Component({ standalone: true, selector: 'insertion', template: `<ng-container #vc></ng-container>`, changeDetection: ChangeDetectionStrategy.OnPush, }) class Insertion { @ViewChild('vc', {read: ViewContainerRef, static: true}) viewContainer!: ViewContainerRef; @Input() template!: TemplateRef<{}>; ngOnChanges() { return this.viewContainer.createEmbeddedView(this.template); } } @Component({ standalone: true, template: ` <ng-template #template>hello world</ng-template> <insertion [template]="transplantedTemplate"></insertion> `, imports: [Insertion], }) class Root { @ViewChild('template', {static: true}) transplantedTemplate!: TemplateRef<{}>; } const fixture = TestBed.createComponent(Root); TestBed.inject(ApplicationRef).attachView(fixture.componentRef.hostView); // wait the 1 tick for exhaustive check to trigger await new Promise((r) => setTimeout(r, 1)); expect(errorSpy).not.toHaveBeenCalled(); }); }); function trim(text: string | null): string { return text ? text.replace(/[\s\n]+/gm, ' ').trim() : ''; }
{ "end_byte": 42880, "start_byte": 41370, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_transplanted_view_spec.ts" }
angular/packages/core/test/acceptance/pipe_spec.ts_0_8130
/** * @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 { ChangeDetectionStrategy, ChangeDetectorRef, Component, Directive, Inject, Injectable, InjectionToken, Input, NgModule, OnChanges, OnDestroy, Pipe, PipeTransform, SimpleChanges, ViewChild, ɵɵdefineInjectable, ɵɵdefinePipe, ɵɵgetInheritedFactory, ɵɵinject, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/src/matchers'; describe('pipe', () => { @Pipe({ name: 'countingPipe', standalone: false, }) class CountingPipe implements PipeTransform { state: number = 0; transform(value: any) { return `${value} state:${this.state++}`; } } @Pipe({ name: 'multiArgPipe', standalone: false, }) class MultiArgPipe implements PipeTransform { transform(value: any, arg1: any, arg2: any, arg3 = 'default') { return `${value} ${arg1} ${arg2} ${arg3}`; } } it('should support interpolation', () => { @Component({ template: '{{person.name | countingPipe}}', standalone: false, }) class App { person = {name: 'bob'}; } TestBed.configureTestingModule({declarations: [App, CountingPipe]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('bob state:0'); }); it('should support bindings', () => { @Directive({ selector: '[my-dir]', standalone: false, }) class Dir { @Input() dirProp: string = ''; } @Pipe({ name: 'double', standalone: false, }) class DoublePipe implements PipeTransform { transform(value: any) { return `${value}${value}`; } } @Component({ template: `<div my-dir [dirProp]="'a'|double"></div>`, standalone: false, }) class App { @ViewChild(Dir) directive!: Dir; } TestBed.configureTestingModule({declarations: [App, DoublePipe, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.directive.dirProp).toBe('aa'); }); it('should support arguments in pipes', () => { @Component({ template: `{{person.name | multiArgPipe:'one':person.address.city}}`, standalone: false, }) class App { person = {name: 'value', address: {city: 'two'}}; } TestBed.configureTestingModule({declarations: [App, MultiArgPipe]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('value one two default'); }); it('should support calling pipes with different number of arguments', () => { @Component({ template: `{{person.name | multiArgPipe:'a':'b'}} {{0 | multiArgPipe:1:2:3}}`, standalone: false, }) class App { person = {name: 'value'}; } TestBed.configureTestingModule({declarations: [App, MultiArgPipe]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('value a b default 0 1 2 3'); }); it('should pick a Pipe defined in `declarations` over imported Pipes', () => { @Pipe({ name: 'number', standalone: false, }) class PipeA implements PipeTransform { transform(value: any) { return `PipeA: ${value}`; } } @NgModule({ declarations: [PipeA], exports: [PipeA], }) class ModuleA {} @Pipe({ name: 'number', standalone: false, }) class PipeB implements PipeTransform { transform(value: any) { return `PipeB: ${value}`; } } @Component({ selector: 'app', template: '{{ count | number }}', standalone: false, }) class App { count = 10; } TestBed.configureTestingModule({ imports: [ModuleA], declarations: [PipeB, App], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('PipeB: 10'); }); it('should respect imported module order when selecting Pipe (last imported Pipe is used)', () => { @Pipe({ name: 'number', standalone: false, }) class PipeA implements PipeTransform { transform(value: any) { return `PipeA: ${value}`; } } @NgModule({ declarations: [PipeA], exports: [PipeA], }) class ModuleA {} @Pipe({ name: 'number', standalone: false, }) class PipeB implements PipeTransform { transform(value: any) { return `PipeB: ${value}`; } } @NgModule({ declarations: [PipeB], exports: [PipeB], }) class ModuleB {} @Component({ selector: 'app', template: '{{ count | number }}', standalone: false, }) class App { count = 10; } TestBed.configureTestingModule({ imports: [ModuleA, ModuleB], declarations: [App], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('PipeB: 10'); }); it('should do nothing when no change', () => { let calls: any[] = []; @Pipe({ name: 'identityPipe', standalone: false, }) class IdentityPipe implements PipeTransform { transform(value: any) { calls.push(value); return value; } } @Component({ template: `{{person.name | identityPipe}}`, standalone: false, }) class App { person = {name: 'Megatron'}; } TestBed.configureTestingModule({declarations: [App, IdentityPipe]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(calls).toEqual(['Megatron']); fixture.detectChanges(); expect(calls).toEqual(['Megatron']); }); it('should support duplicates by using the later entry', () => { @Pipe({ name: 'duplicatePipe', standalone: false, }) class DuplicatePipe1 implements PipeTransform { transform(value: any) { return `${value} from duplicate 1`; } } @Pipe({ name: 'duplicatePipe', standalone: false, }) class DuplicatePipe2 implements PipeTransform { transform(value: any) { return `${value} from duplicate 2`; } } @Component({ template: '{{person.name | duplicatePipe}}', standalone: false, }) class App { person = {name: 'bob'}; } TestBed.configureTestingModule({declarations: [App, DuplicatePipe1, DuplicatePipe2]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('bob from duplicate 2'); }); it('should support pipe in context of ternary operator', () => { @Pipe({ name: 'pipe', standalone: false, }) class MyPipe implements PipeTransform { transform(value: any): any { return value; } } @Component({ template: `{{ condition ? 'a' : 'b' | pipe }}`, standalone: false, }) class App { condition = false; } TestBed.configureTestingModule({declarations: [App, MyPipe]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement).toHaveText('b'); fixture.componentInstance.condition = true; fixture.detectChanges(); expect(fixture.nativeElement).toHaveText('a'); }); // This test uses AOT-generated code, because we can't capture the same behavior that we want // when going through `TestBed`. Here we're testing the behavior of AOT-compiled code which // differs from the JIT code in `TestBed`, because it includes a `ɵɵgetInheritedFactory` call // when the pipe is using inheritance. it('sho
{ "end_byte": 8130, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/pipe_spec.ts" }
angular/packages/core/test/acceptance/pipe_spec.ts_8133_13939
be able to use DI in a Pipe that extends an Injectable', () => { @Injectable({providedIn: 'root'}) class SayHelloService { getHello() { return 'Hello there'; } } // The generated code corresponds to the following decorator: // @Injectable() class ParentPipe { constructor(protected sayHelloService: SayHelloService) {} static ɵfac = (t?: any) => new (t || ParentPipe)(ɵɵinject(SayHelloService)); static ɵprov = ɵɵdefineInjectable({token: ParentPipe, factory: ParentPipe.ɵfac}); } // The generated code corresponds to the following decorator: // @Pipe({name: 'sayHello', pure: true, standalone: true}) class SayHelloPipe extends ParentPipe implements PipeTransform { transform() { return this.sayHelloService.getHello(); } static override ɵfac = (t?: any) => ɵɵgetInheritedFactory(t || SayHelloPipe)(SayHelloPipe); static ɵpipe = ɵɵdefinePipe({ name: 'sayHello', type: SayHelloPipe, pure: true, }); } @Component({ standalone: true, selector: 'app', template: '{{ value | sayHello }}', imports: [SayHelloPipe], }) class AppComponent { value = 'test'; } const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Hello there'); }); describe('pure', () => { it('should call pure pipes only if the arguments change', () => { @Component({ template: '{{person.name | countingPipe}}', standalone: false, }) class App { person = {name: null as string | null}; } TestBed.configureTestingModule({declarations: [App, CountingPipe]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); // change from undefined -> null fixture.componentInstance.person.name = null; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('null state:0'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('null state:0'); // change from null -> some value fixture.componentInstance.person.name = 'bob'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('bob state:1'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('bob state:1'); // change from some value -> some other value fixture.componentInstance.person.name = 'bart'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('bart state:2'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toEqual('bart state:2'); }); }); describe('impure', () => { let impurePipeInstances: CountingImpurePipe[] = []; @Pipe({ name: 'countingImpurePipe', pure: false, standalone: false, }) class CountingImpurePipe implements PipeTransform { state: number = 0; transform(value: any) { return `${value} state:${this.state++}`; } constructor() { impurePipeInstances.push(this); } } beforeEach(() => (impurePipeInstances = [])); afterEach(() => (impurePipeInstances = [])); it('should call impure pipes on each change detection run', () => { @Component({ template: '{{person.name | countingImpurePipe}}', standalone: false, }) class App { person = {name: 'bob'}; } TestBed.configureTestingModule({declarations: [App, CountingImpurePipe]}); const fixture = TestBed.createComponent(App); const pipe = impurePipeInstances[0]; spyOn(pipe, 'transform').and.returnValue(''); expect(pipe.transform).not.toHaveBeenCalled(); fixture.detectChanges(); expect(pipe.transform).toHaveBeenCalledTimes(2); fixture.detectChanges(); expect(pipe.transform).toHaveBeenCalledTimes(4); }); it('should not cache impure pipes', () => { @Component({ template: ` <div [id]="0 | countingImpurePipe">{{1 | countingImpurePipe}}</div> <div [id]="2 | countingImpurePipe">{{3 | countingImpurePipe}}</div> `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, CountingImpurePipe]}); TestBed.createComponent(App); expect(impurePipeInstances.length).toEqual(4); expect(impurePipeInstances[0]).toBeInstanceOf(CountingImpurePipe); expect(impurePipeInstances[1]).toBeInstanceOf(CountingImpurePipe); expect(impurePipeInstances[1]).not.toBe(impurePipeInstances[0]); expect(impurePipeInstances[2]).toBeInstanceOf(CountingImpurePipe); expect(impurePipeInstances[2]).not.toBe(impurePipeInstances[0]); expect(impurePipeInstances[3]).toBeInstanceOf(CountingImpurePipe); expect(impurePipeInstances[3]).not.toBe(impurePipeInstances[0]); }); }); describe('lifecycles', () => { it('should call ngOnDestroy on pipes', () => { let destroyCalls = 0; @Pipe({ name: 'pipeWithOnDestroy', standalone: false, }) class PipeWithOnDestroy implements PipeTransform, OnDestroy { ngOnDestroy() { destroyCalls++; } transform(value: any): any { return null; } } @Component({ template: '{{1 | pipeWithOnDestroy}}', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, PipeWithOnDestroy]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(destroyCalls).toBe(1); }); }); describe('injection
{ "end_byte": 13939, "start_byte": 8133, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/pipe_spec.ts" }
angular/packages/core/test/acceptance/pipe_spec.ts_13943_20332
hanism', () => { it('should be able to handle Service injection', () => { @Injectable() class Service { title = 'Service Title'; } @Pipe({ name: 'myConcatPipe', standalone: false, }) class ConcatPipe implements PipeTransform { constructor(public service: Service) {} transform(value: string): string { return `${value} - ${this.service.title}`; } } @Component({ template: '{{title | myConcatPipe}}', standalone: false, }) class App { title = 'MyComponent Title'; } TestBed.configureTestingModule({declarations: [App, ConcatPipe], providers: [Service]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('MyComponent Title - Service Title'); }); it('should be able to handle Token injections', () => { class Service { title = 'Service Title'; } const token = new InjectionToken<Service>('service token'); @Pipe({ name: 'myConcatPipe', standalone: false, }) class ConcatPipe implements PipeTransform { constructor(@Inject(token) public service: Service) {} transform(value: string): string { return `${value} - ${this.service.title}`; } } @Component({ template: '{{title | myConcatPipe}}', standalone: false, }) class App { title = 'MyComponent Title'; } TestBed.configureTestingModule({ declarations: [App, ConcatPipe], providers: [{provide: token, useValue: new Service()}], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('MyComponent Title - Service Title'); }); it('should be able to handle Module injection', () => { @Injectable() class Service { title = 'Service Title'; } @NgModule({providers: [Service]}) class SomeModule {} @Pipe({ name: 'myConcatPipe', standalone: false, }) class ConcatPipe implements PipeTransform { constructor(public service: Service) {} transform(value: string): string { return `${value} - ${this.service.title}`; } } @Component({ template: '{{title | myConcatPipe}}', standalone: false, }) class App { title = 'MyComponent Title'; } TestBed.configureTestingModule({declarations: [App, ConcatPipe], imports: [SomeModule]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('MyComponent Title - Service Title'); }); it('should inject the ChangeDetectorRef of the containing view when using pipe inside a component input', () => { let pipeChangeDetectorRef: ChangeDetectorRef | undefined; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, selector: 'some-comp', template: 'Inner value: "{{displayValue}}"', standalone: false, }) class SomeComp { @Input() value: any; displayValue = 0; } @Component({ changeDetection: ChangeDetectionStrategy.OnPush, template: ` <some-comp [value]="pipeValue | testPipe"></some-comp> Outer value: "{{displayValue}}" `, standalone: false, }) class App { @Input() something: any; @ViewChild(SomeComp) comp!: SomeComp; pipeValue = 10; displayValue = 0; } @Pipe({ name: 'testPipe', standalone: false, }) class TestPipe implements PipeTransform { constructor(changeDetectorRef: ChangeDetectorRef) { pipeChangeDetectorRef = changeDetectorRef; } transform() { return ''; } } TestBed.configureTestingModule({declarations: [App, SomeComp, TestPipe]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.componentInstance.displayValue = 1; fixture.componentInstance.comp.displayValue = 1; pipeChangeDetectorRef!.markForCheck(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Outer value: "1"'); expect(fixture.nativeElement.textContent).toContain('Inner value: "0"'); }); it('should inject the ChangeDetectorRef of the containing view when using pipe inside a component input which has child nodes', () => { let pipeChangeDetectorRef: ChangeDetectorRef | undefined; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, selector: 'some-comp', template: 'Inner value: "{{displayValue}}" <ng-content></ng-content>', standalone: false, }) class SomeComp { @Input() value: any; displayValue = 0; } @Component({ changeDetection: ChangeDetectionStrategy.OnPush, template: ` <some-comp [value]="pipeValue | testPipe"> <div>Hello</div> </some-comp> Outer value: "{{displayValue}}" `, standalone: false, }) class App { @Input() something: any; @ViewChild(SomeComp) comp!: SomeComp; pipeValue = 10; displayValue = 0; } @Pipe({ name: 'testPipe', standalone: false, }) class TestPipe implements PipeTransform { constructor(changeDetectorRef: ChangeDetectorRef) { pipeChangeDetectorRef = changeDetectorRef; } transform() { return ''; } } TestBed.configureTestingModule({declarations: [App, SomeComp, TestPipe]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.componentInstance.displayValue = 1; fixture.componentInstance.comp.displayValue = 1; pipeChangeDetectorRef!.markForCheck(); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Outer value: "1"'); expect(fixture.nativeElement.textContent).toContain('Inner value: "0"'); }); }); describe('pure pipe
{ "end_byte": 20332, "start_byte": 13943, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/pipe_spec.ts" }
angular/packages/core/test/acceptance/pipe_spec.ts_20336_29757
or handling', () => { it('should not re-invoke pure pipes if it fails initially', () => { @Pipe({ name: 'throwPipe', pure: true, standalone: false, }) class ThrowPipe implements PipeTransform { transform(): never { throw new Error('ThrowPipeError'); } } @Component({ template: `{{val | throwPipe}}`, standalone: false, }) class App { val = 'anything'; } const fixture = TestBed.configureTestingModule({ declarations: [App, ThrowPipe], }).createComponent(App); // first invocation expect(() => fixture.detectChanges()).toThrowError(/ThrowPipeError/); // second invocation - should not throw fixture.detectChanges(); }); it('should display the last known result from a pure pipe when it throws', () => { @Pipe({ name: 'throwPipe', pure: true, standalone: false, }) class ThrowPipe implements PipeTransform { transform(value: string): string { if (value === 'KO') { throw new Error('ThrowPipeError'); } else { return value; } } } @Component({ template: `{{val | throwPipe}}`, standalone: false, }) class App { val = 'anything'; } const fixture = TestBed.configureTestingModule({ declarations: [App, ThrowPipe], }).createComponent(App); // first invocation - no error thrown fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('anything'); // second invocation when the error is thrown fixture.componentInstance.val = 'KO'; expect(() => fixture.detectChanges()).toThrowError(/ThrowPipeError/); expect(fixture.nativeElement.textContent).toBe('anything'); // third invocation with no changes to input - should not thrown and preserve the last known // results fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('anything'); }); describe('pure pipe error handling with multiple arguments', () => { const args: string[] = new Array(10).fill(':0'); for (let numberOfPipeArgs = 0; numberOfPipeArgs < args.length; numberOfPipeArgs++) { it(`should not invoke ${numberOfPipeArgs} argument pure pipe second time if it throws unless input changes`, () => { // https://stackblitz.com/edit/angular-mbx2pg const log: string[] = []; @Pipe({ name: 'throw', pure: true, standalone: false, }) class ThrowPipe implements PipeTransform { transform(): never { log.push('throw'); throw new Error('ThrowPipeError'); } } @Component({ template: `{{val | throw${args.slice(0, numberOfPipeArgs).join('')}}}`, standalone: false, }) class App { val = 'anything'; } const fixture = TestBed.configureTestingModule({ declarations: [App, ThrowPipe], }).createComponent(App); // First invocation of detect changes should throw. expect(() => fixture.detectChanges()).toThrowError(/ThrowPipeError/); expect(log).toEqual(['throw']); // Second invocation should not throw as input to the `throw` pipe has not changed and // the pipe is pure. log.length = 0; expect(() => fixture.detectChanges()).not.toThrow(); expect(log).toEqual([]); fixture.componentInstance.val = 'change'; // First invocation of detect changes should throw because the input changed. expect(() => fixture.detectChanges()).toThrowError(/ThrowPipeError/); expect(log).toEqual(['throw']); // Second invocation should not throw as input to the `throw` pipe has not changed and // the pipe is pure. log.length = 0; expect(() => fixture.detectChanges()).not.toThrow(); expect(log).toEqual([]); }); } }); }); [false, true].forEach((componentIsStandalone) => { const expectedThrowRegex = new RegExp( "The pipe 'testMissingPipe' could not be found in the 'TestComponent' component." + (componentIsStandalone ? " Verify that it is included in the '@Component.imports' of this component" : ' Verify that it is declared or imported in this module'), ); describe(`missing pipe detection logic (inside ${ componentIsStandalone ? '' : 'non-' }standalone component)`, () => { it(`should throw an error if a pipe is not found in a component`, () => { @Component({ template: '{{ 1 | testMissingPipe }}', standalone: componentIsStandalone, }) class TestComponent {} if (!componentIsStandalone) { TestBed.configureTestingModule({declarations: [TestComponent]}); } expect(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); }).toThrowError(expectedThrowRegex); }); it('should throw an error if a pipe is not found inside an inline template', () => { @Component({ template: ` <ng-container *ngIf="true"> {{ value | testMissingPipe }} </ng-container>`, standalone: componentIsStandalone, ...(componentIsStandalone ? {imports: [CommonModule]} : {}), }) class TestComponent { value: string = 'test'; } if (!componentIsStandalone) { TestBed.configureTestingModule({declarations: [TestComponent]}); } expect(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); }).toThrowError(expectedThrowRegex); }); it('should throw an error if a pipe is not found inside a projected content', () => { @Component({ selector: 'app-test-child', template: '<ng-content></ng-content>', standalone: componentIsStandalone, }) class TestChildComponent {} @Component({ template: ` <app-test-child> {{ value | testMissingPipe }} </app-test-child>`, standalone: componentIsStandalone, ...(componentIsStandalone ? {imports: [TestChildComponent]} : {}), }) class TestComponent { value: string = 'test'; } if (!componentIsStandalone) { TestBed.configureTestingModule({declarations: [TestComponent, TestChildComponent]}); } expect(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); }).toThrowError(expectedThrowRegex); }); it('should throw an error if a pipe is not found inside a projected content in an inline template', () => { @Component({ selector: 'app-test-child', template: '<ng-content></ng-content>', standalone: componentIsStandalone, }) class TestChildComponent {} @Component({ template: ` <app-test-child> <ng-container *ngIf="true"> {{ value | testMissingPipe }} </ng-container> </app-test-child>`, standalone: componentIsStandalone, ...(componentIsStandalone ? {imports: [TestChildComponent, CommonModule]} : {}), }) class TestComponent { value: string = 'test'; } if (!componentIsStandalone) { TestBed.configureTestingModule({declarations: [TestComponent, TestChildComponent]}); } expect(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); }).toThrowError(expectedThrowRegex); }); it('should throw an error if a pipe is not found in a property binding', () => { @Component({ template: '<div [title]="value | testMissingPipe"></div>', standalone: componentIsStandalone, }) class TestComponent { value: string = 'test'; } if (!componentIsStandalone) { TestBed.configureTestingModule({declarations: [TestComponent]}); } expect(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); }).toThrowError(expectedThrowRegex); }); it('should throw an error if a pipe is not found inside a structural directive input', () => { @Component({ template: '<div *ngIf="isVisible | testMissingPipe"></div>', standalone: componentIsStandalone, ...(componentIsStandalone ? {imports: [CommonModule]} : {}), }) class TestComponent { isVisible: boolean = true; } if (!componentIsStandalone) { TestBed.configureTestingModule({declarations: [TestComponent]}); } expect(() => { const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); }).toThrowError(expectedThrowRegex); }); }); }); });
{ "end_byte": 29757, "start_byte": 20336, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/pipe_spec.ts" }
angular/packages/core/test/acceptance/internal_spec.ts_0_4990
/*! * @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, Directive, EnvironmentInjector, ɵgetClosestComponentName as getClosestComponentName, ViewChild, ViewContainerRef, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; describe('internal utilities', () => { describe('getClosestComponentName', () => { it('should get the name from a node placed inside a root component', () => { @Component({ standalone: true, template: `<section><div class="target"></div></section>`, }) class App {} const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(getClosestComponentName(fixture.nativeElement)).toBe('App'); expect(getClosestComponentName(fixture.nativeElement.querySelector('.target'))).toBe('App'); }); it('should get the name from a node placed inside a component', () => { @Component({ selector: 'comp', template: `<section><div class="target"></div></section>`, standalone: true, }) class Comp {} @Component({ standalone: true, template: `<comp/>`, imports: [Comp], }) class App {} const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(getClosestComponentName(fixture.nativeElement.querySelector('comp'))).toBe('Comp'); expect(getClosestComponentName(fixture.nativeElement.querySelector('.target'))).toBe('Comp'); }); it('should get the name from a node placed inside a repeated component', () => { @Component({ selector: 'comp', template: `<section><div class="target"></div></section>`, standalone: true, }) class Comp {} @Component({ standalone: true, template: ` @for (current of [1]; track $index) { <comp/> } `, imports: [Comp], }) class App {} const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(getClosestComponentName(fixture.nativeElement.querySelector('comp'))).toBe('Comp'); expect(getClosestComponentName(fixture.nativeElement.querySelector('.target'))).toBe('Comp'); }); it('should get the name from a node that has a directive', () => { @Directive({ selector: 'dir', standalone: true, }) class Dir {} @Component({ standalone: true, template: `<section><dir class="target"></dir></section>`, imports: [Dir], }) class App {} const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(getClosestComponentName(fixture.nativeElement)).toBe('App'); expect(getClosestComponentName(fixture.nativeElement.querySelector('.target'))).toBe('App'); }); it('should return null when not placed in a component', () => { @Component({ standalone: true, template: '', }) class App {} const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(getClosestComponentName(document.body)).toBe(null); }); it('should get the name from a node placed inside a dynamically-created component through ViewContainerRef', () => { @Component({ selector: 'comp', template: `<section><div class="target"></div></section>`, standalone: true, }) class Comp {} @Component({ standalone: true, template: `<ng-container #insertionPoint/>`, }) class App { @ViewChild('insertionPoint', {read: ViewContainerRef}) vcr!: ViewContainerRef; } const fixture = TestBed.createComponent(App); fixture.detectChanges(); const ref = fixture.componentInstance.vcr.createComponent(Comp); fixture.detectChanges(); expect(getClosestComponentName(fixture.nativeElement.querySelector('comp'))).toBe('Comp'); expect(getClosestComponentName(fixture.nativeElement.querySelector('.target'))).toBe('Comp'); ref.destroy(); }); it('should get the name from a node placed inside a dynamically-created component through createComponent', () => { @Component({ selector: 'comp', template: `<section><div class="target"></div></section>`, standalone: true, }) class Comp {} TestBed.configureTestingModule({}); const ref = createComponent(Comp, {environmentInjector: TestBed.inject(EnvironmentInjector)}); ref.changeDetectorRef.detectChanges(); expect(getClosestComponentName(ref.location.nativeElement)).toBe('Comp'); expect(getClosestComponentName(ref.location.nativeElement.querySelector('.target'))).toBe( 'Comp', ); ref.destroy(); }); }); });
{ "end_byte": 4990, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/internal_spec.ts" }
angular/packages/core/test/acceptance/bootstrap_spec.ts_0_7175
/** * @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, COMPILER_OPTIONS, Component, destroyPlatform, forwardRef, NgModule, NgZone, provideExperimentalZonelessChangeDetection, provideZoneChangeDetection, TestabilityRegistry, ViewContainerRef, ViewEncapsulation, ɵNoopNgZone, ɵZONELESS_ENABLED, } from '@angular/core'; import {bootstrapApplication, BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {withBody} from '@angular/private/testing'; describe('bootstrap', () => { beforeEach(destroyPlatform); afterEach(destroyPlatform); it( 'should bootstrap using #id selector', withBody('<div>before|</div><button id="my-app"></button>', async () => { try { const ngModuleRef = await platformBrowserDynamic().bootstrapModule(IdSelectorAppModule); expect(document.body.textContent).toEqual('before|works!'); ngModuleRef.destroy(); } catch (err) { console.error(err); } }), ); it( 'should bootstrap using one of selectors from the list', withBody('<div>before|</div><div class="bar"></div>', async () => { try { const ngModuleRef = await platformBrowserDynamic().bootstrapModule( MultipleSelectorsAppModule, ); expect(document.body.textContent).toEqual('before|works!'); ngModuleRef.destroy(); } catch (err) { console.error(err); } }), ); it( 'should allow injecting VCRef into the root (bootstrapped) component', withBody('before|<test-cmp></test-cmp>|after', async () => { @Component({selector: 'dynamic-cmp', standalone: true, template: 'dynamic'}) class DynamicCmp {} @Component({selector: 'test-cmp', standalone: true, template: '(test)'}) class TestCmp { constructor(public vcRef: ViewContainerRef) {} } expect(document.body.textContent).toEqual('before||after'); const appRef = await bootstrapApplication(TestCmp); expect(document.body.textContent).toEqual('before|(test)|after'); appRef.components[0].instance.vcRef.createComponent(DynamicCmp); expect(document.body.textContent).toEqual('before|(test)dynamic|after'); appRef.destroy(); expect(document.body.textContent).toEqual('before||after'); }), ); describe('options', () => { function createComponentAndModule( options: { encapsulation?: ViewEncapsulation; preserveWhitespaces?: boolean; selector?: string; } = {}, ) { @Component({ selector: options.selector || 'my-app', // styles must be non-empty to trigger `ViewEncapsulation.Emulated` styles: 'span {color:red}', template: '<span>a b</span>', encapsulation: options.encapsulation, preserveWhitespaces: options.preserveWhitespaces, jit: true, standalone: false, }) class TestComponent {} @NgModule({ imports: [BrowserModule], declarations: [TestComponent], bootstrap: [TestComponent], jit: true, }) class TestModule {} return TestModule; } it( 'should use ViewEncapsulation.Emulated as default', withBody('<my-app></my-app>', async () => { const TestModule = createComponentAndModule(); const ngModuleRef = await platformBrowserDynamic().bootstrapModule(TestModule); expect(document.body.innerHTML).toContain('<span _ngcontent-'); ngModuleRef.destroy(); }), ); it( 'should allow setting defaultEncapsulation using bootstrap option', withBody('<my-app></my-app>', async () => { const TestModule = createComponentAndModule(); const ngModuleRef = await platformBrowserDynamic().bootstrapModule(TestModule, { defaultEncapsulation: ViewEncapsulation.None, }); expect(document.body.innerHTML).toContain('<span>'); expect(document.body.innerHTML).not.toContain('_ngcontent-'); ngModuleRef.destroy(); }), ); it( 'should allow setting defaultEncapsulation using compiler option', withBody('<my-app></my-app>', async () => { const TestModule = createComponentAndModule(); const ngModuleRef = await platformBrowserDynamic([ { provide: COMPILER_OPTIONS, useValue: {defaultEncapsulation: ViewEncapsulation.None}, multi: true, }, ]).bootstrapModule(TestModule); expect(document.body.innerHTML).toContain('<span>'); expect(document.body.innerHTML).not.toContain('_ngcontent-'); ngModuleRef.destroy(); }), ); it( 'should prefer encapsulation on component over bootstrap option', withBody('<my-app></my-app>', async () => { const TestModule = createComponentAndModule({encapsulation: ViewEncapsulation.Emulated}); const ngModuleRef = await platformBrowserDynamic().bootstrapModule(TestModule, { defaultEncapsulation: ViewEncapsulation.None, }); expect(document.body.innerHTML).toContain('<span _ngcontent-'); ngModuleRef.destroy(); }), ); it( 'should use preserveWhitespaces: false as default', withBody('<my-app></my-app>', async () => { const TestModule = createComponentAndModule(); const ngModuleRef = await platformBrowserDynamic().bootstrapModule(TestModule); expect(document.body.innerHTML).toContain('a b'); ngModuleRef.destroy(); }), ); it( 'should allow setting preserveWhitespaces using bootstrap option', withBody('<my-app></my-app>', async () => { const TestModule = createComponentAndModule(); const ngModuleRef = await platformBrowserDynamic().bootstrapModule(TestModule, { preserveWhitespaces: true, }); expect(document.body.innerHTML).toContain('a b'); ngModuleRef.destroy(); }), ); it( 'should allow setting preserveWhitespaces using compiler option', withBody('<my-app></my-app>', async () => { const TestModule = createComponentAndModule(); const ngModuleRef = await platformBrowserDynamic([ {provide: COMPILER_OPTIONS, useValue: {preserveWhitespaces: true}, multi: true}, ]).bootstrapModule(TestModule); expect(document.body.innerHTML).toContain('a b'); ngModuleRef.destroy(); }), ); it( 'should prefer preserveWhitespaces on component over bootstrap option', withBody('<my-app></my-app>', async () => { const TestModule = createComponentAndModule({preserveWhitespaces: false}); const ngModuleRef = await platformBrowserDynamic().bootstrapModule(TestModule, { preserveWhitespaces: true, }); expect(document.body.innerHTML).toContain('a b'); ngModuleRef.destroy(); }), );
{ "end_byte": 7175, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/bootstrap_spec.ts" }
angular/packages/core/test/acceptance/bootstrap_spec.ts_7181_15117
scribe('ApplicationRef cleanup', () => { it( 'should cleanup ApplicationRef when Injector is destroyed', withBody('<my-app></my-app>', async () => { const TestModule = createComponentAndModule(); const ngModuleRef = await platformBrowserDynamic().bootstrapModule(TestModule); const appRef = ngModuleRef.injector.get(ApplicationRef); const testabilityRegistry = ngModuleRef.injector.get(TestabilityRegistry); expect(appRef.components.length).toBe(1); expect(testabilityRegistry.getAllRootElements().length).toBe(1); ngModuleRef.destroy(); // also destroys an Injector instance. expect(appRef.components.length).toBe(0); expect(testabilityRegistry.getAllRootElements().length).toBe(0); }), ); it( 'should cleanup ApplicationRef when ComponentRef is destroyed', withBody('<my-app></my-app>', async () => { const TestModule = createComponentAndModule(); const ngModuleRef = await platformBrowserDynamic().bootstrapModule(TestModule); const appRef = ngModuleRef.injector.get(ApplicationRef); const testabilityRegistry = ngModuleRef.injector.get(TestabilityRegistry); const componentRef = appRef.components[0]; expect(appRef.components.length).toBe(1); expect(testabilityRegistry.getAllRootElements().length).toBe(1); componentRef.destroy(); expect(appRef.components.length).toBe(0); expect(testabilityRegistry.getAllRootElements().length).toBe(0); }), ); it( 'should not throw in case ComponentRef is destroyed and Injector is destroyed after that', withBody('<my-app></my-app>', async () => { const TestModule = createComponentAndModule(); const ngModuleRef = await platformBrowserDynamic().bootstrapModule(TestModule); const appRef = ngModuleRef.injector.get(ApplicationRef); const testabilityRegistry = ngModuleRef.injector.get(TestabilityRegistry); const componentRef = appRef.components[0]; expect(appRef.components.length).toBe(1); expect(testabilityRegistry.getAllRootElements().length).toBe(1); componentRef.destroy(); ngModuleRef.destroy(); // also destroys an Injector instance. expect(appRef.components.length).toBe(0); expect(testabilityRegistry.getAllRootElements().length).toBe(0); }), ); it( 'should not throw in case Injector is destroyed and ComponentRef is destroyed after that', withBody('<my-app></my-app>', async () => { const TestModule = createComponentAndModule(); const ngModuleRef = await platformBrowserDynamic().bootstrapModule(TestModule); const appRef = ngModuleRef.injector.get(ApplicationRef); const testabilityRegistry = ngModuleRef.injector.get(TestabilityRegistry); const componentRef = appRef.components[0]; expect(appRef.components.length).toBe(1); expect(testabilityRegistry.getAllRootElements().length).toBe(1); ngModuleRef.destroy(); // also destroys an Injector instance. componentRef.destroy(); expect(appRef.components.length).toBe(0); expect(testabilityRegistry.getAllRootElements().length).toBe(0); }), ); it( 'should throw when standalone component is used in @NgModule.bootstrap', withBody('<my-app></my-app>', async () => { @Component({ standalone: true, selector: 'standalone-comp', template: '...', }) class StandaloneComponent {} @NgModule({ bootstrap: [StandaloneComponent], }) class MyModule {} try { await platformBrowserDynamic().bootstrapModule(MyModule); // This test tries to bootstrap a standalone component using NgModule-based bootstrap // mechanisms. We expect standalone components to be bootstrapped via // `bootstrapApplication` API instead. fail('Expected to throw'); } catch (e: unknown) { const expectedErrorMessage = 'The `StandaloneComponent` class is a standalone component, ' + 'which can not be used in the `@NgModule.bootstrap` array.'; expect(e).toBeInstanceOf(Error); expect((e as Error).message).toContain(expectedErrorMessage); } }), ); it( 'can configure zone with provideZoneChangeDetection', withBody('<my-app></my-app>', async () => { @Component({ selector: 'my-app', template: '...', standalone: false, }) class App {} @NgModule({ declarations: [App], providers: [provideZoneChangeDetection({eventCoalescing: true})], imports: [BrowserModule], bootstrap: [App], }) class MyModule {} const {injector} = await platformBrowserDynamic().bootstrapModule(MyModule); expect((injector.get(NgZone) as any).shouldCoalesceEventChangeDetection).toBe(true); }), ); it( 'can configure zoneless correctly without `ngZone: "noop"`', withBody('<my-app></my-app>', async () => { @Component({ selector: 'my-app', template: '...', standalone: false, }) class App {} @NgModule({ declarations: [App], providers: [provideExperimentalZonelessChangeDetection()], imports: [BrowserModule], bootstrap: [App], }) class MyModule {} const {injector} = await platformBrowserDynamic().bootstrapModule(MyModule); expect(injector.get(NgZone)).toBeInstanceOf(ɵNoopNgZone); expect(injector.get(ɵZONELESS_ENABLED)).toBeTrue(); }), ); it( 'should throw when standalone component wrapped in `forwardRef` is used in @NgModule.bootstrap', withBody('<my-app></my-app>', async () => { @Component({ standalone: true, selector: 'standalone-comp', template: '...', }) class StandaloneComponent {} @NgModule({ bootstrap: [forwardRef(() => StandaloneComponent)], }) class MyModule {} try { await platformBrowserDynamic().bootstrapModule(MyModule); // This test tries to bootstrap a standalone component using NgModule-based bootstrap // mechanisms. We expect standalone components to be bootstrapped via // `bootstrapApplication` API instead. fail('Expected to throw'); } catch (e: unknown) { const expectedErrorMessage = 'The `StandaloneComponent` class is a standalone component, which ' + 'can not be used in the `@NgModule.bootstrap` array. Use the `bootstrapApplication` ' + 'function for bootstrap instead.'; expect(e).toBeInstanceOf(Error); expect((e as Error).message).toContain(expectedErrorMessage); } }), ); }); describe('PlatformRef cleanup', () => { it( 'should unsubscribe from `onError` when Injector is destroyed', withBody('<my-app></my-app>', async () => { const TestModule = createComponentAndModule(); const ngModuleRef = await platformBrowserDynamic().bootstrapModule(TestModule); const ngZone = ngModuleRef.injector.get(NgZone); expect(ngZone.onError.observers.length).toBe(1); ngModuleRef.destroy(); expect(ngZone.onError.observers.length).toBe(0); }), ); });
{ "end_byte": 15117, "start_byte": 7181, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/bootstrap_spec.ts" }
angular/packages/core/test/acceptance/bootstrap_spec.ts_15123_21011
ribe('changing bootstrap options', () => { beforeEach(() => { spyOn(console, 'error'); }); it( 'should log an error when changing defaultEncapsulation bootstrap options', withBody('<my-app-a></my-app-a><my-app-b></my-app-b>', async () => { const platformRef = platformBrowserDynamic(); const TestModuleA = createComponentAndModule({selector: 'my-app-a'}); const ngModuleRefA = await platformRef.bootstrapModule(TestModuleA, { defaultEncapsulation: ViewEncapsulation.None, }); ngModuleRefA.destroy(); const TestModuleB = createComponentAndModule({selector: 'my-app-b'}); const ngModuleRefB = await platformRef.bootstrapModule(TestModuleB, { defaultEncapsulation: ViewEncapsulation.ShadowDom, }); expect(console.error).toHaveBeenCalledWith( 'Provided value for `defaultEncapsulation` can not be changed once it has been set.', ); // The options should not have been changed expect(document.body.innerHTML).not.toContain('_ngcontent-'); ngModuleRefB.destroy(); }), ); it( 'should log an error when changing preserveWhitespaces bootstrap options', withBody('<my-app-a></my-app-a><my-app-b></my-app-b>', async () => { const platformRef = platformBrowserDynamic(); const TestModuleA = createComponentAndModule({selector: 'my-app-a'}); const ngModuleRefA = await platformRef.bootstrapModule(TestModuleA, { preserveWhitespaces: true, }); ngModuleRefA.destroy(); const TestModuleB = createComponentAndModule({selector: 'my-app-b'}); const ngModuleRefB = await platformRef.bootstrapModule(TestModuleB, { preserveWhitespaces: false, }); expect(console.error).toHaveBeenCalledWith( 'Provided value for `preserveWhitespaces` can not be changed once it has been set.', ); // The options should not have been changed expect(document.body.innerHTML).toContain('a b'); ngModuleRefB.destroy(); }), ); it( 'should log an error when changing defaultEncapsulation to its default', withBody('<my-app-a></my-app-a><my-app-b></my-app-b>', async () => { const platformRef = platformBrowserDynamic(); const TestModuleA = createComponentAndModule({selector: 'my-app-a'}); const ngModuleRefA = await platformRef.bootstrapModule(TestModuleA); ngModuleRefA.destroy(); const TestModuleB = createComponentAndModule({selector: 'my-app-b'}); const ngModuleRefB = await platformRef.bootstrapModule(TestModuleB, { defaultEncapsulation: ViewEncapsulation.Emulated, }); // Although the configured value may be identical to the default, the provided set of // options has still been changed compared to the previously provided options. expect(console.error).toHaveBeenCalledWith( 'Provided value for `defaultEncapsulation` can not be changed once it has been set.', ); ngModuleRefB.destroy(); }), ); it( 'should log an error when changing preserveWhitespaces to its default', withBody('<my-app-a></my-app-a><my-app-b></my-app-b>', async () => { const platformRef = platformBrowserDynamic(); const TestModuleA = createComponentAndModule({selector: 'my-app-a'}); const ngModuleRefA = await platformRef.bootstrapModule(TestModuleA); ngModuleRefA.destroy(); const TestModuleB = createComponentAndModule({selector: 'my-app-b'}); const ngModuleRefB = await platformRef.bootstrapModule(TestModuleB, { preserveWhitespaces: false, }); // Although the configured value may be identical to the default, the provided set of // options has still been changed compared to the previously provided options. expect(console.error).toHaveBeenCalledWith( 'Provided value for `preserveWhitespaces` can not be changed once it has been set.', ); ngModuleRefB.destroy(); }), ); it( 'should not log an error when passing identical bootstrap options', withBody('<my-app-a></my-app-a><my-app-b></my-app-b>', async () => { const platformRef = platformBrowserDynamic(); const TestModuleA = createComponentAndModule({selector: 'my-app-a'}); const ngModuleRefA = await platformRef.bootstrapModule(TestModuleA, { defaultEncapsulation: ViewEncapsulation.None, preserveWhitespaces: true, }); ngModuleRefA.destroy(); // Bootstrapping multiple modules using the exact same options should be allowed. const TestModuleB = createComponentAndModule({selector: 'my-app-b'}); const ngModuleRefB = await platformRef.bootstrapModule(TestModuleB, { defaultEncapsulation: ViewEncapsulation.None, preserveWhitespaces: true, }); ngModuleRefB.destroy(); }), ); }); }); }); @Component({ selector: '#my-app', template: 'works!', standalone: false, }) export class IdSelectorAppComponent {} @NgModule({ imports: [BrowserModule], declarations: [IdSelectorAppComponent], bootstrap: [IdSelectorAppComponent], }) export class IdSelectorAppModule {} @Component({ selector: '[foo],span,.bar', template: 'works!', standalone: false, }) export class MultipleSelectorsAppComponent {} @NgModule({ imports: [BrowserModule], declarations: [MultipleSelectorsAppComponent], bootstrap: [MultipleSelectorsAppComponent], }) export class MultipleSelectorsAppModule {}
{ "end_byte": 21011, "start_byte": 15123, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/bootstrap_spec.ts" }
angular/packages/core/test/acceptance/let_spec.ts_0_457
/** * @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, Output, EventEmitter, ErrorHandler, Pipe, PipeTransform, inject, ChangeDetectorRef, ViewChild, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; describe('@let declarations', () =>
{ "end_byte": 457, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/let_spec.ts" }
angular/packages/core/test/acceptance/let_spec.ts_458_9754
{ it('should update the value of a @let declaration over time', () => { @Component({ standalone: true, template: ` @let multiplier = 2; @let result = value * multiplier; {{value}} times {{multiplier}} is {{result}} `, }) class TestComponent { value = 0; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('0 times 2 is 0'); fixture.componentInstance.value = 1; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('1 times 2 is 2'); fixture.componentInstance.value = 2; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('2 times 2 is 4'); }); it('should be able to use @let declarations inside event listeners', () => { const values: number[] = []; @Component({ standalone: true, template: ` @let result = value * 2; <button (click)="log(result)"></button> `, }) class TestComponent { value = 0; log(value: number) { values.push(value); } } const fixture = TestBed.createComponent(TestComponent); const button: HTMLButtonElement = fixture.nativeElement.querySelector('button'); fixture.detectChanges(); expect(values).toEqual([]); button.click(); expect(values).toEqual([0]); fixture.componentInstance.value = 2; fixture.detectChanges(); button.click(); expect(values).toEqual([0, 4]); }); it('should be able to access @let declarations through multiple levels of views', () => { @Component({ standalone: true, template: ` @if (true) { @if (true) { @let three = two + 1; The result is {{three}} } @let two = one + 1; } @let one = value + 1; `, }) class TestComponent { value = 0; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('The result is 3'); fixture.componentInstance.value = 2; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('The result is 5'); }); it('should be able to access @let declarations from parent view before they are declared', () => { @Component({ standalone: true, template: ` @if (true) { {{value}} times {{multiplier}} is {{result}} } @let multiplier = 2; @let result = value * multiplier; `, }) class TestComponent { value = 0; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('0 times 2 is 0'); fixture.componentInstance.value = 1; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('1 times 2 is 2'); fixture.componentInstance.value = 2; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('2 times 2 is 4'); }); it('should throw if a @let declaration is accessed before it is initialized', () => { const errors: string[] = []; @Directive({ selector: '[dir]', standalone: true, }) class TestDirective { @Output() testEvent = new EventEmitter<void>(); ngOnInit() { this.testEvent.emit(); } } @Component({ standalone: true, imports: [TestDirective], template: ` <div dir (testEvent)="callback(value)"></div> @let value = 1; `, }) class TestComponent { callback(_value: number) {} } TestBed.configureTestingModule({ imports: [TestComponent], providers: [ // We can't use `toThrow` in the tests, because errors in listeners // are caught. Capture them using a custom ErrorHandler instead. { provide: ErrorHandler, useValue: { handleError: (error: Error) => errors.push(error.message), }, }, ], }); const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(errors.length).toBe(1); expect(errors[0]).toContain( 'Attempting to access a @let declaration whose value is not available yet', ); }); it('should be able to use pipes injecting ChangeDetectorRef in a let declaration', () => { @Pipe({name: 'double', standalone: true}) class DoublePipe implements PipeTransform { changeDetectorRef = inject(ChangeDetectorRef); transform(value: number) { return value * 2; } } @Component({ standalone: true, template: ` @let result = value | double; Result: {{result}} `, imports: [DoublePipe], }) class TestComponent { value = 2; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Result: 4'); fixture.componentInstance.value = 5; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Result: 10'); }); it('should be able to use local references inside @let declarations', () => { @Component({ standalone: true, template: ` <input #firstName value="Frodo" name="first-name"> <input #lastName value="Baggins"> @let fullName = firstName.value + ' ' + lastName.value; Hello, {{fullName}} `, }) class TestComponent {} const fixture = TestBed.createComponent(TestComponent); const firstNameInput = fixture.nativeElement.querySelector('[name="first-name"]'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Hello, Frodo Baggins'); firstNameInput.value = 'Bilbo'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Hello, Bilbo Baggins'); }); it('should be able to proxy a local reference through @let declarations', () => { @Component({ standalone: true, template: ` <input #input value="foo"> @let one = input; @if (true) { @let two = one; @if (true) { The value is {{two.value}} } } `, }) class TestComponent {} const fixture = TestBed.createComponent(TestComponent); const input = fixture.nativeElement.querySelector('input'); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('The value is foo'); input.value = 'bar'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('The value is bar'); }); it('should evaluate unused let declarations', () => { let calls = 0; @Component({ standalone: true, template: ` @let one = getOne(); @let two = one + getTwo(); @let three = two + getThree(); `, }) class TestComponent { getOne(): number { calls++; return 1; } getTwo(): number { calls++; return 2; } getThree(): number { calls++; return 3; } } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(calls).toBeGreaterThan(0); }); it('should resolve a @let declaration correctly within an embedded view that uses a value from parent view and cannot be optimized', () => { @Component({ standalone: true, template: ` @let foo = value + 1; @if (true) { <div> @let bar = foo + 1; bar is {{bar}} <button (click)="callback(bar)">I'm here to prevent the optimization of "bar"</button> </div> } `, }) class TestComponent { value = 0; callback(value: number) {} } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('bar is 2'); fixture.componentInstance.value = 2; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('bar is 4'); }); it('should not be able to access @let declarations using a query', () => { @Component({ standalone: true, template: ` @let value = 1; {{value}} `, }) class TestComponent { @ViewChild('value') value: any; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.componentInstance.value).toBeUndefined(); }); it('should be able to access @let declaration from inside ng-content', () => { @Component({ selector: 'inner', template: ` @let value = 123; <ng-content>The value is {{value}}</ng-content> `, standalone: true, }) class InnerComponent {} @Component({ standalone: true, template: '<inner/>', imports: [InnerComponent], }) class TestComponent {} const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('The value is 123'); });
{ "end_byte": 9754, "start_byte": 458, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/let_spec.ts" }
angular/packages/core/test/acceptance/let_spec.ts_9758_12305
it('should not project let declarations', () => { @Component({ selector: 'inner', template: ` <ng-content select="header">Fallback header</ng-content> <ng-content>Fallback content</ng-content> <ng-content select="footer">Fallback footer</ng-content> `, standalone: true, }) class InnerComponent {} @Component({ standalone: true, template: ` <inner> @let one = 1; <footer>|Footer value {{one}}</footer> @let two = one + 1; <header>Header value {{two}}|</header> </inner> `, imports: [InnerComponent], }) class TestComponent {} const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.innerHTML).toContain( '<inner><!--container--><header>Header value 2|</header>' + 'Fallback content<!--container--><!--container-->' + '<footer>|Footer value 1</footer></inner>', ); }); it('should give precedence to @let declarations over component properties', () => { @Component({ standalone: true, template: ` @let value = '@let'; @if (true) { The value comes from {{value}} } `, }) class TestComponent { value = 'component'; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('The value comes from @let'); }); it('should give precedence to local @let definition over one from a parent view', () => { @Component({ standalone: true, template: ` @let value = 'parent'; @if (true) { @let value = 'local'; The value comes from {{value}} } `, }) class TestComponent {} const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('The value comes from local'); }); it('should be able to use @for loop variables in @let declarations', () => { @Component({ standalone: true, template: ` @for (value of values; track $index) { @let calculation = value * $index; {{calculation}}| } `, }) class TestComponent { values = [1, 2, 3]; } const fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('0| 2| 6|'); }); });
{ "end_byte": 12305, "start_byte": 9758, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/let_spec.ts" }
angular/packages/core/test/acceptance/discover_utils_spec.ts_0_8345
/** * @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 { ChangeDetectionStrategy, Component, Directive, InjectionToken, Input, Output, ViewChild, ViewEncapsulation, } from '@angular/core'; import {EventEmitter} from '@angular/core/src/event_emitter'; import {isLView} from '@angular/core/src/render3/interfaces/type_checks'; import {CONTEXT} from '@angular/core/src/render3/interfaces/view'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {getLContext} from '../../src/render3/context_discovery'; import {getHostElement} from '../../src/render3/index'; import { ComponentDebugMetadata, getComponent, getComponentLView, getContext, getDirectiveMetadata, getDirectives, getInjectionTokens, getInjector, getListeners, getLocalRefs, getOwningComponent, getRootComponents, } from '../../src/render3/util/discovery_utils'; describe('discovery utils', () => { let fixture: ComponentFixture<MyApp>; let myApp: MyApp; let dirA: DirectiveA[]; let childComponent: (DirectiveA | Child)[]; let child: NodeListOf<Element>; let span: NodeListOf<Element>; let div: NodeListOf<Element>; let p: NodeListOf<Element>; let log: any[]; beforeEach(() => { log = []; dirA = []; childComponent = []; TestBed.configureTestingModule({ imports: [CommonModule], declarations: [MyApp, DirectiveA, Child], providers: [{provide: String, useValue: 'Module'}], }); fixture = TestBed.createComponent(MyApp); fixture.detectChanges(); child = fixture.nativeElement.querySelectorAll('child'); span = fixture.nativeElement.querySelectorAll('span'); div = fixture.nativeElement.querySelectorAll('div'); p = fixture.nativeElement.querySelectorAll('p'); }); @Component({ selector: 'child', template: '<p></p>', providers: [{provide: String, useValue: 'Child'}], standalone: false, }) class Child { constructor() { childComponent.push(this); } } @Directive({ selector: '[dirA]', exportAs: 'dirA', standalone: false, }) class DirectiveA { @Input('a') b = 2; @Output('c') d = new EventEmitter(); constructor() { dirA.push(this); } } @Component({ selector: 'my-app', template: ` <span (click)="log($event)" *ngIf="spanVisible">{{text}}</span> <div dirA #div #foo="dirA"></div> <child></child> <child dirA #child></child> <child dirA *ngIf="conditionalChildVisible"></child> <ng-container><p></p></ng-container> <b *ngIf="visible">Bold</b> `, standalone: false, }) class MyApp { text: string = 'INIT'; spanVisible = true; conditionalChildVisible = true; @Input('a') b = 2; @Output('c') d = new EventEmitter(); constructor() { myApp = this; } log(event: any) { log.push(event); } } describe('getComponent', () => { it('should return null if no component', () => { expect(getComponent(span[0])).toEqual(null); expect(getComponent(div[0])).toEqual(null); expect(getComponent(p[0])).toEqual(null); }); it('should throw when called on non-element', () => { expect(() => getComponent(dirA[0] as any)).toThrowError(/Expecting instance of DOM Element/); expect(() => getComponent(dirA[1] as any)).toThrowError(/Expecting instance of DOM Element/); }); it('should return component from element', () => { expect(getComponent<MyApp>(fixture.nativeElement)).toEqual(myApp); expect(getComponent<Child>(child[0])).toEqual(childComponent[0]); expect(getComponent<Child>(child[1])).toEqual(childComponent[1]); }); it('should not throw when called on a destroyed node', () => { expect(getComponent(span[0])).toEqual(null); expect(getComponent<Child>(child[2])).toEqual(childComponent[2]); fixture.componentInstance.spanVisible = false; fixture.componentInstance.conditionalChildVisible = false; fixture.detectChanges(); expect(getComponent(span[0])).toEqual(null); expect(getComponent<Child>(child[2])).toEqual(childComponent[2]); }); }); describe('getComponentLView', () => { it('should retrieve component LView from element', () => { const childLView = getComponentLView(child[0]); expect(isLView(childLView)).toBe(true); expect(childLView[CONTEXT] instanceof Child).toBe(true); }); it('should retrieve component LView from component instance', () => { const childLView = getComponentLView(childComponent[0]); expect(isLView(childLView)).toBe(true); expect(childLView[CONTEXT] instanceof Child).toBe(true); }); }); describe('getContext', () => { it('should throw when called on non-element', () => { expect(() => getContext(dirA[0] as any)).toThrowError(/Expecting instance of DOM Element/); expect(() => getContext(dirA[1] as any)).toThrowError(/Expecting instance of DOM Element/); }); it('should return context from element', () => { expect(getContext<MyApp>(child[0])).toEqual(myApp); expect(getContext<{$implicit: boolean}>(child[2])!.$implicit).toEqual(true); expect(getContext<Child>(p[0])).toEqual(childComponent[0]); }); it('should return null for destroyed node', () => { expect(getContext(span[0])).toBeTruthy(); fixture.componentInstance.spanVisible = false; fixture.detectChanges(); expect(getContext(span[0])).toBeNull(); }); }); describe('getHostElement', () => { it('should return element on component', () => { expect(getHostElement(myApp)).toEqual(fixture.nativeElement); expect(getHostElement(childComponent[0])).toEqual(child[0]); expect(getHostElement(childComponent[1])).toEqual(child[1]); }); it('should return element on directive', () => { expect(getHostElement(dirA[0])).toEqual(div[0]); expect(getHostElement(dirA[1])).toEqual(child[1]); }); it('should throw on unknown target', () => { expect(() => getHostElement({})).toThrowError(); // }); it('should return element for destroyed node', () => { expect(getHostElement(span[0])).toEqual(span[0]); fixture.componentInstance.spanVisible = false; fixture.detectChanges(); expect(getHostElement(span[0])).toEqual(span[0]); }); }); describe('getInjector', () => { it('should return node-injector from element', () => { expect(getInjector(fixture.nativeElement).get(String)).toEqual('Module'); expect(getInjector(child[0]).get(String)).toEqual('Child'); expect(getInjector(p[0]).get(String)).toEqual('Child'); }); it('should return node-injector from component with providers', () => { expect(getInjector(myApp).get(String)).toEqual('Module'); expect(getInjector(childComponent[0]).get(String)).toEqual('Child'); expect(getInjector(childComponent[1]).get(String)).toEqual('Child'); }); it('should return node-injector from directive without providers', () => { expect(getInjector(dirA[0]).get(String)).toEqual('Module'); expect(getInjector(dirA[1]).get(String)).toEqual('Child'); }); it('should retrieve injector from destroyed node', () => { expect(getInjector(span[0])).toBeTruthy(); fixture.componentInstance.spanVisible = false; fixture.detectChanges(); expect(getInjector(span[0])).toBeTruthy(); }); }); describe('getDirectives', () => { it('should return empty array if no directives', () => { expect(getDirectives(fixture.nativeElement)).toEqual([]); expect(getDirectives(span[0])).toEqual([]); expect(getDirectives(child[0])).toEqual([]); }); it('should return just directives', () => { expect(getDirectives(div[0])).toEqual([dirA[0]]); expect(getDirectives(child[1])).toEqual([dirA[1]]); }); it('should return empty array for destroyed node', () => { expect(getDirectives(span[0])).toEqual([]); fixture.componentInstance.spanVisible = false; fixture.detectChanges(); expect(getDirectives(span[0])).toEqual([]); }); });
{ "end_byte": 8345, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/discover_utils_spec.ts" }
angular/packages/core/test/acceptance/discover_utils_spec.ts_8349_15199
describe('getOwningComponent', () => { it('should return null when called on root component', () => { expect(getOwningComponent(fixture.nativeElement)).toEqual(null); expect(getOwningComponent(myApp)).toEqual(null); }); it('should return containing component of child component', () => { expect(getOwningComponent<MyApp>(child[0])).toEqual(myApp); expect(getOwningComponent<MyApp>(child[1])).toEqual(myApp); expect(getOwningComponent<MyApp>(child[2])).toEqual(myApp); expect(getOwningComponent<MyApp>(childComponent[0])).toEqual(myApp); expect(getOwningComponent<MyApp>(childComponent[1])).toEqual(myApp); expect(getOwningComponent<MyApp>(childComponent[2])).toEqual(myApp); }); it('should return containing component of any view element', () => { expect(getOwningComponent<MyApp>(span[0])).toEqual(myApp); expect(getOwningComponent<MyApp>(div[0])).toEqual(myApp); expect(getOwningComponent<Child>(p[0])).toEqual(childComponent[0]); expect(getOwningComponent<Child>(p[1])).toEqual(childComponent[1]); expect(getOwningComponent<Child>(p[2])).toEqual(childComponent[2]); }); it('should return containing component of child directive', () => { expect(getOwningComponent<MyApp>(dirA[0])).toEqual(myApp); expect(getOwningComponent<MyApp>(dirA[1])).toEqual(myApp); }); it('should return null for destroyed node', () => { expect(getOwningComponent<MyApp>(span[0])).toEqual(myApp); fixture.componentInstance.spanVisible = false; fixture.detectChanges(); expect(getOwningComponent<MyApp>(span[0])).toEqual(null); }); }); describe('getLocalRefs', () => { it('should retrieve empty map', () => { expect(getLocalRefs(fixture.nativeElement)).toEqual({}); expect(getLocalRefs(myApp)).toEqual({}); expect(getLocalRefs(span[0])).toEqual({}); expect(getLocalRefs(child[0])).toEqual({}); }); it('should retrieve the local map', () => { expect(getLocalRefs(div[0])).toEqual({div: div[0], foo: dirA[0]}); expect(getLocalRefs(dirA[0])).toEqual({div: div[0], foo: dirA[0]}); expect(getLocalRefs(child[1])).toEqual({child: childComponent[1]}); expect(getLocalRefs(dirA[1])).toEqual({child: childComponent[1]}); }); it('should retrieve from a destroyed node', () => { expect(getLocalRefs(span[0])).toEqual({}); fixture.componentInstance.spanVisible = false; fixture.detectChanges(); expect(getLocalRefs(span[0])).toEqual({}); }); }); describe('getRootComponents', () => { it('should return root components from component', () => { const rootComponents = [myApp]; expect(getRootComponents(myApp)).toEqual(rootComponents); expect(getRootComponents(childComponent[0])).toEqual(rootComponents); expect(getRootComponents(childComponent[1])).toEqual(rootComponents); expect(getRootComponents(dirA[0])).toEqual(rootComponents); expect(getRootComponents(dirA[1])).toEqual(rootComponents); expect(getRootComponents(child[0])).toEqual(rootComponents); expect(getRootComponents(child[1])).toEqual(rootComponents); expect(getRootComponents(div[0])).toEqual(rootComponents); expect(getRootComponents(p[0])).toEqual(rootComponents); }); it('should return an empty array for a destroyed node', () => { expect(getRootComponents(span[0])).toEqual([myApp]); fixture.componentInstance.spanVisible = false; fixture.detectChanges(); expect(getRootComponents(span[0])).toEqual([]); }); }); describe('getListeners', () => { it('should return no listeners', () => { expect(getListeners(fixture.nativeElement)).toEqual([]); expect(getListeners(child[0])).toEqual([]); }); it('should return the listeners', () => { const listeners = getListeners(span[0]); expect(listeners.length).toEqual(1); expect(listeners[0].name).toEqual('click'); expect(listeners[0].element).toEqual(span[0]); expect(listeners[0].useCapture).toEqual(false); expect(listeners[0].type).toEqual('dom'); listeners[0].callback('CLICKED'); expect(log).toEqual(['CLICKED']); }); it('should return no listeners for destroyed node', () => { expect(getListeners(span[0]).length).toEqual(1); fixture.componentInstance.spanVisible = false; fixture.detectChanges(); expect(getListeners(span[0]).length).toEqual(0); }); }); describe('getInjectionTokens', () => { it('should retrieve tokens', () => { expect(getInjectionTokens(fixture.nativeElement)).toEqual([MyApp]); expect(getInjectionTokens(child[0])).toEqual([String, Child]); expect(getInjectionTokens(child[1])).toEqual([String, Child, DirectiveA]); }); it('should retrieve tokens from destroyed node', () => { expect(getInjectionTokens(span[0])).toEqual([]); fixture.componentInstance.spanVisible = false; fixture.detectChanges(); expect(getInjectionTokens(span[0])).toEqual([]); }); }); describe('getLContext', () => { it('should work on components', () => { const lContext = getLContext(child[0])!; expect(lContext).toBeDefined(); expect(lContext.native as any).toBe(child[0]); }); it('should work on templates', () => { const templateComment = Array.from((fixture.nativeElement as HTMLElement).childNodes).find( (node: ChildNode) => node.nodeType === Node.COMMENT_NODE, )!; const lContext = getLContext(templateComment)!; expect(lContext).toBeDefined(); expect(lContext.native as any).toBe(templateComment); }); it('should work on ng-container', () => { const ngContainerComment = Array.from((fixture.nativeElement as HTMLElement).childNodes).find( (node: ChildNode) => node.nodeType === Node.COMMENT_NODE && node.textContent === `ng-container`, )!; const lContext = getLContext(ngContainerComment)!; expect(lContext).toBeDefined(); expect(lContext.native as any).toBe(ngContainerComment); }); }); describe('getDirectiveMetadata', () => { it('should work with components', () => { const metadata = getDirectiveMetadata(myApp); expect(metadata!.inputs).toEqual({a: 'b'}); expect(metadata!.outputs).toEqual({c: 'd'}); expect((metadata as ComponentDebugMetadata).changeDetection).toBe( ChangeDetectionStrategy.Default, ); expect((metadata as ComponentDebugMetadata).encapsulation).toBe(ViewEncapsulation.None); }); it('should work with directives', () => { const metadata = getDirectiveMetadata(getDirectives(div[0])[0]); expect(metadata!.inputs).toEqual({a: 'b'}); expect(metadata!.outputs).toEqual({c: 'd'}); }); }); });
{ "end_byte": 15199, "start_byte": 8349, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/discover_utils_spec.ts" }
angular/packages/core/test/acceptance/discover_utils_spec.ts_15201_20460
describe('discovery utils deprecated', () => { describe('getRootComponents()', () => { it('should return a list of the root components of the application from an element', () => { @Component({ selector: 'inner-comp', template: '<div></div>', standalone: false, }) class InnerComp {} @Component({ selector: 'comp', template: '<inner-comp></inner-comp>', standalone: false, }) class Comp {} TestBed.configureTestingModule({declarations: [Comp, InnerComp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); const hostElm = fixture.nativeElement; const innerElm = hostElm.querySelector('inner-comp')!; const divElm = hostElm.querySelector('div')!; const component = fixture.componentInstance; expect(getRootComponents(hostElm)!).toEqual([component]); expect(getRootComponents(innerElm)!).toEqual([component]); expect(getRootComponents(divElm)!).toEqual([component]); }); }); describe('getDirectives()', () => { it('should return a list of the directives that are on the given element', () => { @Directive({ selector: '[my-dir-1]', standalone: false, }) class MyDir1 {} @Directive({ selector: '[my-dir-2]', standalone: false, }) class MyDir2 {} @Directive({ selector: '[my-dir-3]', standalone: false, }) class MyDir3 {} @Component({ selector: 'comp', template: ` <div my-dir-1 my-dir-2></div> <div my-dir-3></div> `, standalone: false, }) class Comp { @ViewChild(MyDir1) myDir1Instance!: MyDir1; @ViewChild(MyDir2) myDir2Instance!: MyDir2; @ViewChild(MyDir3) myDir3Instance!: MyDir3; } TestBed.configureTestingModule({declarations: [Comp, MyDir1, MyDir2, MyDir3]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); const hostElm = fixture.nativeElement; const elements = hostElm.querySelectorAll('div'); const elm1 = elements[0]; const elm1Dirs = getDirectives(elm1); expect(elm1Dirs).toContain(fixture.componentInstance.myDir1Instance!); expect(elm1Dirs).toContain(fixture.componentInstance.myDir2Instance!); const elm2 = elements[1]; const elm2Dirs = getDirectives(elm2); expect(elm2Dirs).toContain(fixture.componentInstance.myDir3Instance!); }); it('should not throw if it cannot find LContext', () => { let result: any; expect(() => { result = getDirectives(document.createElement('div')); }).not.toThrow(); expect(result).toEqual([]); }); }); describe('getInjector', () => { it('should return an injector that can return directive instances', () => { @Component({ template: '', standalone: false, }) class Comp {} TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); const nodeInjector = getInjector(fixture.nativeElement); expect(nodeInjector.get(Comp)).toEqual(jasmine.any(Comp)); }); it('should return an injector that falls-back to a module injector', () => { @Component({ template: '', standalone: false, }) class Comp {} class TestToken {} const token = new InjectionToken<TestToken>('test token'); TestBed.configureTestingModule({ declarations: [Comp], providers: [{provide: token, useValue: new TestToken()}], }); const fixture = TestBed.createComponent(Comp); const nodeInjector = getInjector(fixture.nativeElement); expect(nodeInjector.get(token)).toEqual(jasmine.any(TestToken)); }); }); describe('getLocalRefs', () => { it('should return a map of local refs for an element', () => { @Directive({ selector: '[myDir]', exportAs: 'myDir', standalone: false, }) class MyDir {} @Component({ template: '<div myDir #elRef #dirRef="myDir"></div>', standalone: false, }) class Comp {} TestBed.configureTestingModule({declarations: [Comp, MyDir]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); const divEl = fixture.nativeElement.querySelector('div')!; const localRefs = getLocalRefs(divEl); expect(localRefs['elRef'].tagName.toLowerCase()).toBe('div'); expect(localRefs['dirRef'].constructor).toBe(MyDir); }); it('should return a map of local refs for an element with styling context', () => { @Component({ template: '<div #elRef class="fooClass" [style.color]="color"></div>', standalone: false, }) class Comp { color = 'red'; } TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); const divEl = fixture.nativeElement.querySelector('div')!; const localRefs = getLocalRefs(divEl); expect(localRefs['elRef'].tagName.toLowerCase()).toBe('div'); }); }); });
{ "end_byte": 20460, "start_byte": 15201, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/discover_utils_spec.ts" }
angular/packages/core/test/acceptance/template_ref_spec.ts_0_343
/** * @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, Injector, TemplateRef, ViewChild, ViewContainerRef} from '@angular/core'; import {TestBed} from '@angular/core/testing';
{ "end_byte": 343, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/template_ref_spec.ts" }
angular/packages/core/test/acceptance/template_ref_spec.ts_345_9383
describe('TemplateRef', () => { describe('rootNodes', () => { @Component({ template: `<ng-template #templateRef></ng-template>`, standalone: false, }) class App { @ViewChild('templateRef', {static: true}) templateRef!: TemplateRef<any>; minutes = 0; } function getRootNodes(template: string): any[] { TestBed.configureTestingModule({ declarations: [App], }); TestBed.overrideTemplate(App, template); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const embeddedView = fixture.componentInstance.templateRef.createEmbeddedView({}); embeddedView.detectChanges(); return embeddedView.rootNodes; } it('should return root render nodes for an embedded view instance', () => { const rootNodes = getRootNodes( `<ng-template #templateRef><div></div>some text<span></span></ng-template>`, ); expect(rootNodes.length).toBe(3); }); it('should return an empty array for embedded view with no nodes', () => { const rootNodes = getRootNodes('<ng-template #templateRef></ng-template>'); expect(rootNodes.length).toBe(0); }); it('should include projected nodes and their children', () => { @Component({ selector: 'menu-content', template: ` <ng-template> Header <ng-content></ng-content> </ng-template> `, exportAs: 'menuContent', standalone: false, }) class MenuContent { @ViewChild(TemplateRef, {static: true}) template!: TemplateRef<any>; } @Component({ template: ` <menu-content #menu="menuContent"> <button>Item one</button> <button>Item two</button> <ng-template [ngIf]="true"><button>Item three</button></ng-template> </menu-content> `, standalone: false, }) class App { @ViewChild(MenuContent) content!: MenuContent; constructor(public viewContainerRef: ViewContainerRef) {} } TestBed.configureTestingModule({declarations: [MenuContent, App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const instance = fixture.componentInstance; const viewRef = instance.viewContainerRef.createEmbeddedView(instance.content.template); const rootNodeTextContent = viewRef.rootNodes .map((node) => node && node.textContent.trim()) .filter((text) => text !== '' && text.indexOf('ng-reflect-ng-if') === -1); expect(rootNodeTextContent).toEqual(['Header', 'Item one', 'Item two', 'Item three']); }); it('should descend into view containers on ng-template', () => { const rootNodes = getRootNodes(` <ng-template #templateRef> <ng-template [ngIf]="true">text|</ng-template>SUFFIX </ng-template>`); expect(rootNodes.length).toBe(3); expect(rootNodes[0].nodeType).toBe(Node.COMMENT_NODE); expect(rootNodes[1].nodeType).toBe(Node.TEXT_NODE); expect(rootNodes[2].nodeType).toBe(Node.TEXT_NODE); }); it('should descend into view containers on an element', () => { /** * Expected DOM structure: * ``` * <div ng-reflect-ng-template-outlet="[object Object]"></div> * text * <!--container--> * SUFFIX * ``` */ const rootNodes = getRootNodes(` <ng-template #dynamicTpl>text</ng-template> <ng-template #templateRef> <div [ngTemplateOutlet]="dynamicTpl"></div>SUFFIX </ng-template> `); expect(rootNodes.length).toBe(4); expect(rootNodes[0].nodeType).toBe(Node.ELEMENT_NODE); expect(rootNodes[1].nodeType).toBe(Node.TEXT_NODE); // This comment node is an anchor for the `ViewContainerRef` // created within the `NgTemplateOutlet` class. expect(rootNodes[2].nodeType).toBe(Node.COMMENT_NODE); expect(rootNodes[3].nodeType).toBe(Node.TEXT_NODE); }); it('should descend into view containers on ng-container', () => { const rootNodes = getRootNodes(` <ng-template #dynamicTpl>text</ng-template> <ng-template #templateRef><ng-container [ngTemplateOutlet]="dynamicTpl"></ng-container>SUFFIX</ng-template> `); expect(rootNodes.length).toBe(3); expect(rootNodes[0].nodeType).toBe(Node.COMMENT_NODE); expect(rootNodes[1].nodeType).toBe(Node.TEXT_NODE); expect(rootNodes[2].nodeType).toBe(Node.TEXT_NODE); }); it('should descend into element containers', () => { const rootNodes = getRootNodes(` <ng-template #templateRef> <ng-container>text</ng-container> </ng-template> `); expect(rootNodes.length).toBe(2); expect(rootNodes[0].nodeType).toBe(Node.COMMENT_NODE); expect(rootNodes[1].nodeType).toBe(Node.TEXT_NODE); }); xit('should descend into ICU containers', () => { const rootNodes = getRootNodes(` <ng-template #templateRef> <ng-container i18n>Updated {minutes, select, =0 {just now} other {some time ago}}</ng-container> </ng-template> `); expect(rootNodes.length).toBe(4); expect(rootNodes[0].nodeType).toBe(Node.COMMENT_NODE); // ng-container expect(rootNodes[1].nodeType).toBe(Node.TEXT_NODE); // "Updated " text expect(rootNodes[2].nodeType).toBe(Node.COMMENT_NODE); // ICU container expect(rootNodes[3].nodeType).toBe(Node.TEXT_NODE); // "one minute ago" text }); it('should return an empty array for an embedded view with projection and no projectable nodes', () => { const rootNodes = getRootNodes( `<ng-template #templateRef><ng-content></ng-content></ng-template>`, ); expect(rootNodes.length).toBe(0); }); it('should return an empty array for an embedded view with multiple projections and no projectable nodes', () => { const rootNodes = getRootNodes( `<ng-template #templateRef><ng-content></ng-content><ng-content select="foo"></ng-content></ng-template>`, ); expect(rootNodes.length).toBe(0); }); describe('projectable nodes provided to a dynamically created component', () => { @Component({ selector: 'dynamic', template: '', standalone: false, }) class DynamicCmp { @ViewChild('templateRef', {static: true}) templateRef!: TemplateRef<any>; } @Component({ selector: 'test', template: '', standalone: false, }) class TestCmp { constructor(public vcr: ViewContainerRef) {} } beforeEach(() => { TestBed.configureTestingModule({declarations: [TestCmp, DynamicCmp]}); }); it('should return projectable nodes when provided', () => { TestBed.overrideTemplate( DynamicCmp, `<ng-template #templateRef><ng-content></ng-content></ng-template>`, ); const fixture = TestBed.createComponent(TestCmp); // Number of projectable nodes matches the number of slots - all nodes should be returned const projectableNodes = [[document.createTextNode('textNode')]]; const cmptRef = fixture.componentInstance.vcr.createComponent(DynamicCmp, { injector: Injector.NULL, projectableNodes, }); const viewRef = cmptRef.instance.templateRef.createEmbeddedView({}); expect(viewRef.rootNodes.length).toBe(1); }); it('should return an empty collection when no projectable nodes were provided', () => { TestBed.overrideTemplate( DynamicCmp, `<ng-template #templateRef><ng-content></ng-content></ng-template>`, ); const fixture = TestBed.createComponent(TestCmp); // There are slots but projectable nodes were not provided - nothing should be returned const cmptRef = fixture.componentInstance.vcr.createComponent(DynamicCmp, { injector: Injector.NULL, projectableNodes: [], }); const viewRef = cmptRef.instance.templateRef.createEmbeddedView({}); expect(viewRef.rootNodes.length).toBe(0); }); it('should return an empty collection when projectable nodes were provided but there are no slots', () => { TestBed.overrideTemplate(DynamicCmp, `<ng-template #templateRef></ng-template>`); const fixture = TestBed.createComponent(TestCmp); // There are no slots but projectable were provided - nothing should be returned const projectableNodes = [[document.createTextNode('textNode')]]; const cmptRef = fixture.componentInstance.vcr.createComponent(DynamicCmp, { injector: Injector.NULL, projectableNodes, }); const viewRef = cmptRef.instance.templateRef.createEmbeddedView({}); expect(viewRef.rootNodes.length).toBe(0); }); }); });
{ "end_byte": 9383, "start_byte": 345, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/template_ref_spec.ts" }
angular/packages/core/test/acceptance/template_ref_spec.ts_9387_13235
describe('context', () => { @Component({ template: ` <ng-template #templateRef let-name="name">{{name}}</ng-template> <ng-container #containerRef></ng-container> `, standalone: false, }) class App { @ViewChild('templateRef') templateRef!: TemplateRef<any>; @ViewChild('containerRef', {read: ViewContainerRef}) containerRef!: ViewContainerRef; } it('should update if the context of a view ref is mutated', () => { TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const context = {name: 'Frodo'}; const viewRef = fixture.componentInstance.templateRef.createEmbeddedView(context); fixture.componentInstance.containerRef.insert(viewRef); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Frodo'); context.name = 'Bilbo'; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Bilbo'); }); it('should update if the context of a view ref is replaced', () => { TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const viewRef = fixture.componentInstance.templateRef.createEmbeddedView({name: 'Frodo'}); fixture.componentInstance.containerRef.insert(viewRef); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Frodo'); viewRef.context = {name: 'Bilbo'}; fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Bilbo'); }); it('should use the latest context information inside template listeners', () => { const events: string[] = []; @Component({ template: ` <ng-template #templateRef let-name="name"> <button (click)="log(name)"></button> </ng-template> <ng-container #containerRef></ng-container> `, standalone: false, }) class ListenerTest { @ViewChild('templateRef') templateRef!: TemplateRef<any>; @ViewChild('containerRef', {read: ViewContainerRef}) containerRef!: ViewContainerRef; log(name: string) { events.push(name); } } TestBed.configureTestingModule({declarations: [ListenerTest]}); const fixture = TestBed.createComponent(ListenerTest); fixture.detectChanges(); const viewRef = fixture.componentInstance.templateRef.createEmbeddedView({name: 'Frodo'}); fixture.componentInstance.containerRef.insert(viewRef); fixture.detectChanges(); const button = fixture.nativeElement.querySelector('button'); button.click(); expect(events).toEqual(['Frodo']); viewRef.context = {name: 'Bilbo'}; fixture.detectChanges(); button.click(); expect(events).toEqual(['Frodo', 'Bilbo']); }); it('should warn if the context of an embedded view ref is replaced', () => { TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const viewRef = fixture.componentInstance.templateRef.createEmbeddedView({name: 'Frodo'}); fixture.componentInstance.containerRef.insert(viewRef); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('Frodo'); spyOn(console, 'warn'); viewRef.context = {name: 'Bilbo'}; fixture.detectChanges(); expect(console.warn).toHaveBeenCalledTimes(1); expect(console.warn).toHaveBeenCalledWith( jasmine.stringContaining( 'Replacing the `context` object of an `EmbeddedViewRef` is deprecated', ), ); expect(fixture.nativeElement.textContent).toBe('Bilbo'); }); }); });
{ "end_byte": 13235, "start_byte": 9387, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/template_ref_spec.ts" }
angular/packages/core/test/acceptance/host_directives_spec.ts_0_8204
/*! * @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 { AfterViewChecked, AfterViewInit, ChangeDetectorRef, Component, Directive, ElementRef, EventEmitter, forwardRef, inject, Inject, InjectionToken, Input, OnChanges, OnInit, Output, SimpleChanges, Type, ViewChild, ViewContainerRef, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {getComponent, getDirectives} from '../../src/render3/util/discovery_utils'; describe('host directives', () => { it('should apply a basic host directive', () => { const logs: string[] = []; @Directive({ standalone: true, host: {'host-dir-attr': '', 'class': 'host-dir', 'style': 'height: 50px'}, }) class HostDir { constructor() { logs.push('HostDir'); } } @Directive({ selector: '[dir]', host: {'host-attr': '', 'class': 'dir', 'style': 'width: 50px'}, hostDirectives: [HostDir], standalone: false, }) class Dir { constructor() { logs.push('Dir'); } } @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(logs).toEqual(['HostDir', 'Dir']); expect(fixture.nativeElement.innerHTML).toBe( '<div host-dir-attr="" host-attr="" dir="" ' + 'class="host-dir dir" style="height: 50px; width: 50px;"></div>', ); }); it('should apply a host directive referenced through a forwardRef', () => { const logs: string[] = []; @Directive({ selector: '[dir]', hostDirectives: [forwardRef(() => HostDir), {directive: forwardRef(() => OtherHostDir)}], standalone: false, }) class Dir { constructor() { logs.push('Dir'); } } @Directive({standalone: true}) class HostDir { constructor() { logs.push('HostDir'); } } @Directive({standalone: true}) class OtherHostDir { constructor() { logs.push('OtherHostDir'); } } @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(logs).toEqual(['HostDir', 'OtherHostDir', 'Dir']); }); it('should apply a chain of host directives', () => { const logs: string[] = []; const token = new InjectionToken('message'); let diTokenValue: string; @Directive({ host: { 'class': 'leaf', 'id': 'leaf-id', }, providers: [{provide: token, useValue: 'leaf value'}], standalone: true, }) class Chain1_3 { constructor(@Inject(token) tokenValue: string) { diTokenValue = tokenValue; logs.push('Chain1 - level 3'); } } @Directive({ standalone: true, hostDirectives: [Chain1_3], }) class Chain1_2 { constructor() { logs.push('Chain1 - level 2'); } } @Directive({ standalone: true, hostDirectives: [Chain1_2], }) class Chain1 { constructor() { logs.push('Chain1 - level 1'); } } @Directive({ standalone: true, host: { 'class': 'middle', 'id': 'middle-id', }, providers: [{provide: token, useValue: 'middle value'}], }) class Chain2_2 { constructor() { logs.push('Chain2 - level 2'); } } @Directive({ standalone: true, hostDirectives: [Chain2_2], }) class Chain2 { constructor() { logs.push('Chain2 - level 1'); } } @Directive({standalone: true}) class Chain3_2 { constructor() { logs.push('Chain3 - level 2'); } } @Directive({standalone: true, hostDirectives: [Chain3_2]}) class Chain3 { constructor() { logs.push('Chain3 - level 1'); } } @Component({ selector: 'my-comp', host: { 'class': 'host', 'id': 'host-id', }, template: '', hostDirectives: [Chain1, Chain2, Chain3], providers: [{provide: token, useValue: 'host value'}], standalone: false, }) class MyComp { constructor() { logs.push('MyComp'); } } @Directive({standalone: true}) class SelectorMatchedHostDir { constructor() { logs.push('SelectorMatchedHostDir'); } } @Directive({ selector: '[selector-matched-dir]', hostDirectives: [SelectorMatchedHostDir], standalone: false, }) class SelectorMatchedDir { constructor() { logs.push('SelectorMatchedDir'); } } @Component({ template: '<my-comp selector-matched-dir></my-comp>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, MyComp, SelectorMatchedDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(diTokenValue!).toBe('host value'); expect(fixture.nativeElement.innerHTML).toBe( '<my-comp id="host-id" selector-matched-dir="" class="leaf middle host"></my-comp>', ); expect(logs).toEqual([ 'Chain1 - level 3', 'Chain1 - level 2', 'Chain1 - level 1', 'Chain2 - level 2', 'Chain2 - level 1', 'Chain3 - level 2', 'Chain3 - level 1', 'MyComp', 'SelectorMatchedHostDir', 'SelectorMatchedDir', ]); }); it('should be able to query for the host directives', () => { let hostInstance!: Host; let firstHostDirInstance!: FirstHostDir; let secondHostDirInstance!: SecondHostDir; @Directive({standalone: true}) class SecondHostDir { constructor() { secondHostDirInstance = this; } } @Directive({standalone: true, hostDirectives: [SecondHostDir]}) class FirstHostDir { constructor() { firstHostDirInstance = this; } } @Directive({ selector: '[dir]', hostDirectives: [FirstHostDir], standalone: false, }) class Host { constructor() { hostInstance = this; } } @Component({ template: '<div dir></div>', standalone: false, }) class App { @ViewChild(FirstHostDir) firstHost!: FirstHostDir; @ViewChild(SecondHostDir) secondHost!: SecondHostDir; } TestBed.configureTestingModule({declarations: [App, Host]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(hostInstance instanceof Host).toBe(true); expect(firstHostDirInstance instanceof FirstHostDir).toBe(true); expect(secondHostDirInstance instanceof SecondHostDir).toBe(true); expect(fixture.componentInstance.firstHost).toBe(firstHostDirInstance); expect(fixture.componentInstance.secondHost).toBe(secondHostDirInstance); }); it('should be able to reference exported host directives', () => { @Directive({standalone: true, exportAs: 'secondHost'}) class SecondHostDir { name = 'SecondHost'; } @Directive({standalone: true, hostDirectives: [SecondHostDir], exportAs: 'firstHost'}) class FirstHostDir { name = 'FirstHost'; } @Directive({ selector: '[dir]', hostDirectives: [FirstHostDir], standalone: false, }) class Host {} @Component({ template: ` <div dir #firstHost="firstHost" #secondHost="secondHost">{{firstHost.name}} | {{secondHost.name}}</div> `, standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Host]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('FirstHost | SecondHost'); });
{ "end_byte": 8204, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }
angular/packages/core/test/acceptance/host_directives_spec.ts_8208_10208
it('should execute inherited host directives in the correct order', () => { const logs: string[] = []; @Directive({standalone: true}) class HostGrandparent_1 { constructor() { logs.push('HostGrandparent_1'); } } @Directive({standalone: true}) class HostGrandparent_2 { constructor() { logs.push('HostGrandparent_2'); } } @Directive({standalone: true, hostDirectives: [HostGrandparent_1, HostGrandparent_2]}) class Grandparent { constructor() { logs.push('Grandparent'); } } @Directive({standalone: true}) class HostParent_1 { constructor() { logs.push('HostParent_1'); } } @Directive({standalone: true}) class HostParent_2 { constructor() { logs.push('HostParent_2'); } } @Directive({standalone: true, hostDirectives: [HostParent_1, HostParent_2]}) class Parent extends Grandparent { constructor() { super(); logs.push('Parent'); } } @Directive({standalone: true}) class HostDir_1 { constructor() { logs.push('HostDir_1'); } } @Directive({standalone: true}) class HostDir_2 { constructor() { logs.push('HostDir_2'); } } @Directive({ selector: '[dir]', hostDirectives: [HostDir_1, HostDir_2], standalone: false, }) class Dir extends Parent { constructor() { super(); logs.push('Dir'); } } @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(logs).toEqual([ 'HostGrandparent_1', 'HostGrandparent_2', 'HostParent_1', 'HostParent_2', 'HostDir_1', 'HostDir_2', 'Grandparent', 'Parent', 'Dir', ]); });
{ "end_byte": 10208, "start_byte": 8208, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }
angular/packages/core/test/acceptance/host_directives_spec.ts_10212_17354
describe('lifecycle hooks', () => { it('should invoke lifecycle hooks from the host directives', () => { const logs: string[] = []; @Directive({standalone: true}) class HostDir implements OnInit, AfterViewInit, AfterViewChecked { ngOnInit() { logs.push('HostDir - ngOnInit'); } ngAfterViewInit() { logs.push('HostDir - ngAfterViewInit'); } ngAfterViewChecked() { logs.push('HostDir - ngAfterViewChecked'); } } @Directive({standalone: true}) class OtherHostDir implements OnInit, AfterViewInit, AfterViewChecked { ngOnInit() { logs.push('OtherHostDir - ngOnInit'); } ngAfterViewInit() { logs.push('OtherHostDir - ngAfterViewInit'); } ngAfterViewChecked() { logs.push('OtherHostDir - ngAfterViewChecked'); } } @Directive({ selector: '[dir]', hostDirectives: [HostDir, OtherHostDir], standalone: false, }) class Dir implements OnInit, AfterViewInit, AfterViewChecked { ngOnInit() { logs.push('Dir - ngOnInit'); } ngAfterViewInit() { logs.push('Dir - ngAfterViewInit'); } ngAfterViewChecked() { logs.push('Dir - ngAfterViewChecked'); } } @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(logs).toEqual([ 'HostDir - ngOnInit', 'OtherHostDir - ngOnInit', 'Dir - ngOnInit', 'HostDir - ngAfterViewInit', 'HostDir - ngAfterViewChecked', 'OtherHostDir - ngAfterViewInit', 'OtherHostDir - ngAfterViewChecked', 'Dir - ngAfterViewInit', 'Dir - ngAfterViewChecked', ]); }); // Note: lifecycle hook order is different when components and directives are mixed so this // test aims to cover it. Usually lifecycle hooks are invoked based on the order in which // directives were matched, but components bypass this logic and always execute first. it('should invoke host directive lifecycle hooks before the host component hooks', () => { const logs: string[] = []; // Utility so we don't have to repeat the logging code. @Directive({standalone: true}) abstract class LogsLifecycles implements OnInit, AfterViewInit { abstract name: string; ngOnInit() { logs.push(`${this.name} - ngOnInit`); } ngAfterViewInit() { logs.push(`${this.name} - ngAfterViewInit`); } } @Directive({standalone: true}) class ChildHostDir extends LogsLifecycles { override name = 'ChildHostDir'; } @Directive({standalone: true}) class OtherChildHostDir extends LogsLifecycles { override name = 'OtherChildHostDir'; } @Component({ selector: 'child', hostDirectives: [ChildHostDir, OtherChildHostDir], standalone: false, }) class Child extends LogsLifecycles { override name = 'Child'; } @Directive({standalone: true}) class ParentHostDir extends LogsLifecycles { override name = 'ParentHostDir'; } @Directive({standalone: true}) class OtherParentHostDir extends LogsLifecycles { override name = 'OtherParentHostDir'; } @Component({ selector: 'parent', hostDirectives: [ParentHostDir, OtherParentHostDir], template: '<child plain-dir="PlainDir on child"></child>', standalone: false, }) class Parent extends LogsLifecycles { override name = 'Parent'; } @Directive({ selector: '[plain-dir]', standalone: false, }) class PlainDir extends LogsLifecycles { @Input('plain-dir') override name = ''; } @Component({ template: '<parent plain-dir="PlainDir on parent"></parent>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Parent, Child, PlainDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(logs).toEqual([ 'ParentHostDir - ngOnInit', 'OtherParentHostDir - ngOnInit', 'Parent - ngOnInit', 'PlainDir on parent - ngOnInit', 'ChildHostDir - ngOnInit', 'OtherChildHostDir - ngOnInit', 'Child - ngOnInit', 'PlainDir on child - ngOnInit', 'ChildHostDir - ngAfterViewInit', 'OtherChildHostDir - ngAfterViewInit', 'Child - ngAfterViewInit', 'PlainDir on child - ngAfterViewInit', 'ParentHostDir - ngAfterViewInit', 'OtherParentHostDir - ngAfterViewInit', 'Parent - ngAfterViewInit', 'PlainDir on parent - ngAfterViewInit', ]); }); it('should invoke host directive ngOnChanges hooks before the host component', () => { let logs: string[] = []; // Utility so we don't have to repeat the logging code. @Directive({standalone: true}) abstract class LogsLifecycles implements OnChanges { @Input() someInput: any; abstract name: string; ngOnChanges(changes: SimpleChanges) { logs.push(`${this.name} - ${changes['someInput'].currentValue}`); } } @Directive({standalone: true}) class HostDir extends LogsLifecycles { override name = 'HostDir'; } @Directive({standalone: true}) class OtherHostDir extends LogsLifecycles { override name = 'OtherHostDir'; } @Component({ selector: 'host-comp', hostDirectives: [ {directive: HostDir, inputs: ['someInput']}, {directive: OtherHostDir, inputs: ['someInput']}, ], standalone: false, }) class HostComp extends LogsLifecycles { override name = 'HostComp'; } @Directive({ selector: '[plain-dir]', standalone: false, }) class PlainDir extends LogsLifecycles { override name = 'PlainDir'; } @Component({ template: '<host-comp plain-dir="PlainDir" [someInput]="inputValue"></host-comp>', standalone: false, }) class App { inputValue = 'hello'; } TestBed.configureTestingModule({declarations: [App, HostComp, PlainDir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(logs).toEqual([ 'HostDir - hello', 'OtherHostDir - hello', 'HostComp - hello', 'PlainDir - hello', ]); logs = []; fixture.componentInstance.inputValue = 'changed'; fixture.detectChanges(); expect(logs).toEqual([ 'HostDir - changed', 'OtherHostDir - changed', 'HostComp - changed', 'PlainDir - changed', ]); }); });
{ "end_byte": 17354, "start_byte": 10212, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }
angular/packages/core/test/acceptance/host_directives_spec.ts_17358_19667
describe('host bindings', () => { it('should apply the host bindings from all host directives', () => { const clicks: string[] = []; @Directive({standalone: true, host: {'host-dir-attr': 'true', '(click)': 'handleClick()'}}) class HostDir { handleClick() { clicks.push('HostDir'); } } @Directive({ standalone: true, host: {'other-host-dir-attr': 'true', '(click)': 'handleClick()'}, }) class OtherHostDir { handleClick() { clicks.push('OtherHostDir'); } } @Directive({ selector: '[dir]', host: {'host-attr': 'true', '(click)': 'handleClick()'}, hostDirectives: [HostDir, OtherHostDir], standalone: false, }) class Dir { handleClick() { clicks.push('Dir'); } } @Component({ template: '<button dir></button>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const host = fixture.nativeElement.querySelector('[dir]'); expect(host.outerHTML).toBe( '<button host-dir-attr="true" other-host-dir-attr="true" host-attr="true" dir=""></button>', ); host.click(); fixture.detectChanges(); expect(clicks).toEqual(['HostDir', 'OtherHostDir', 'Dir']); }); it('should have the host bindings take precedence over the ones from the host directives', () => { @Directive({standalone: true, host: {'id': 'host-dir'}}) class HostDir {} @Directive({standalone: true, host: {'id': 'other-host-dir'}}) class OtherHostDir {} @Directive({ selector: '[dir]', host: {'id': 'host'}, hostDirectives: [HostDir, OtherHostDir], standalone: false, }) class Dir {} @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('[dir]').getAttribute('id')).toBe('host'); }); });
{ "end_byte": 19667, "start_byte": 17358, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }
angular/packages/core/test/acceptance/host_directives_spec.ts_19671_28718
describe('dependency injection', () => { it('should allow the host to inject its host directives', () => { let hostInstance!: Host; let firstHostDirInstance!: FirstHostDir; let secondHostDirInstance!: SecondHostDir; @Directive({standalone: true}) class SecondHostDir { constructor() { secondHostDirInstance = this; } } @Directive({standalone: true, hostDirectives: [SecondHostDir]}) class FirstHostDir { constructor() { firstHostDirInstance = this; } } @Directive({ selector: '[dir]', hostDirectives: [FirstHostDir], standalone: false, }) class Host { firstHostDir = inject(FirstHostDir); secondHostDir = inject(SecondHostDir); constructor() { hostInstance = this; } } @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Host]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(hostInstance instanceof Host).toBe(true); expect(firstHostDirInstance instanceof FirstHostDir).toBe(true); expect(secondHostDirInstance instanceof SecondHostDir).toBe(true); expect(hostInstance.firstHostDir).toBe(firstHostDirInstance); expect(hostInstance.secondHostDir).toBe(secondHostDirInstance); }); it('should be able to inject a host directive into a child component', () => { let hostDirectiveInstance!: HostDir; @Component({ selector: 'child', template: '', standalone: false, }) class Child { hostDir = inject(HostDir); } @Directive({standalone: true}) class HostDir { constructor() { hostDirectiveInstance = this; } } @Component({ selector: 'host', template: '<child></child>', hostDirectives: [HostDir], standalone: false, }) class Host { @ViewChild(Child) child!: Child; } @Component({ template: '<host></host>', standalone: false, }) class App { @ViewChild(Host) host!: Host; } TestBed.configureTestingModule({declarations: [App, Host, Child]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const injectedInstance = fixture.componentInstance.host.child.hostDir; expect(injectedInstance instanceof HostDir).toBe(true); expect(injectedInstance).toBe(hostDirectiveInstance); }); it('should allow the host directives to inject their host', () => { let hostInstance!: Host; let firstHostDirInstance!: FirstHostDir; let secondHostDirInstance!: SecondHostDir; @Directive({standalone: true}) class SecondHostDir { host = inject(Host); constructor() { secondHostDirInstance = this; } } @Directive({standalone: true, hostDirectives: [SecondHostDir]}) class FirstHostDir { host = inject(Host); constructor() { firstHostDirInstance = this; } } @Directive({ selector: '[dir]', hostDirectives: [FirstHostDir], standalone: false, }) class Host { constructor() { hostInstance = this; } } @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Host]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(hostInstance instanceof Host).toBe(true); expect(firstHostDirInstance instanceof FirstHostDir).toBe(true); expect(secondHostDirInstance instanceof SecondHostDir).toBe(true); expect(firstHostDirInstance.host).toBe(hostInstance); expect(secondHostDirInstance.host).toBe(hostInstance); }); it('should give precedence to the DI tokens from the host over the host directive tokens', () => { const token = new InjectionToken<string>('token'); let hostInstance!: Host; let firstHostDirInstance!: FirstHostDir; let secondHostDirInstance!: SecondHostDir; @Directive({standalone: true, providers: [{provide: token, useValue: 'SecondDir'}]}) class SecondHostDir { tokenValue = inject(token); constructor() { secondHostDirInstance = this; } } @Directive({ standalone: true, hostDirectives: [SecondHostDir], providers: [{provide: token, useValue: 'FirstDir'}], }) class FirstHostDir { tokenValue = inject(token); constructor() { firstHostDirInstance = this; } } @Directive({ selector: '[dir]', hostDirectives: [FirstHostDir], providers: [{provide: token, useValue: 'HostDir'}], standalone: false, }) class Host { tokenValue = inject(token); constructor() { hostInstance = this; } } @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Host]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(hostInstance instanceof Host).toBe(true); expect(firstHostDirInstance instanceof FirstHostDir).toBe(true); expect(secondHostDirInstance instanceof SecondHostDir).toBe(true); expect(hostInstance.tokenValue).toBe('HostDir'); expect(firstHostDirInstance.tokenValue).toBe('HostDir'); expect(secondHostDirInstance.tokenValue).toBe('HostDir'); }); it('should allow the host to inject tokens from the host directives', () => { const firstToken = new InjectionToken<string>('firstToken'); const secondToken = new InjectionToken<string>('secondToken'); @Directive({standalone: true, providers: [{provide: secondToken, useValue: 'SecondDir'}]}) class SecondHostDir {} @Directive({ standalone: true, hostDirectives: [SecondHostDir], providers: [{provide: firstToken, useValue: 'FirstDir'}], }) class FirstHostDir {} @Directive({ selector: '[dir]', hostDirectives: [FirstHostDir], standalone: false, }) class Host { firstTokenValue = inject(firstToken); secondTokenValue = inject(secondToken); } @Component({ template: '<div dir></div>', standalone: false, }) class App { @ViewChild(Host) host!: Host; } TestBed.configureTestingModule({declarations: [App, Host]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.host.firstTokenValue).toBe('FirstDir'); expect(fixture.componentInstance.host.secondTokenValue).toBe('SecondDir'); }); it('should not give precedence to tokens from host directives over ones in viewProviders', () => { const token = new InjectionToken<string>('token'); let tokenValue: string | undefined; @Directive({standalone: true, providers: [{provide: token, useValue: 'host-dir'}]}) class HostDir {} @Component({ selector: 'host', hostDirectives: [HostDir], providers: [{provide: token, useValue: 'host'}], template: '<span child></span>', standalone: false, }) class Host {} @Directive({ selector: '[child]', standalone: false, }) class Child { constructor() { tokenValue = inject(token); } } @Component({ template: '<host></host>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Host, Child]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(tokenValue).toBe('host'); }); it('should not be able to access viewProviders from the host in the host directives', () => { const token = new InjectionToken<string>('token'); let tokenValue: string | null = null; @Directive({standalone: true}) class HostDir { constructor() { tokenValue = inject(token, {optional: true}); } } @Component({ selector: 'host', hostDirectives: [HostDir], viewProviders: [{provide: token, useValue: 'host'}], template: '', standalone: false, }) class Host {} @Component({ template: '<host></host>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Host]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(tokenValue).toBe(null); });
{ "end_byte": 28718, "start_byte": 19671, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }
angular/packages/core/test/acceptance/host_directives_spec.ts_28724_31046
it('should throw a circular dependency error if a host and a host directive inject each other', () => { @Directive({standalone: true}) class HostDir { host = inject(Host); } @Directive({ selector: '[dir]', hostDirectives: [HostDir], standalone: false, }) class Host { hostDir = inject(HostDir); } @Component({ template: '<div dir></div>', standalone: false, }) class App {} TestBed.configureTestingModule({declarations: [App, Host]}); expect(() => TestBed.createComponent(App)).toThrowError( /NG0200: Circular dependency in DI detected for HostDir/, ); }); it('should inject a valid ChangeDetectorRef when attached to a component', () => { type InternalChangeDetectorRef = ChangeDetectorRef & {_lView: unknown}; @Directive({standalone: true}) class HostDir { changeDetectorRef = inject(ChangeDetectorRef) as InternalChangeDetectorRef; } @Component({ selector: 'my-comp', hostDirectives: [HostDir], template: '', standalone: false, }) class Comp { changeDetectorRef = inject(ChangeDetectorRef) as InternalChangeDetectorRef; } @Component({ template: '<my-comp></my-comp>', standalone: false, }) class App { @ViewChild(HostDir) hostDir!: HostDir; @ViewChild(Comp) comp!: Comp; } TestBed.configureTestingModule({declarations: [App, Comp]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const hostDirectiveCdr = fixture.componentInstance.hostDir.changeDetectorRef; const componentCdr = fixture.componentInstance.comp.changeDetectorRef; // We can't assert that the change detectors are the same by comparing // them directly, because a new one is created each time. Instead of we // compare that they're associated with the same LView. expect(hostDirectiveCdr._lView).toBeTruthy(); expect(componentCdr._lView).toBeTruthy(); expect(hostDirectiveCdr._lView).toBe(componentCdr._lView); expect(() => { hostDirectiveCdr.markForCheck(); hostDirectiveCdr.detectChanges(); }).not.toThrow(); }); });
{ "end_byte": 31046, "start_byte": 28724, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }
angular/packages/core/test/acceptance/host_directives_spec.ts_31050_40292
describe('outputs', () => { it('should not emit to an output of a host directive that has not been exposed', () => { let hostDirectiveInstance: HostDir | undefined; @Directive({standalone: true, host: {'(click)': 'hasBeenClicked.emit()'}}) class HostDir { @Output() hasBeenClicked = new EventEmitter<void>(); constructor() { hostDirectiveInstance = this; } } @Directive({ selector: '[dir]', hostDirectives: [HostDir], standalone: false, }) class Dir {} @Component({ template: '<button dir (hasBeenClicked)="spy()"></button>', standalone: false, }) class App { spy = jasmine.createSpy('click spy'); } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); expect(hostDirectiveInstance instanceof HostDir).toBe(true); expect(fixture.componentInstance.spy).not.toHaveBeenCalled(); }); it('should emit to an output of a host directive that has been exposed', () => { @Directive({standalone: true, host: {'(click)': 'hasBeenClicked.emit("hello")'}}) class HostDir { @Output() hasBeenClicked = new EventEmitter<string>(); } @Directive({ selector: '[dir]', hostDirectives: [ { directive: HostDir, outputs: ['hasBeenClicked'], }, ], standalone: false, }) class Dir {} @Component({ template: '<button dir (hasBeenClicked)="spy($event)"></button>', standalone: false, }) class App { spy = jasmine.createSpy('click spy'); } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); expect(fixture.componentInstance.spy).toHaveBeenCalledOnceWith('hello'); }); it('should emit to an output of a host directive that has been exposed under an alias', () => { @Directive({standalone: true, host: {'(click)': 'hasBeenClicked.emit("hello")'}}) class HostDir { @Output() hasBeenClicked = new EventEmitter<string>(); } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, outputs: ['hasBeenClicked: wasClicked']}], standalone: false, }) class Dir {} @Component({ template: ` <button dir (wasClicked)="validSpy($event)" (hasBeenClicked)="invalidSpy($event)"></button>`, standalone: false, }) class App { validSpy = jasmine.createSpy('valid spy'); invalidSpy = jasmine.createSpy('invalid spy'); } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); expect(fixture.componentInstance.validSpy).toHaveBeenCalledOnceWith('hello'); expect(fixture.componentInstance.invalidSpy).not.toHaveBeenCalled(); }); it('should alias to the public name of the host directive output, not the private one', () => { @Directive({standalone: true, host: {'(click)': 'hasBeenClicked.emit("hello")'}}) class HostDir { @Output('wasClicked') hasBeenClicked = new EventEmitter<string>(); } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, outputs: ['wasClicked: clickOccurred']}], standalone: false, }) class Dir {} @Component({ template: ` <button dir (clickOccurred)="validSpy($event)" (hasBeenClicked)="invalidSpy($event)"></button>`, standalone: false, }) class App { validSpy = jasmine.createSpy('valid spy'); invalidSpy = jasmine.createSpy('invalid spy'); } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); expect(fixture.componentInstance.validSpy).toHaveBeenCalledOnceWith('hello'); expect(fixture.componentInstance.invalidSpy).not.toHaveBeenCalled(); }); it('should emit to an output of a host that has the same name as a non-exposed output of a host directive', () => { @Directive({standalone: true, host: {'(click)': 'hasBeenClicked.emit("HostDir")'}}) class HostDir { @Output() hasBeenClicked = new EventEmitter<string>(); } @Directive({ selector: '[dir]', hostDirectives: [HostDir], host: {'(click)': 'hasBeenClicked.emit("Dir")'}, standalone: false, }) class Dir { @Output() hasBeenClicked = new EventEmitter<string>(); } @Component({ template: '<button dir (hasBeenClicked)="spy($event)"></button>', standalone: false, }) class App { spy = jasmine.createSpy('click spy'); } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); expect(fixture.componentInstance.spy).toHaveBeenCalledOnceWith('Dir'); }); it('should emit to an output of a host that has the same name as an exposed output of a host directive', () => { @Directive({standalone: true, host: {'(click)': 'hasBeenClicked.emit("HostDir")'}}) class HostDir { @Output() hasBeenClicked = new EventEmitter<string>(); } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, outputs: ['hasBeenClicked']}], host: {'(click)': 'hasBeenClicked.emit("Dir")'}, standalone: false, }) class Dir { @Output() hasBeenClicked = new EventEmitter<string>(); } @Component({ template: '<button dir (hasBeenClicked)="spy($event)"></button>', standalone: false, }) class App { spy = jasmine.createSpy('click spy'); } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); expect(fixture.componentInstance.spy).toHaveBeenCalledTimes(2); expect(fixture.componentInstance.spy).toHaveBeenCalledWith('HostDir'); expect(fixture.componentInstance.spy).toHaveBeenCalledWith('Dir'); }); it('should emit to an output of a host that has the same name as the alias of a host directive output', () => { @Directive({standalone: true, host: {'(click)': 'hasBeenClicked.emit("HostDir")'}}) class HostDir { @Output() hasBeenClicked = new EventEmitter<string>(); } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, outputs: ['hasBeenClicked: wasClicked']}], host: {'(click)': 'wasClicked.emit("Dir")'}, standalone: false, }) class Dir { @Output() wasClicked = new EventEmitter<string>(); } @Component({ template: '<button dir (wasClicked)="spy($event)"></button>', standalone: false, }) class App { spy = jasmine.createSpy('click spy'); } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); expect(fixture.componentInstance.spy).toHaveBeenCalledTimes(2); expect(fixture.componentInstance.spy).toHaveBeenCalledWith('HostDir'); expect(fixture.componentInstance.spy).toHaveBeenCalledWith('Dir'); }); it('should not expose the same output more than once', () => { @Directive({standalone: true, host: {'(click)': 'hasBeenClicked.emit()'}}) class HostDir { @Output() hasBeenClicked = new EventEmitter<void>(); } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, outputs: ['hasBeenClicked', 'hasBeenClicked']}], standalone: false, }) class Dir {} @Component({ template: '<button dir (hasBeenClicked)="spy($event)"></button>', standalone: false, }) class App { spy = jasmine.createSpy('click spy'); } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); expect(fixture.componentInstance.spy).toHaveBeenCalledTimes(1); });
{ "end_byte": 40292, "start_byte": 31050, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }
angular/packages/core/test/acceptance/host_directives_spec.ts_40298_45447
it('should emit to an inherited output of a host directive', () => { @Directive({ host: {'(click)': 'hasBeenClicked.emit("hello")'}, standalone: false, }) class ParentDir { @Output() hasBeenClicked = new EventEmitter<string>(); } @Directive({standalone: true}) class HostDir extends ParentDir {} @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, outputs: ['hasBeenClicked']}], standalone: false, }) class Dir {} @Component({ template: '<button dir (hasBeenClicked)="spy($event)"></button>', standalone: false, }) class App { spy = jasmine.createSpy('click spy'); } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); expect(fixture.componentInstance.spy).toHaveBeenCalledOnceWith('hello'); }); it('should emit to an output that was exposed from one host directive, but not another', () => { @Directive({standalone: true, host: {'(click)': 'hasBeenClicked.emit("ExposedHostDir")'}}) class ExposedHostDir { @Output() hasBeenClicked = new EventEmitter<string>(); } @Directive({standalone: true, host: {'(click)': 'hasBeenClicked.emit("UnExposedHostDir")'}}) class UnExposedHostDir { @Output() hasBeenClicked = new EventEmitter<string>(); } @Directive({ selector: '[dir]', hostDirectives: [ {directive: ExposedHostDir, outputs: ['hasBeenClicked']}, UnExposedHostDir, ], standalone: false, }) class Dir {} @Component({ template: '<button dir (hasBeenClicked)="spy($event)"></button>', standalone: false, }) class App { spy = jasmine.createSpy('click spy'); } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); expect(fixture.componentInstance.spy).toHaveBeenCalledOnceWith('ExposedHostDir'); expect(fixture.componentInstance.spy).not.toHaveBeenCalledWith('UnExposedHostDir'); }); it('should emit to outputs from different host directives that have been aliased to the same name', () => { @Directive({ standalone: true, host: {'(click)': 'firstHasBeenClicked.emit("FirstHostDir")'}, }) class FirstHostDir { @Output() firstHasBeenClicked = new EventEmitter<string>(); } @Directive({ standalone: true, host: {'(click)': 'secondHasBeenClicked.emit("SecondHostDir")'}, }) class SecondHostDir { @Output() secondHasBeenClicked = new EventEmitter<string>(); } @Directive({ selector: '[dir]', hostDirectives: [ {directive: FirstHostDir, outputs: ['firstHasBeenClicked: wasClicked']}, {directive: SecondHostDir, outputs: ['secondHasBeenClicked: wasClicked']}, ], standalone: false, }) class Dir {} @Component({ template: '<button dir (wasClicked)="spy($event)"></button>', standalone: false, }) class App { spy = jasmine.createSpy('click spy'); } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); expect(fixture.componentInstance.spy).toHaveBeenCalledTimes(2); expect(fixture.componentInstance.spy).toHaveBeenCalledWith('FirstHostDir'); expect(fixture.componentInstance.spy).toHaveBeenCalledWith('SecondHostDir'); }); it('should emit to an output of an inherited host directive that has been exposed', () => { @Directive({standalone: true, host: {'(click)': 'hasBeenClicked.emit("hello")'}}) class HostDir { @Output() hasBeenClicked = new EventEmitter<string>(); } @Directive({ hostDirectives: [ { directive: HostDir, outputs: ['hasBeenClicked'], }, ], standalone: false, }) class Parent {} @Directive({ selector: '[dir]', standalone: false, }) class Dir extends Parent {} @Component({ template: '<button dir (hasBeenClicked)="spy($event)"></button>', standalone: false, }) class App { spy = jasmine.createSpy('click spy'); } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.nativeElement.querySelector('button').click(); fixture.detectChanges(); expect(fixture.componentInstance.spy).toHaveBeenCalledOnceWith('hello'); }); });
{ "end_byte": 45447, "start_byte": 40298, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }
angular/packages/core/test/acceptance/host_directives_spec.ts_45451_53534
describe('inputs', () => { it('should not set an input of a host directive that has not been exposed', () => { @Directive({standalone: true}) class HostDir { @Input() color?: string; } @Directive({ selector: '[dir]', hostDirectives: [HostDir], standalone: false, }) class Dir {} @Component({ template: '<button dir [color]="color"></button>', standalone: false, }) class App { color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir], errorOnUnknownProperties: true}); expect(() => { const fixture = TestBed.createComponent(App); fixture.detectChanges(); }).toThrowError(/Can't bind to 'color' since it isn't a known property/); }); it('should set the input of a host directive that has been exposed', () => { @Directive({standalone: true}) class HostDir { @Input() color?: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['color']}], standalone: false, }) class Dir {} @Component({ template: '<button dir [color]="color"></button>', standalone: false, }) class App { @ViewChild(HostDir) hostDir!: HostDir; color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.hostDir.color).toBe('red'); fixture.componentInstance.color = 'green'; fixture.detectChanges(); expect(fixture.componentInstance.hostDir.color).toBe('green'); }); it('should set an input of a host directive that has been exposed under an alias', () => { @Directive({standalone: true}) class HostDir { @Input() color?: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['color: buttonColor']}], standalone: false, }) class Dir {} @Component({ template: '<button dir [buttonColor]="color"></button>', standalone: false, }) class App { @ViewChild(HostDir) hostDir!: HostDir; color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.hostDir.color).toBe('red'); fixture.componentInstance.color = 'green'; fixture.detectChanges(); expect(fixture.componentInstance.hostDir.color).toBe('green'); }); it('should alias to the public name of the host directive input, not the private one', () => { @Directive({standalone: true}) class HostDir { @Input('colorAlias') color?: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['colorAlias: buttonColor']}], standalone: false, }) class Dir {} @Component({ template: '<button dir [buttonColor]="color"></button>', standalone: false, }) class App { @ViewChild(HostDir) hostDir!: HostDir; color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.hostDir.color).toBe('red'); fixture.componentInstance.color = 'green'; fixture.detectChanges(); expect(fixture.componentInstance.hostDir.color).toBe('green'); }); it('should set an input of a host that has the same name as a non-exposed input of a host directive', () => { @Directive({standalone: true}) class HostDir { @Input() color?: string; } @Directive({ selector: '[dir]', hostDirectives: [HostDir], standalone: false, }) class Dir { @Input() color?: string; } @Component({ template: '<button dir [color]="color"></button>', standalone: false, }) class App { @ViewChild(Dir) dir!: Dir; @ViewChild(HostDir) hostDir!: HostDir; color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const {dir, hostDir} = fixture.componentInstance; expect(dir.color).toBe('red'); expect(hostDir.color).toBe(undefined); fixture.componentInstance.color = 'green'; fixture.detectChanges(); expect(dir.color).toBe('green'); expect(hostDir.color).toBe(undefined); }); it('should set an input of a host that has the same name as an exposed input of a host directive', () => { @Directive({standalone: true}) class HostDir { @Input() color?: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['color']}], standalone: false, }) class Dir { @Input() color?: string; } @Component({ template: '<button dir [color]="color"></button>', standalone: false, }) class App { @ViewChild(Dir) dir!: Dir; @ViewChild(HostDir) hostDir!: HostDir; color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const {dir, hostDir} = fixture.componentInstance; expect(dir.color).toBe('red'); expect(hostDir.color).toBe('red'); fixture.componentInstance.color = 'green'; fixture.detectChanges(); expect(dir.color).toBe('green'); expect(hostDir.color).toBe('green'); }); it('should set an input of a host that has the same name as the alias of a host directive input', () => { @Directive({standalone: true}) class HostDir { @Input() color?: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['color: buttonColor']}], standalone: false, }) class Dir { @Input() buttonColor?: string; } @Component({ template: '<button dir [buttonColor]="color"></button>', standalone: false, }) class App { @ViewChild(Dir) dir!: Dir; @ViewChild(HostDir) hostDir!: HostDir; color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const {dir, hostDir} = fixture.componentInstance; expect(dir.buttonColor).toBe('red'); expect(hostDir.color).toBe('red'); fixture.componentInstance.color = 'green'; fixture.detectChanges(); expect(dir.buttonColor).toBe('green'); expect(hostDir.color).toBe('green'); }); it('should set an inherited input of a host directive', () => { @Directive() class ParentDir { @Input() color?: string; } @Directive({standalone: true}) class HostDir extends ParentDir {} @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['color']}], standalone: false, }) class Dir {} @Component({ template: '<button dir [color]="color"></button>', standalone: false, }) class App { @ViewChild(HostDir) hostDir!: HostDir; color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.hostDir.color).toBe('red'); fixture.componentInstance.color = 'green'; fixture.detectChanges(); expect(fixture.componentInstance.hostDir.color).toBe('green'); });
{ "end_byte": 53534, "start_byte": 45451, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }
angular/packages/core/test/acceptance/host_directives_spec.ts_53540_61782
it('should set an input that was exposed from one host directive, but not another', () => { @Directive({standalone: true}) class ExposedHostDir { @Input() color?: string; } @Directive({standalone: true}) class UnExposedHostDir { @Input() color?: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: ExposedHostDir, inputs: ['color']}, UnExposedHostDir], standalone: false, }) class Dir {} @Component({ template: '<button dir [color]="color"></button>', standalone: false, }) class App { @ViewChild(ExposedHostDir) exposedHostDir!: ExposedHostDir; @ViewChild(UnExposedHostDir) unExposedHostDir!: UnExposedHostDir; color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const {exposedHostDir, unExposedHostDir} = fixture.componentInstance; expect(exposedHostDir.color).toBe('red'); expect(unExposedHostDir.color).toBe(undefined); fixture.componentInstance.color = 'green'; fixture.detectChanges(); expect(exposedHostDir.color).toBe('green'); expect(unExposedHostDir.color).toBe(undefined); }); it('should set inputs from different host directives that have been aliased to the same name', () => { @Directive({standalone: true}) class FirstHostDir { @Input() firstColor?: string; } @Directive({standalone: true}) class SecondHostDir { @Input() secondColor?: string; } @Directive({ selector: '[dir]', hostDirectives: [ {directive: FirstHostDir, inputs: ['firstColor: buttonColor']}, {directive: SecondHostDir, inputs: ['secondColor: buttonColor']}, ], standalone: false, }) class Dir {} @Component({ template: '<button dir [buttonColor]="color"></button>', standalone: false, }) class App { @ViewChild(FirstHostDir) firstHostDir!: FirstHostDir; @ViewChild(SecondHostDir) secondHostDir!: SecondHostDir; color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const {firstHostDir, secondHostDir} = fixture.componentInstance; expect(firstHostDir.firstColor).toBe('red'); expect(secondHostDir.secondColor).toBe('red'); fixture.componentInstance.color = 'green'; fixture.detectChanges(); expect(firstHostDir.firstColor).toBe('green'); expect(secondHostDir.secondColor).toBe('green'); }); it('should not set a static input of a host directive that has not been exposed', () => { @Directive({standalone: true}) class HostDir { @Input() color?: string; } @Directive({ selector: '[dir]', hostDirectives: [HostDir], standalone: false, }) class Dir {} @Component({ template: '<button dir color="red"></button>', standalone: false, }) class App { @ViewChild(HostDir) hostDir!: HostDir; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.hostDir.color).toBe(undefined); }); it('should set a static input of a host directive that has been exposed', () => { @Directive({standalone: true}) class HostDir { @Input() color?: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['color']}], standalone: false, }) class Dir {} @Component({ template: '<button dir color="red"></button>', standalone: false, }) class App { @ViewChild(HostDir) hostDir!: HostDir; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.hostDir.color).toBe('red'); }); it('should set a static input of a host directive that has been exposed under an alias', () => { @Directive({standalone: true}) class HostDir { @Input() color?: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['color: buttonColor']}], standalone: false, }) class Dir {} @Component({ template: '<button dir buttonColor="red"></button>', standalone: false, }) class App { @ViewChild(HostDir) hostDir!: HostDir; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.hostDir.color).toBe('red'); }); it('should alias to the public name of a static host directive input, not the private one', () => { @Directive({standalone: true}) class HostDir { @Input('colorAlias') color?: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: HostDir, inputs: ['colorAlias: buttonColor']}], standalone: false, }) class Dir {} @Component({ template: '<button dir buttonColor="red"></button>', standalone: false, }) class App { @ViewChild(HostDir) hostDir!: HostDir; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.hostDir.color).toBe('red'); }); it('should set a static input that was exposed from one host directive, but not another', () => { @Directive({standalone: true}) class ExposedHostDir { @Input() color?: string; } @Directive({standalone: true}) class UnExposedHostDir { @Input() color?: string; } @Directive({ selector: '[dir]', hostDirectives: [{directive: ExposedHostDir, inputs: ['color']}, UnExposedHostDir], standalone: false, }) class Dir {} @Component({ template: '<button dir color="red"></button>', standalone: false, }) class App { @ViewChild(ExposedHostDir) exposedHostDir!: ExposedHostDir; @ViewChild(UnExposedHostDir) unExposedHostDir!: UnExposedHostDir; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.exposedHostDir.color).toBe('red'); expect(fixture.componentInstance.unExposedHostDir.color).toBe(undefined); }); it('should set static inputs from different host directives that have been aliased to the same name', () => { @Directive({standalone: true}) class FirstHostDir { @Input() firstColor?: string; } @Directive({standalone: true}) class SecondHostDir { @Input() secondColor?: string; } @Directive({ selector: '[dir]', hostDirectives: [ {directive: FirstHostDir, inputs: ['firstColor: buttonColor']}, {directive: SecondHostDir, inputs: ['secondColor: buttonColor']}, ], standalone: false, }) class Dir {} @Component({ template: '<button dir buttonColor="red"></button>', standalone: false, }) class App { @ViewChild(FirstHostDir) firstHostDir!: FirstHostDir; @ViewChild(SecondHostDir) secondHostDir!: SecondHostDir; color = 'red'; } TestBed.configureTestingModule({declarations: [App, Dir]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.firstHostDir.firstColor).toBe('red'); expect(fixture.componentInstance.secondHostDir.secondColor).toBe('red'); });
{ "end_byte": 61782, "start_byte": 53540, "url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/host_directives_spec.ts" }