_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/core/test/acceptance/content_spec.ts_35791_44633 | describe('on inline templates (e.g. *ngIf)', () => {
it('should work when matching the element name', () => {
let divDirectives = 0;
@Component({
selector: 'selector-proj',
template: '<ng-content select="div"></ng-content>',
standalone: false,
})
class SelectedNgContentComp {}
@Directive({
selector: 'div',
standalone: false,
})
class DivDirective {
constructor() {
divDirectives++;
}
}
@Component({
selector: 'main-selector',
template: '<selector-proj><div x="true" *ngIf="true">Hello world!</div></selector-proj>',
standalone: false,
})
class SelectorMainComp {}
TestBed.configureTestingModule({
declarations: [DivDirective, SelectedNgContentComp, SelectorMainComp],
});
const fixture = TestBed.createComponent<SelectorMainComp>(SelectorMainComp);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('Hello world!');
expect(divDirectives).toEqual(1);
});
it('should work when matching attributes', () => {
let xDirectives = 0;
@Component({
selector: 'selector-proj',
template: '<ng-content select="[x]"></ng-content>',
standalone: false,
})
class SelectedNgContentComp {}
@Directive({
selector: '[x]',
standalone: false,
})
class XDirective {
constructor() {
xDirectives++;
}
}
@Component({
selector: 'main-selector',
template: '<selector-proj><div x="true" *ngIf="true">Hello world!</div></selector-proj>',
standalone: false,
})
class SelectorMainComp {}
TestBed.configureTestingModule({
declarations: [XDirective, SelectedNgContentComp, SelectorMainComp],
});
const fixture = TestBed.createComponent<SelectorMainComp>(SelectorMainComp);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('Hello world!');
expect(xDirectives).toEqual(1);
});
it('should work when matching classes', () => {
let xDirectives = 0;
@Component({
selector: 'selector-proj',
template: '<ng-content select=".x"></ng-content>',
standalone: false,
})
class SelectedNgContentComp {}
@Directive({
selector: '.x',
standalone: false,
})
class XDirective {
constructor() {
xDirectives++;
}
}
@Component({
selector: 'main-selector',
template: '<selector-proj><div class="x" *ngIf="true">Hello world!</div></selector-proj>',
standalone: false,
})
class SelectorMainComp {}
TestBed.configureTestingModule({
declarations: [XDirective, SelectedNgContentComp, SelectorMainComp],
});
const fixture = TestBed.createComponent<SelectorMainComp>(SelectorMainComp);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('Hello world!');
expect(xDirectives).toEqual(1);
});
it('should ignore synthesized attributes (e.g. ngTrackBy)', () => {
@Component({
selector: 'selector-proj',
template: '<ng-content select="[ngTrackBy]"></ng-content>',
standalone: false,
})
class SelectedNgContentComp {}
@Component({
selector: 'main-selector',
template:
'inline(<selector-proj><div *ngFor="let item of items trackBy getItemId">{{item.name}}</div></selector-proj>)' +
'ng-template(<selector-proj><ng-template ngFor [ngForOf]="items" let-item ngTrackBy="getItemId"><div>{{item.name}}</div></ng-template></selector-proj>)',
standalone: false,
})
class SelectorMainComp {
items = [
{id: 1, name: 'one'},
{id: 2, name: 'two'},
{id: 3, name: 'three'},
];
getItemId(item: {id: number}) {
return item.id;
}
}
TestBed.configureTestingModule({declarations: [SelectedNgContentComp, SelectorMainComp]});
const fixture = TestBed.createComponent<SelectorMainComp>(SelectorMainComp);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('inline()ng-template(onetwothree)');
});
it('should project template content with `ngProjectAs` defined', () => {
@Component({
selector: 'projector-app',
template: `
Projected
<ng-content select="foo"></ng-content>
<ng-content select="[foo]"></ng-content>
<ng-content select=".foo"></ng-content>
`,
standalone: false,
})
class ProjectorApp {}
@Component({
selector: 'root-comp',
template: `
<projector-app>
<div *ngIf="show" ngProjectAs="foo">as element</div>
<div *ngIf="show" ngProjectAs="[foo]">as attribute</div>
<div *ngIf="show" ngProjectAs=".foo">as class</div>
</projector-app>
`,
standalone: false,
})
class RootComp {
show = true;
}
TestBed.configureTestingModule({
declarations: [ProjectorApp, RootComp],
});
const fixture = TestBed.createComponent(RootComp);
fixture.detectChanges();
let content = fixture.nativeElement.textContent;
expect(content).toContain('as element');
expect(content).toContain('as attribute');
expect(content).toContain('as class');
fixture.componentInstance.show = false;
fixture.detectChanges();
content = fixture.nativeElement.textContent;
expect(content).not.toContain('as element');
expect(content).not.toContain('as attribute');
expect(content).not.toContain('as class');
});
describe('on containers', () => {
it('should work when matching attributes', () => {
let xDirectives = 0;
@Component({
selector: 'selector-proj',
template: '<ng-content select="[x]"></ng-content>',
standalone: false,
})
class SelectedNgContentComp {}
@Directive({
selector: '[x]',
standalone: false,
})
class XDirective {
constructor() {
xDirectives++;
}
}
@Component({
selector: 'main-selector',
template:
'<selector-proj><ng-container x="true">Hello world!</ng-container></selector-proj>',
standalone: false,
})
class SelectorMainComp {}
TestBed.configureTestingModule({
declarations: [XDirective, SelectedNgContentComp, SelectorMainComp],
});
const fixture = TestBed.createComponent<SelectorMainComp>(SelectorMainComp);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('Hello world!');
expect(xDirectives).toEqual(1);
});
it('should work when matching classes', () => {
let xDirectives = 0;
@Component({
selector: 'selector-proj',
template: '<ng-content select=".x"></ng-content>',
standalone: false,
})
class SelectedNgContentComp {}
@Directive({
selector: '.x',
standalone: false,
})
class XDirective {
constructor() {
xDirectives++;
}
}
@Component({
selector: 'main-selector',
template:
'<selector-proj><ng-container class="x">Hello world!</ng-container></selector-proj>',
standalone: false,
})
class SelectorMainComp {}
TestBed.configureTestingModule({
declarations: [XDirective, SelectedNgContentComp, SelectorMainComp],
});
const fixture = TestBed.createComponent<SelectorMainComp>(SelectorMainComp);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('Hello world!');
expect(xDirectives).toEqual(1);
});
it('should work without exception when subelement has both ngIf and class as interpolation', () => {
@Component({
selector: 'child-comp',
template: '<ng-content select=".nomatch"></ng-content>',
standalone: false,
})
class ChildComp {}
@Component({
selector: 'parent-comp',
template: `<child-comp><span *ngIf="true" class="{{'a'}}"></span></child-comp>`,
standalone: false,
})
class ParentComp {}
TestBed.configureTestingModule({declarations: [ParentComp, ChildComp]});
const fixture = TestBed.createComponent<ParentComp>(ParentComp);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toBe('<child-comp></child-comp>');
});
}); | {
"end_byte": 44633,
"start_byte": 35791,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/content_spec.ts"
} |
angular/packages/core/test/acceptance/content_spec.ts_44639_45736 | it('selection of child element should properly work even with confusing attribute names', () => {
@Component({
selector: 'child-comp',
template: '<ng-content select=".title"></ng-content>',
standalone: false,
})
class ChildComp {}
@Component({
selector: 'parent-comp',
template: `<child-comp><span *ngIf="true" id="5" jjj="class" class="{{'a'}}" [title]="'abc'"></span></child-comp>`,
standalone: false,
})
class ParentComp {}
TestBed.configureTestingModule({declarations: [ParentComp, ChildComp]});
const fixture = TestBed.createComponent<ParentComp>(ParentComp);
fixture.detectChanges();
// tNode.attrs will be ['id', '5', 'jjj', 'class', 3 /* AttributeMarker.Bindings */, 'class',
// 'title', 4 /* AttributeMarker.Template */, 'ngIf'] isNodeMatchingSelector() must not
// confuse it as 'class=title' attribute. <ng-content select=".title"> should not match the
// child.
expect(fixture.nativeElement.innerHTML).toBe('<child-comp></child-comp>');
});
}); | {
"end_byte": 45736,
"start_byte": 44639,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/content_spec.ts"
} |
angular/packages/core/test/acceptance/content_spec.ts_45740_55077 | describe('fallback content', () => {
it('should render the fallback content if nothing is projected into a slot', () => {
@Component({
selector: 'projection',
template:
`
<ng-content select="[one]">One fallback</ng-content>|` +
`<ng-content>Catch-all fallback</ng-content>|` +
`<ng-content select="[two]">Two fallback</ng-content>` +
`<ng-content select="[three]">Three fallback</ng-content>
`,
standalone: true,
})
class Projection {}
@Component({
standalone: true,
imports: [Projection],
template: `
<projection>
<span one>One</span>
<div three>Three</div>
</projection>
`,
})
class App {}
const fixture = TestBed.createComponent(App);
expect(getElementHtml(fixture.nativeElement)).toContain(
`<projection><span one="">One</span>|` +
`Catch-all fallback|Two fallback<div three="">Three</div></projection>`,
);
});
it('should render the catch-all slots fallback content if the element only contains comments', () => {
@Component({
selector: 'projection',
template: `<ng-content>Fallback content</ng-content>`,
standalone: true,
})
class Projection {}
@Component({
standalone: true,
imports: [Projection],
template: `
<projection>
<!-- One -->
<!-- Two -->
</projection>
`,
})
class App {}
const fixture = TestBed.createComponent(App);
expect(getElementHtml(fixture.nativeElement)).toContain(
`<projection>Fallback content</projection>`,
);
});
it('should account for ngProjectAs when rendering fallback content', () => {
@Component({
selector: 'projection',
template: `<ng-content select="div">I have no divs</ng-content>|<ng-content select="span">I have no spans</ng-content>`,
standalone: true,
})
class Projection {}
@Component({
standalone: true,
imports: [Projection],
template: `
<projection>
<div ngProjectAs="span">div pretending to be a span</div>
</projection>
`,
})
class App {
@ViewChild(Projection) projection!: Projection;
}
const fixture = TestBed.createComponent(App);
expect(getElementHtml(fixture.nativeElement)).toContain(
`<projection>I have no divs|` +
`<div ngprojectas="span">div pretending to be a span</div></projection>`,
);
});
it('should not render the fallback content if there is a control flow expression', () => {
@Component({
selector: 'projection',
template: `<ng-content>Wildcard fallback</ng-content>|<ng-content select="span">Span fallback</ng-content>`,
standalone: true,
})
class Projection {}
@Component({
standalone: true,
imports: [Projection],
template: `
<projection>
@if (showSpan) {
<span>Span override</span>
}
</projection>
`,
})
class App {
showSpan = false;
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(getElementHtml(fixture.nativeElement)).toContain(
`<projection>Wildcard fallback|</projection>`,
);
fixture.componentInstance.showSpan = true;
fixture.detectChanges();
expect(getElementHtml(fixture.nativeElement)).toContain(
`<projection>Wildcard fallback|<span>Span override</span></projection>`,
);
fixture.componentInstance.showSpan = false;
fixture.detectChanges();
expect(getElementHtml(fixture.nativeElement)).toContain(
`<projection>Wildcard fallback|</projection>`,
);
});
it('should not render the fallback content if there is an ng-container', () => {
@Component({
selector: 'projection',
template: `<ng-content>Fallback</ng-content>`,
standalone: true,
})
class Projection {}
@Component({
standalone: true,
imports: [Projection],
template: `
<projection><ng-container/></projection>
`,
})
class App {
showSpan = false;
}
const fixture = TestBed.createComponent(App);
expect(getElementHtml(fixture.nativeElement)).toContain(`<projection></projection>`);
});
it('should be able to use data bindings in the fallback content', () => {
@Component({
selector: 'projection',
template: `<ng-content>Value: {{value}}</ng-content>`,
standalone: true,
})
class Projection {
value = 0;
}
@Component({standalone: true, imports: [Projection], template: `<projection/>`})
class App {
@ViewChild(Projection) projection!: Projection;
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(getElementHtml(fixture.nativeElement)).toContain(`<projection>Value: 0</projection>`);
fixture.componentInstance.projection.value = 1;
fixture.detectChanges();
expect(getElementHtml(fixture.nativeElement)).toContain(`<projection>Value: 1</projection>`);
});
it('should be able to use event listeners in the fallback content', () => {
@Component({
selector: 'projection',
template: `
<ng-content>
<button (click)="callback()">Click me</button>
</ng-content>
Value: {{value}}
`,
standalone: true,
})
class Projection {
value = 0;
callback() {
this.value++;
}
}
@Component({standalone: true, imports: [Projection], template: `<projection/>`})
class App {}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(getElementHtml(fixture.nativeElement)).toContain(`Value: 0`);
fixture.nativeElement.querySelector('button').click();
fixture.detectChanges();
expect(getElementHtml(fixture.nativeElement)).toContain(`Value: 1`);
});
it('should create and destroy directives in the fallback content', () => {
let directiveCount = 0;
@Directive({
selector: 'fallback-dir',
standalone: true,
})
class FallbackDir implements OnDestroy {
constructor() {
directiveCount++;
}
ngOnDestroy(): void {
directiveCount--;
}
}
@Component({
selector: 'projection',
template: `<ng-content><fallback-dir/></ng-content>`,
standalone: true,
imports: [FallbackDir],
})
class Projection {}
@Component({
standalone: true,
imports: [Projection],
template: `
@if (hasProjection) {
<projection/>
}
`,
})
class App {
hasProjection = true;
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(directiveCount).toBe(1);
fixture.componentInstance.hasProjection = false;
fixture.detectChanges();
expect(directiveCount).toBe(0);
});
it('should be able to query inside the fallback content', () => {
let directiveInstance: FallbackDir | undefined;
@Directive({
selector: 'fallback-dir',
standalone: true,
})
class FallbackDir {
constructor() {
directiveInstance = this;
}
}
@Component({
selector: 'projection',
template: `<ng-content><fallback-dir/></ng-content>`,
standalone: true,
imports: [FallbackDir],
})
class Projection {
@ViewChild(FallbackDir) fallback!: FallbackDir;
}
@Component({
standalone: true,
imports: [Projection],
template: `<projection/>`,
})
class App {
@ViewChild(Projection) projection!: Projection;
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(directiveInstance).toBeTruthy();
expect(fixture.componentInstance.projection.fallback).toBe(directiveInstance!);
});
it('should be able to inject the host component from inside the fallback content', () => {
@Directive({
selector: 'fallback-dir',
standalone: true,
})
class FallbackDir {
host = inject(Projection);
}
@Component({
selector: 'projection',
template: `<ng-content><fallback-dir/></ng-content>`,
standalone: true,
imports: [FallbackDir],
})
class Projection {
@ViewChild(FallbackDir) fallback!: FallbackDir;
}
@Component({
standalone: true,
imports: [Projection],
template: `<projection/>`,
})
class App {
@ViewChild(Projection) projection!: Projection;
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const instance = fixture.componentInstance;
expect(instance.projection.fallback.host).toBe(instance.projection);
}); | {
"end_byte": 55077,
"start_byte": 45740,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/content_spec.ts"
} |
angular/packages/core/test/acceptance/content_spec.ts_55083_62025 | it('should render the fallback content if content is not provided through projectableNodes', () => {
@Component({
standalone: true,
template:
`<ng-content>One fallback</ng-content>|` +
`<ng-content>Two fallback</ng-content>|<ng-content>Three fallback</ng-content>`,
})
class Projection {}
const hostElement = document.createElement('div');
const environmentInjector = TestBed.inject(EnvironmentInjector);
const paragraph = document.createElement('p');
paragraph.textContent = 'override';
const projectableNodes = [[paragraph]];
const componentRef = createComponent(Projection, {
hostElement,
environmentInjector,
projectableNodes,
});
componentRef.changeDetectorRef.detectChanges();
expect(getElementHtml(hostElement)).toContain('<p>override</p>|Two fallback|Three fallback');
componentRef.destroy();
});
it('should render the content through projectableNodes along with fallback', () => {
@Component({
standalone: true,
template:
`<ng-content>One fallback</ng-content>|` +
`<ng-content>Two fallback</ng-content>|<ng-content>Three fallback</ng-content>`,
})
class Projection {}
const hostElement = document.createElement('div');
const environmentInjector = TestBed.inject(EnvironmentInjector);
const paragraph = document.createElement('p');
paragraph.textContent = 'override';
const secondParagraph = document.createElement('p');
secondParagraph.textContent = 'override';
const projectableNodes = [[paragraph], [], [secondParagraph]];
const componentRef = createComponent(Projection, {
hostElement,
environmentInjector,
projectableNodes,
});
componentRef.changeDetectorRef.detectChanges();
expect(getElementHtml(hostElement)).toContain('<p>override</p>|Two fallback|<p>override</p>');
});
it('should render fallback content when ng-content is inside an ng-template', () => {
@Component({
selector: 'projection',
template: `<ng-container #ref/><ng-template #template><ng-content>Fallback</ng-content></ng-template>`,
standalone: true,
})
class Projection {
@ViewChild('template') template!: TemplateRef<unknown>;
@ViewChild('ref', {read: ViewContainerRef}) viewContainerRef!: ViewContainerRef;
createContent() {
this.viewContainerRef.createEmbeddedView(this.template);
}
}
@Component({
standalone: true,
imports: [Projection],
template: `<projection/>`,
})
class App {
@ViewChild(Projection) projection!: Projection;
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(getElementHtml(fixture.nativeElement)).toContain(`<projection></projection>`);
fixture.componentInstance.projection.createContent();
fixture.detectChanges();
expect(getElementHtml(fixture.nativeElement)).toContain(`<projection>Fallback</projection>`);
});
it('should render the fallback content when ng-content is re-projected', () => {
@Component({
selector: 'inner-projection',
template: `
<ng-content select="[inner-header]">Inner header fallback</ng-content>
<ng-content select="[inner-footer]">Inner footer fallback</ng-content>
`,
standalone: true,
})
class InnerProjection {}
@Component({
selector: 'projection',
template: `
<inner-projection>
<ng-content select="[outer-header]" inner-header>Outer header fallback</ng-content>
<ng-content select="[outer-footer]" inner-footer>Outer footer fallback</ng-content>
</inner-projection>
`,
standalone: true,
imports: [InnerProjection],
})
class Projection {}
@Component({
standalone: true,
imports: [Projection],
template: `
<projection>
<span outer-header>Outer header override</span>
</projection>
`,
})
class App {}
const fixture = TestBed.createComponent(App);
const content = getElementHtml(fixture.nativeElement);
expect(content).toContain('Outer header override');
expect(content).toContain('Outer footer fallback');
});
it('should not instantiate directives inside the fallback content', () => {
let creationCount = 0;
@Component({
selector: 'fallback',
standalone: true,
template: 'Fallback',
})
class Fallback {
constructor() {
creationCount++;
}
}
@Component({
selector: 'projection',
template: `<ng-content><fallback/></ng-content>`,
standalone: true,
imports: [Fallback],
})
class Projection {}
@Component({
standalone: true,
imports: [Projection],
template: `<projection>Hello</projection>`,
})
class App {}
const fixture = TestBed.createComponent(App);
expect(creationCount).toBe(0);
expect(getElementHtml(fixture.nativeElement)).toContain(`<projection>Hello</projection>`);
});
it(
'should render the fallback content when an instance of a component that uses ' +
'fallback content is declared after one that does not',
() => {
@Component({
selector: 'projection',
template: `<ng-content>Fallback</ng-content>`,
standalone: true,
})
class Projection {}
@Component({
standalone: true,
imports: [Projection],
template: `
<projection>Content</projection>
<projection/>
`,
})
class App {}
const fixture = TestBed.createComponent(App);
expect(getElementHtml(fixture.nativeElement)).toContain(
'<projection>Content</projection><projection>Fallback</projection>',
);
},
);
it(
'should render the fallback content when an instance of a component that uses ' +
'fallback content is declared before one that does not',
() => {
@Component({
selector: 'projection',
template: `<ng-content>Fallback</ng-content>`,
standalone: true,
})
class Projection {}
@Component({
standalone: true,
imports: [Projection],
template: `
<projection/>
<projection>Content</projection>
`,
})
class App {}
const fixture = TestBed.createComponent(App);
expect(getElementHtml(fixture.nativeElement)).toContain(
'<projection>Fallback</projection><projection>Content</projection>',
);
},
);
});
}); | {
"end_byte": 62025,
"start_byte": 55083,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/content_spec.ts"
} |
angular/packages/core/test/acceptance/query_spec.ts_0_620 | /**
* @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 {
AfterViewInit,
Component,
ContentChild,
ContentChildren,
Directive,
ElementRef,
EventEmitter,
forwardRef,
InjectionToken,
Input,
QueryList,
TemplateRef,
Type,
ViewChild,
ViewChildren,
ViewContainerRef,
ViewRef,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser'; | {
"end_byte": 620,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/query_spec.ts"
} |
angular/packages/core/test/acceptance/query_spec.ts_622_10581 | describe('query logic', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
AppComp,
QueryComp,
SimpleCompA,
SimpleCompB,
StaticViewQueryComp,
TextDirective,
SubclassStaticViewQueryComp,
StaticContentQueryComp,
SubclassStaticContentQueryComp,
QueryCompWithChanges,
StaticContentQueryDir,
SuperDirectiveQueryTarget,
SuperDirective,
SubComponent,
TestComponentWithToken,
TestInjectionTokenContentQueries,
TestInjectionTokenQueries,
],
});
});
describe('view queries', () => {
it('should return Component instances when Components are labeled and retrieved', () => {
const template = `
<div><simple-comp-a #viewQuery></simple-comp-a></div>
<div><simple-comp-b #viewQuery></simple-comp-b></div>
`;
const fixture = initWithTemplate(QueryComp, template);
const comp = fixture.componentInstance;
expect(comp.viewChild).toBeInstanceOf(SimpleCompA);
expect(comp.viewChildren.first).toBeInstanceOf(SimpleCompA);
expect(comp.viewChildren.last).toBeInstanceOf(SimpleCompB);
});
it('should return ElementRef when HTML element is labeled and retrieved', () => {
const template = `
<div #viewQuery></div>
`;
const fixture = initWithTemplate(QueryComp, template);
const comp = fixture.componentInstance;
expect(comp.viewChild).toBeInstanceOf(ElementRef);
expect(comp.viewChildren.first).toBeInstanceOf(ElementRef);
});
it('should return ElementRefs when HTML elements are labeled and retrieved', () => {
const template = `
<div #viewQuery #first>A</div>
<div #viewQuery #second>B</div>
`;
const fixture = initWithTemplate(QueryComp, template);
const comp = fixture.componentInstance;
expect(comp.viewChild).toBeInstanceOf(ElementRef);
expect(comp.viewChild.nativeElement).toBe(fixture.debugElement.children[0].nativeElement);
expect(comp.viewChildren.first).toBeInstanceOf(ElementRef);
expect(comp.viewChildren.last).toBeInstanceOf(ElementRef);
expect(comp.viewChildren.length).toBe(2);
});
it('should return TemplateRef when template is labeled and retrieved', () => {
const template = `
<ng-template #viewQuery></ng-template>
`;
const fixture = initWithTemplate(QueryComp, template);
const comp = fixture.componentInstance;
expect(comp.viewChildren.first).toBeInstanceOf(TemplateRef);
});
it('should support selecting InjectionToken', () => {
const fixture = TestBed.createComponent(TestInjectionTokenQueries);
const instance = fixture.componentInstance;
fixture.detectChanges();
expect(instance.viewFirstOption).toBeDefined();
expect(instance.viewFirstOption instanceof TestComponentWithToken).toBe(true);
expect(instance.viewOptions).toBeDefined();
expect(instance.viewOptions.length).toBe(2);
expect(instance.contentFirstOption).toBeUndefined();
expect(instance.contentOptions).toBeDefined();
expect(instance.contentOptions.length).toBe(0);
});
it('should return TemplateRefs when templates are labeled and retrieved', () => {
const template = `
<ng-template #viewQuery></ng-template>
<ng-template #viewQuery></ng-template>
`;
const fixture = initWithTemplate(QueryComp, template);
const comp = fixture.componentInstance;
expect(comp.viewChild).toBeInstanceOf(TemplateRef);
expect(comp.viewChild.elementRef.nativeElement).toBe(
fixture.debugElement.childNodes[0].nativeNode,
);
expect(comp.viewChildren.first).toBeInstanceOf(TemplateRef);
expect(comp.viewChildren.last).toBeInstanceOf(TemplateRef);
expect(comp.viewChildren.length).toBe(2);
});
it('should set static view child queries in creation mode (and just in creation mode)', () => {
const fixture = TestBed.createComponent(StaticViewQueryComp);
const component = fixture.componentInstance;
// static ViewChild query should be set in creation mode, before CD runs
expect(component.textDir).toBeInstanceOf(TextDirective);
expect(component.textDir.text).toEqual('');
expect(component.setEvents).toEqual(['textDir set']);
// dynamic ViewChild query should not have been resolved yet
expect(component.foo).not.toBeDefined();
const span = fixture.nativeElement.querySelector('span');
fixture.detectChanges();
expect(component.textDir.text).toEqual('some text');
expect(component.foo.nativeElement).toBe(span);
expect(component.setEvents).toEqual(['textDir set', 'foo set']);
});
it('should support static view child queries inherited from superclasses', () => {
const fixture = TestBed.createComponent(SubclassStaticViewQueryComp);
const component = fixture.componentInstance;
const divs = fixture.nativeElement.querySelectorAll('div');
const spans = fixture.nativeElement.querySelectorAll('span');
// static ViewChild queries should be set in creation mode, before CD runs
expect(component.textDir).toBeInstanceOf(TextDirective);
expect(component.textDir.text).toEqual('');
expect(component.bar.nativeElement).toEqual(divs[1]);
// dynamic ViewChild queries should not have been resolved yet
expect(component.foo).not.toBeDefined();
expect(component.baz).not.toBeDefined();
fixture.detectChanges();
expect(component.textDir.text).toEqual('some text');
expect(component.foo.nativeElement).toBe(spans[0]);
expect(component.baz.nativeElement).toBe(spans[1]);
});
it('should support multiple static view queries (multiple template passes)', () => {
const template = `
<static-view-query-comp></static-view-query-comp>
<static-view-query-comp></static-view-query-comp>
`;
TestBed.overrideComponent(AppComp, {set: new Component({template})});
const fixture = TestBed.createComponent(AppComp);
const firstComponent = fixture.debugElement.children[0].injector.get(StaticViewQueryComp);
const secondComponent = fixture.debugElement.children[1].injector.get(StaticViewQueryComp);
// static ViewChild query should be set in creation mode, before CD runs
expect(firstComponent.textDir).toBeInstanceOf(TextDirective);
expect(secondComponent.textDir).toBeInstanceOf(TextDirective);
expect(firstComponent.textDir.text).toEqual('');
expect(secondComponent.textDir.text).toEqual('');
expect(firstComponent.setEvents).toEqual(['textDir set']);
expect(secondComponent.setEvents).toEqual(['textDir set']);
// dynamic ViewChild query should not have been resolved yet
expect(firstComponent.foo).not.toBeDefined();
expect(secondComponent.foo).not.toBeDefined();
const spans = fixture.nativeElement.querySelectorAll('span');
fixture.detectChanges();
expect(firstComponent.textDir.text).toEqual('some text');
expect(secondComponent.textDir.text).toEqual('some text');
expect(firstComponent.foo.nativeElement).toBe(spans[0]);
expect(secondComponent.foo.nativeElement).toBe(spans[1]);
expect(firstComponent.setEvents).toEqual(['textDir set', 'foo set']);
expect(secondComponent.setEvents).toEqual(['textDir set', 'foo set']);
});
it('should allow for view queries to be inherited from a directive', () => {
const fixture = TestBed.createComponent(SubComponent);
const comp = fixture.componentInstance;
fixture.detectChanges();
expect(comp.headers).toBeTruthy();
expect(comp.headers.length).toBe(2);
expect(
comp.headers.toArray().every((result) => result instanceof SuperDirectiveQueryTarget),
).toBe(true);
});
it('should support ViewChild query inherited from undecorated superclasses', () => {
class MyComp {
@ViewChild('foo') foo: any;
}
@Component({
selector: 'sub-comp',
template: '<div #foo></div>',
standalone: false,
})
class SubComp extends MyComp {}
TestBed.configureTestingModule({declarations: [SubComp]});
const fixture = TestBed.createComponent(SubComp);
fixture.detectChanges();
expect(fixture.componentInstance.foo).toBeInstanceOf(ElementRef);
});
it('should support ViewChild query inherited from undecorated grand superclasses', () => {
class MySuperComp {
@ViewChild('foo') foo: any;
}
class MyComp extends MySuperComp {}
@Component({
selector: 'sub-comp',
template: '<div #foo></div>',
standalone: false,
})
class SubComp extends MyComp {}
TestBed.configureTestingModule({declarations: [SubComp]});
const fixture = TestBed.createComponent(SubComp);
fixture.detectChanges();
expect(fixture.componentInstance.foo).toBeInstanceOf(ElementRef);
});
it('should support ViewChildren query inherited from undecorated superclasses', () => {
@Directive({
selector: '[some-dir]',
standalone: false,
})
class SomeDir {}
class MyComp {
@ViewChildren(SomeDir) foo!: QueryList<SomeDir>;
}
@Component({
selector: 'sub-comp',
template: `
<div some-dir></div>
<div some-dir></div>
`,
standalone: false,
})
class SubComp extends MyComp {}
TestBed.configureTestingModule({declarations: [SubComp, SomeDir]});
const fixture = TestBed.createComponent(SubComp);
fixture.detectChanges();
expect(fixture.componentInstance.foo).toBeInstanceOf(QueryList);
expect(fixture.componentInstance.foo.length).toBe(2);
}); | {
"end_byte": 10581,
"start_byte": 622,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/query_spec.ts"
} |
angular/packages/core/test/acceptance/query_spec.ts_10587_13915 | it('should support ViewChildren query inherited from undecorated grand superclasses', () => {
@Directive({
selector: '[some-dir]',
standalone: false,
})
class SomeDir {}
class MySuperComp {
@ViewChildren(SomeDir) foo!: QueryList<SomeDir>;
}
class MyComp extends MySuperComp {}
@Component({
selector: 'sub-comp',
template: `
<div some-dir></div>
<div some-dir></div>
`,
standalone: false,
})
class SubComp extends MyComp {}
TestBed.configureTestingModule({declarations: [SubComp, SomeDir]});
const fixture = TestBed.createComponent(SubComp);
fixture.detectChanges();
expect(fixture.componentInstance.foo).toBeInstanceOf(QueryList);
expect(fixture.componentInstance.foo.length).toBe(2);
});
it('should support ViewChild query where template is inserted in child component', () => {
@Component({
selector: 'required',
template: '',
standalone: false,
})
class Required {}
@Component({
selector: 'insertion',
template: `<ng-container [ngTemplateOutlet]="content"></ng-container>`,
standalone: false,
})
class Insertion {
@Input() content!: TemplateRef<{}>;
}
@Component({
template: `
<ng-template #template>
<required></required>
</ng-template>
<insertion [content]="template"></insertion>
`,
standalone: false,
})
class App {
@ViewChild(Required) requiredEl!: Required;
viewChildAvailableInAfterViewInit?: boolean;
ngAfterViewInit() {
this.viewChildAvailableInAfterViewInit = this.requiredEl !== undefined;
}
}
const fixture = TestBed.configureTestingModule({
declarations: [App, Insertion, Required],
}).createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.viewChildAvailableInAfterViewInit).toBe(true);
});
it('should destroy QueryList when the containing view is destroyed', () => {
let queryInstance: QueryList<any>;
@Component({
selector: 'comp-with-view-query',
template: '<div #foo>Content</div>',
standalone: false,
})
class ComponentWithViewQuery {
@ViewChildren('foo')
set foo(value: any) {
queryInstance = value;
}
get foo() {
return queryInstance;
}
}
@Component({
selector: 'root',
template: `
<ng-container *ngIf="condition">
<comp-with-view-query></comp-with-view-query>
</ng-container>
`,
standalone: false,
})
class Root {
condition = true;
}
TestBed.configureTestingModule({
declarations: [Root, ComponentWithViewQuery],
imports: [CommonModule],
});
const fixture = TestBed.createComponent(Root);
fixture.detectChanges();
expect((queryInstance!.changes as EventEmitter<any>).closed).toBeFalsy();
fixture.componentInstance.condition = false;
fixture.detectChanges();
expect((queryInstance!.changes as EventEmitter<any>).closed).toBeTruthy();
});
}); | {
"end_byte": 13915,
"start_byte": 10587,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/query_spec.ts"
} |
angular/packages/core/test/acceptance/query_spec.ts_13919_22296 | describe('content queries', () => {
it('should return Component instance when Component is labeled and retrieved', () => {
const template = `
<local-ref-query-component #q>
<simple-comp-a #contentQuery></simple-comp-a>
</local-ref-query-component>
`;
const fixture = initWithTemplate(AppComp, template);
const comp = fixture.debugElement.children[0].references['q'];
expect(comp.contentChild).toBeInstanceOf(SimpleCompA);
expect(comp.contentChildren.first).toBeInstanceOf(SimpleCompA);
});
it('should support selecting InjectionToken', () => {
const fixture = TestBed.createComponent(TestInjectionTokenContentQueries);
const instance = fixture.debugElement.query(
By.directive(TestInjectionTokenQueries),
).componentInstance;
fixture.detectChanges();
expect(instance.contentFirstOption).toBeDefined();
expect(instance.contentFirstOption instanceof TestComponentWithToken).toBe(true);
expect(instance.contentOptions).toBeDefined();
expect(instance.contentOptions.length).toBe(2);
});
it('should return Component instances when Components are labeled and retrieved', () => {
const template = `
<local-ref-query-component #q>
<simple-comp-a #contentQuery></simple-comp-a>
<simple-comp-b #contentQuery></simple-comp-b>
</local-ref-query-component>
`;
const fixture = initWithTemplate(AppComp, template);
const comp = fixture.debugElement.children[0].references['q'];
expect(comp.contentChild).toBeInstanceOf(SimpleCompA);
expect(comp.contentChildren.first).toBeInstanceOf(SimpleCompA);
expect(comp.contentChildren.last).toBeInstanceOf(SimpleCompB);
expect(comp.contentChildren.length).toBe(2);
});
it('should return ElementRef when HTML element is labeled and retrieved', () => {
const template = `
<local-ref-query-component #q>
<div #contentQuery></div>
</local-ref-query-component>
`;
const fixture = initWithTemplate(AppComp, template);
const comp = fixture.debugElement.children[0].references['q'];
expect(comp.contentChildren.first).toBeInstanceOf(ElementRef);
});
it('should return ElementRefs when HTML elements are labeled and retrieved', () => {
const template = `
<local-ref-query-component #q>
<div #contentQuery></div>
<div #contentQuery></div>
</local-ref-query-component>
`;
const fixture = initWithTemplate(AppComp, template);
const firstChild = fixture.debugElement.children[0];
const comp = firstChild.references['q'];
expect(comp.contentChild).toBeInstanceOf(ElementRef);
expect(comp.contentChild.nativeElement).toBe(firstChild.children[0].nativeElement);
expect(comp.contentChildren.first).toBeInstanceOf(ElementRef);
expect(comp.contentChildren.last).toBeInstanceOf(ElementRef);
expect(comp.contentChildren.length).toBe(2);
});
it('should return TemplateRef when template is labeled and retrieved', () => {
const template = `
<local-ref-query-component #q>
<ng-template #contentQuery></ng-template>
</local-ref-query-component>
`;
const fixture = initWithTemplate(AppComp, template);
const comp = fixture.debugElement.children[0].references['q'];
expect(comp.contentChildren.first).toBeInstanceOf(TemplateRef);
});
it('should return TemplateRefs when templates are labeled and retrieved', () => {
const template = `
<local-ref-query-component #q>
<ng-template #contentQuery></ng-template>
<ng-template #contentQuery></ng-template>
</local-ref-query-component>
`;
const fixture = initWithTemplate(AppComp, template);
const firstChild = fixture.debugElement.children[0];
const comp = firstChild.references['q'];
expect(comp.contentChild).toBeInstanceOf(TemplateRef);
expect(comp.contentChild.elementRef.nativeElement).toBe(firstChild.childNodes[0].nativeNode);
expect(comp.contentChildren.first).toBeInstanceOf(TemplateRef);
expect(comp.contentChildren.last).toBeInstanceOf(TemplateRef);
expect(comp.contentChildren.length).toBe(2);
});
it('should set static content child queries in creation mode (and just in creation mode)', () => {
const template = `
<static-content-query-comp>
<div [text]="text"></div>
<span #foo></span>
</static-content-query-comp>
`;
TestBed.overrideComponent(AppComp, {set: new Component({template})});
const fixture = TestBed.createComponent(AppComp);
const component = fixture.debugElement.children[0].injector.get(StaticContentQueryComp);
// static ContentChild query should be set in creation mode, before CD runs
expect(component.textDir).toBeInstanceOf(TextDirective);
expect(component.textDir.text).toEqual('');
expect(component.setEvents).toEqual(['textDir set']);
// dynamic ContentChild query should not have been resolved yet
expect(component.foo).not.toBeDefined();
const span = fixture.nativeElement.querySelector('span');
(fixture.componentInstance as any).text = 'some text';
fixture.detectChanges();
expect(component.textDir.text).toEqual('some text');
expect(component.foo.nativeElement).toBe(span);
expect(component.setEvents).toEqual(['textDir set', 'foo set']);
});
it('should support static content child queries inherited from superclasses', () => {
const template = `
<subclass-static-content-query-comp>
<div [text]="text"></div>
<span #foo></span>
<div #bar></div>
<span #baz></span>
</subclass-static-content-query-comp>
`;
TestBed.overrideComponent(AppComp, {set: new Component({template})});
const fixture = TestBed.createComponent(AppComp);
const component = fixture.debugElement.children[0].injector.get(
SubclassStaticContentQueryComp,
);
const divs = fixture.nativeElement.querySelectorAll('div');
const spans = fixture.nativeElement.querySelectorAll('span');
// static ContentChild queries should be set in creation mode, before CD runs
expect(component.textDir).toBeInstanceOf(TextDirective);
expect(component.textDir.text).toEqual('');
expect(component.bar.nativeElement).toEqual(divs[1]);
// dynamic ContentChild queries should not have been resolved yet
expect(component.foo).not.toBeDefined();
expect(component.baz).not.toBeDefined();
(fixture.componentInstance as any).text = 'some text';
fixture.detectChanges();
expect(component.textDir.text).toEqual('some text');
expect(component.foo.nativeElement).toBe(spans[0]);
expect(component.baz.nativeElement).toBe(spans[1]);
});
it('should set static content child queries on directives', () => {
const template = `
<div staticContentQueryDir>
<div [text]="text"></div>
<span #foo></span>
</div>
`;
TestBed.overrideComponent(AppComp, {set: new Component({template})});
const fixture = TestBed.createComponent(AppComp);
const component = fixture.debugElement.children[0].injector.get(StaticContentQueryDir);
// static ContentChild query should be set in creation mode, before CD runs
expect(component.textDir).toBeInstanceOf(TextDirective);
expect(component.textDir.text).toEqual('');
expect(component.setEvents).toEqual(['textDir set']);
// dynamic ContentChild query should not have been resolved yet
expect(component.foo).not.toBeDefined();
const span = fixture.nativeElement.querySelector('span');
(fixture.componentInstance as any).text = 'some text';
fixture.detectChanges();
expect(component.textDir.text).toEqual('some text');
expect(component.foo.nativeElement).toBe(span);
expect(component.setEvents).toEqual(['textDir set', 'foo set']);
}); | {
"end_byte": 22296,
"start_byte": 13919,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/query_spec.ts"
} |
angular/packages/core/test/acceptance/query_spec.ts_22302_31200 | it('should support multiple content query components (multiple template passes)', () => {
const template = `
<static-content-query-comp>
<div [text]="text"></div>
<span #foo></span>
</static-content-query-comp>
<static-content-query-comp>
<div [text]="text"></div>
<span #foo></span>
</static-content-query-comp>
`;
TestBed.overrideComponent(AppComp, {set: new Component({template})});
const fixture = TestBed.createComponent(AppComp);
const firstComponent = fixture.debugElement.children[0].injector.get(StaticContentQueryComp);
const secondComponent = fixture.debugElement.children[1].injector.get(StaticContentQueryComp);
// static ContentChild query should be set in creation mode, before CD runs
expect(firstComponent.textDir).toBeInstanceOf(TextDirective);
expect(secondComponent.textDir).toBeInstanceOf(TextDirective);
expect(firstComponent.textDir.text).toEqual('');
expect(secondComponent.textDir.text).toEqual('');
expect(firstComponent.setEvents).toEqual(['textDir set']);
expect(secondComponent.setEvents).toEqual(['textDir set']);
// dynamic ContentChild query should not have been resolved yet
expect(firstComponent.foo).not.toBeDefined();
expect(secondComponent.foo).not.toBeDefined();
const spans = fixture.nativeElement.querySelectorAll('span');
(fixture.componentInstance as any).text = 'some text';
fixture.detectChanges();
expect(firstComponent.textDir.text).toEqual('some text');
expect(secondComponent.textDir.text).toEqual('some text');
expect(firstComponent.foo.nativeElement).toBe(spans[0]);
expect(secondComponent.foo.nativeElement).toBe(spans[1]);
expect(firstComponent.setEvents).toEqual(['textDir set', 'foo set']);
expect(secondComponent.setEvents).toEqual(['textDir set', 'foo set']);
});
it('should support ContentChild query inherited from undecorated superclasses', () => {
class MyComp {
@ContentChild('foo') foo: any;
}
@Component({
selector: 'sub-comp',
template: '<ng-content></ng-content>',
standalone: false,
})
class SubComp extends MyComp {}
@Component({
template: '<sub-comp><div #foo></div></sub-comp>',
standalone: false,
})
class App {
@ViewChild(SubComp) subComp!: SubComp;
}
TestBed.configureTestingModule({declarations: [App, SubComp]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.subComp.foo).toBeInstanceOf(ElementRef);
});
it('should support ContentChild query inherited from undecorated grand superclasses', () => {
class MySuperComp {
@ContentChild('foo') foo: any;
}
class MyComp extends MySuperComp {}
@Component({
selector: 'sub-comp',
template: '<ng-content></ng-content>',
standalone: false,
})
class SubComp extends MyComp {}
@Component({
template: '<sub-comp><div #foo></div></sub-comp>',
standalone: false,
})
class App {
@ViewChild(SubComp) subComp!: SubComp;
}
TestBed.configureTestingModule({declarations: [App, SubComp]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.subComp.foo).toBeInstanceOf(ElementRef);
});
it('should support ContentChildren query inherited from undecorated superclasses', () => {
@Directive({
selector: '[some-dir]',
standalone: false,
})
class SomeDir {}
class MyComp {
@ContentChildren(SomeDir) foo!: QueryList<SomeDir>;
}
@Component({
selector: 'sub-comp',
template: '<ng-content></ng-content>',
standalone: false,
})
class SubComp extends MyComp {}
@Component({
template: `
<sub-comp>
<div some-dir></div>
<div some-dir></div>
</sub-comp>
`,
standalone: false,
})
class App {
@ViewChild(SubComp) subComp!: SubComp;
}
TestBed.configureTestingModule({declarations: [App, SubComp, SomeDir]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.subComp.foo).toBeInstanceOf(QueryList);
expect(fixture.componentInstance.subComp.foo.length).toBe(2);
});
it('should support ContentChildren query inherited from undecorated grand superclasses', () => {
@Directive({
selector: '[some-dir]',
standalone: false,
})
class SomeDir {}
class MySuperComp {
@ContentChildren(SomeDir) foo!: QueryList<SomeDir>;
}
class MyComp extends MySuperComp {}
@Component({
selector: 'sub-comp',
template: '<ng-content></ng-content>',
standalone: false,
})
class SubComp extends MyComp {}
@Component({
template: `
<sub-comp>
<div some-dir></div>
<div some-dir></div>
</sub-comp>
`,
standalone: false,
})
class App {
@ViewChild(SubComp) subComp!: SubComp;
}
TestBed.configureTestingModule({declarations: [App, SubComp, SomeDir]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.subComp.foo).toBeInstanceOf(QueryList);
expect(fixture.componentInstance.subComp.foo.length).toBe(2);
});
it('should match shallow content queries in views inserted / removed by ngIf', () => {
@Component({
selector: 'test-comp',
template: `
<shallow-comp>
<div *ngIf="showing" #foo></div>
</shallow-comp>
`,
standalone: false,
})
class TestComponent {
showing = false;
}
@Component({
selector: 'shallow-comp',
template: '',
standalone: false,
})
class ShallowComp {
@ContentChildren('foo', {descendants: false}) foos!: QueryList<ElementRef>;
}
TestBed.configureTestingModule({
declarations: [TestComponent, ShallowComp],
imports: [CommonModule],
});
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const shallowComp = fixture.debugElement.query(By.directive(ShallowComp)).componentInstance;
const queryList = shallowComp!.foos;
expect(queryList.length).toBe(0);
fixture.componentInstance.showing = true;
fixture.detectChanges();
expect(queryList.length).toBe(1);
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(queryList.length).toBe(0);
});
it('should support content queries for directives within repeated embedded views', () => {
const withContentInstances: DirWithContentQuery[] = [];
@Directive({
selector: '[with-content]',
standalone: false,
})
class DirWithContentQuery {
constructor() {
withContentInstances.push(this);
}
@ContentChildren('foo', {descendants: false}) foos!: QueryList<ElementRef>;
contentInitQuerySnapshot = 0;
contentCheckedQuerySnapshot = 0;
ngAfterContentInit() {
this.contentInitQuerySnapshot = this.foos ? this.foos.length : 0;
}
ngAfterContentChecked() {
this.contentCheckedQuerySnapshot = this.foos ? this.foos.length : 0;
}
}
@Component({
selector: 'comp',
template: `
<ng-container *ngFor="let item of items">
<div with-content>
<span #foo></span>
</div>
</ng-container>
`,
standalone: false,
})
class Root {
items = [1, 2, 3];
}
TestBed.configureTestingModule({
declarations: [Root, DirWithContentQuery],
imports: [CommonModule],
});
const fixture = TestBed.createComponent(Root);
fixture.detectChanges();
for (let i = 0; i < 3; i++) {
expect(withContentInstances[i].foos.length).toBe(
1,
`Expected content query to match <span #foo>.`,
);
expect(withContentInstances[i].contentInitQuerySnapshot).toBe(
1,
`Expected content query results to be available when ngAfterContentInit was called.`,
);
expect(withContentInstances[i].contentCheckedQuerySnapshot).toBe(
1,
`Expected content query results to be available when ngAfterContentChecked was called.`,
);
}
}); | {
"end_byte": 31200,
"start_byte": 22302,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/query_spec.ts"
} |
angular/packages/core/test/acceptance/query_spec.ts_31206_40110 | it('should not match directive host with content queries', () => {
@Directive({
selector: '[content-query]',
standalone: true,
})
class ContentQueryDirective {
@ContentChildren('foo', {descendants: true}) foos!: QueryList<ElementRef>;
}
@Component({
standalone: true,
imports: [ContentQueryDirective],
template: `<div content-query #foo></div>`,
})
class TestCmp {
@ViewChild(ContentQueryDirective, {static: true})
contentQueryDirective!: ContentQueryDirective;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.contentQueryDirective.foos;
expect(qList.length).toBe(0);
});
it('should report results to appropriate queries where deep content queries are nested', () => {
@Directive({selector: '[content-query]', standalone: true, exportAs: 'query'})
class ContentQueryDirective {
@ContentChildren('foo, bar, baz', {descendants: true}) qlist!: QueryList<ElementRef>;
}
@Component({
standalone: true,
imports: [ContentQueryDirective],
template: `
<div content-query #out="query">
<span #foo></span>
<div content-query #in="query">
<span #bar></span>
</div>
<span #baz></span>
</div>
`,
})
class TestCmp {
@ViewChild('in', {static: true}) in!: ContentQueryDirective;
@ViewChild('out', {static: true}) out!: ContentQueryDirective;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const inQList = fixture.componentInstance.in.qlist;
expect(inQList.length).toBe(1);
const outQList = fixture.componentInstance.out.qlist;
expect(outQList.length).toBe(3);
});
it('should support nested shallow content queries', () => {
@Directive({selector: '[content-query]', standalone: true, exportAs: 'query'})
class ContentQueryDirective {
@ContentChildren('foo') qlist!: QueryList<ElementRef>;
}
@Component({
standalone: true,
imports: [ContentQueryDirective],
template: `
<div content-query #out="query">
<div content-query #in="query" #foo>
<span #foo></span>
</div>
</div>
`,
})
class TestCmp {
@ViewChild('in', {static: true}) in!: ContentQueryDirective;
@ViewChild('out', {static: true}) out!: ContentQueryDirective;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const inQList = fixture.componentInstance.in.qlist;
expect(inQList.length).toBe(1);
const outQList = fixture.componentInstance.out.qlist;
expect(outQList.length).toBe(1);
});
it('should respect shallow flag on content queries when mixing deep and shallow queries', () => {
@Directive({selector: '[shallow-content-query]', standalone: true, exportAs: 'shallow-query'})
class ShallowContentQueryDirective {
@ContentChildren('foo') qlist!: QueryList<ElementRef>;
}
@Directive({selector: '[deep-content-query]', standalone: true, exportAs: 'deep-query'})
class DeepContentQueryDirective {
@ContentChildren('foo', {descendants: true}) qlist!: QueryList<ElementRef>;
}
@Component({
standalone: true,
imports: [ShallowContentQueryDirective, DeepContentQueryDirective],
template: `
<div shallow-content-query #shallow="shallow-query" deep-content-query #deep="deep-query">
<span #foo></span>
<div>
<span #foo></span>
</div>
</div>
`,
})
class TestCmp {
@ViewChild('shallow', {static: true}) shallow!: ShallowContentQueryDirective;
@ViewChild('deep', {static: true}) deep!: DeepContentQueryDirective;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const inQList = fixture.componentInstance.shallow.qlist;
expect(inQList.length).toBe(1);
const outQList = fixture.componentInstance.deep.qlist;
expect(outQList.length).toBe(2);
});
it('should support shallow ContentChild queries', () => {
@Directive({selector: '[query-dir]', standalone: true})
class ContentQueryDirective {
@ContentChild('foo', {descendants: false}) shallow: ElementRef | undefined;
// ContentChild queries have {descendants: true} option by default
@ContentChild('foo') deep: ElementRef | undefined;
}
@Component({
standalone: true,
imports: [ContentQueryDirective],
template: `
<div query-dir>
<div>
<span #foo></span>
</div>
</div>
`,
})
class TestCmp {
@ViewChild(ContentQueryDirective, {static: true}) queryDir!: ContentQueryDirective;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.componentInstance.queryDir.shallow).toBeUndefined();
expect(fixture.componentInstance.queryDir.deep).toBeInstanceOf(ElementRef);
});
it('should support view and content queries matching the same element', () => {
@Directive({
selector: '[content-query]',
standalone: true,
})
class ContentQueryDirective {
@ContentChildren('foo') foos!: QueryList<ElementRef>;
}
@Component({
standalone: true,
imports: [ContentQueryDirective],
template: `
<div content-query>
<div id="contentAndView" #foo></div>
</div>
<div id="contentOnly" #bar></div>
`,
})
class TestCmp {
@ViewChild(ContentQueryDirective, {static: true}) contentQueryDir!: ContentQueryDirective;
@ViewChildren('foo, bar') fooBars!: QueryList<ElementRef>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const contentQList = fixture.componentInstance.contentQueryDir.foos;
expect(contentQList.length).toBe(1);
expect(contentQList.first.nativeElement.getAttribute('id')).toBe('contentAndView');
const viewQList = fixture.componentInstance.fooBars;
expect(viewQList.length).toBe(2);
expect(viewQList.first.nativeElement.getAttribute('id')).toBe('contentAndView');
expect(viewQList.last.nativeElement.getAttribute('id')).toBe('contentOnly');
});
});
describe('query order', () => {
@Directive({selector: '[text]', standalone: true})
class TextDirective {
@Input() text: string | undefined;
}
it('should register view query matches from top to bottom', () => {
@Component({
standalone: true,
imports: [TextDirective],
template: `
<span text="A"></span>
<div text="B">
<span text="C">
<span text="D"></span>
</span>
</div>
<span text="E"></span>`,
})
class TestCmp {
@ViewChildren(TextDirective) texts!: QueryList<TextDirective>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.componentInstance.texts.map((item) => item.text)).toEqual([
'A',
'B',
'C',
'D',
'E',
]);
});
it('should register content query matches from top to bottom', () => {
@Directive({
selector: '[content-query]',
standalone: true,
})
class ContentQueryDirective {
@ContentChildren(TextDirective, {descendants: true}) texts!: QueryList<TextDirective>;
}
@Component({
standalone: true,
imports: [TextDirective, ContentQueryDirective],
template: `
<div content-query>
<span text="A"></span>
<div text="B">
<span text="C">
<span text="D"></span>
</span>
</div>
<span text="E"></span>
</div>`,
})
class TestCmp {
@ViewChild(ContentQueryDirective, {static: true})
contentQueryDirective!: ContentQueryDirective;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(
fixture.componentInstance.contentQueryDirective.texts.map((item) => item.text),
).toEqual(['A', 'B', 'C', 'D', 'E']);
});
});
// Some root components may have ContentChildren queries if they are also
// usable as a child component. We should still generate an empty QueryList
// for these queries when they are at root for backwards compatibility with
// ViewEngine. | {
"end_byte": 40110,
"start_byte": 31206,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/query_spec.ts"
} |
angular/packages/core/test/acceptance/query_spec.ts_40113_40423 | it('should generate an empty QueryList for root components', () => {
const fixture = TestBed.createComponent(QueryComp);
fixture.detectChanges();
expect(fixture.componentInstance.contentChildren).toBeInstanceOf(QueryList);
expect(fixture.componentInstance.contentChildren.length).toBe(0);
}); | {
"end_byte": 40423,
"start_byte": 40113,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/query_spec.ts"
} |
angular/packages/core/test/acceptance/query_spec.ts_40427_49862 | describe('descendants: false (default)', () => {
/**
* A helper function to check if a given object looks like ElementRef. It is used in place of
* the `instanceof ElementRef` check since ivy returns a type that looks like ElementRef (have
* the same properties but doesn't pass the instanceof ElementRef test)
*/
function isElementRefLike(result: any): boolean {
return result.nativeElement != null;
}
it('should match directives on elements that used to be wrapped by a required parent in HTML parser', () => {
@Directive({
selector: '[myDef]',
standalone: false,
})
class MyDef {}
@Component({
selector: 'my-container',
template: ``,
standalone: false,
})
class MyContainer {
@ContentChildren(MyDef) myDefs!: QueryList<MyDef>;
}
@Component({
selector: 'test-cmpt',
template: `<my-container><tr myDef></tr></my-container>`,
standalone: false,
})
class TestCmpt {}
TestBed.configureTestingModule({declarations: [TestCmpt, MyContainer, MyDef]});
const fixture = TestBed.createComponent(TestCmpt);
const cmptWithQuery = fixture.debugElement.children[0].injector.get(MyContainer);
fixture.detectChanges();
expect(cmptWithQuery.myDefs.length).toBe(1);
});
it('should match elements with local refs inside <ng-container>', () => {
@Component({
selector: 'needs-target',
template: ``,
standalone: false,
})
class NeedsTarget {
@ContentChildren('target') targets!: QueryList<ElementRef>;
}
@Component({
selector: 'test-cmpt',
template: `
<needs-target>
<ng-container>
<tr #target></tr>
</ng-container>
</needs-target>
`,
standalone: false,
})
class TestCmpt {}
TestBed.configureTestingModule({declarations: [TestCmpt, NeedsTarget]});
const fixture = TestBed.createComponent(TestCmpt);
const cmptWithQuery = fixture.debugElement.children[0].injector.get(NeedsTarget);
fixture.detectChanges();
expect(cmptWithQuery.targets.length).toBe(1);
expect(isElementRefLike(cmptWithQuery.targets.first)).toBeTruthy();
});
it('should match elements with local refs inside nested <ng-container>', () => {
@Component({
selector: 'needs-target',
template: ``,
standalone: false,
})
class NeedsTarget {
@ContentChildren('target') targets!: QueryList<ElementRef>;
}
@Component({
selector: 'test-cmpt',
template: `
<needs-target>
<ng-container>
<ng-container>
<ng-container>
<tr #target></tr>
</ng-container>
</ng-container>
</ng-container>
</needs-target>
`,
standalone: false,
})
class TestCmpt {}
TestBed.configureTestingModule({declarations: [TestCmpt, NeedsTarget]});
const fixture = TestBed.createComponent(TestCmpt);
const cmptWithQuery = fixture.debugElement.children[0].injector.get(NeedsTarget);
fixture.detectChanges();
expect(cmptWithQuery.targets.length).toBe(1);
expect(isElementRefLike(cmptWithQuery.targets.first)).toBeTruthy();
});
it('should match directives inside <ng-container>', () => {
@Directive({
selector: '[targetDir]',
standalone: false,
})
class TargetDir {}
@Component({
selector: 'needs-target',
template: ``,
standalone: false,
})
class NeedsTarget {
@ContentChildren(TargetDir) targets!: QueryList<HTMLElement>;
}
@Component({
selector: 'test-cmpt',
template: `
<needs-target>
<ng-container>
<tr targetDir></tr>
</ng-container>
</needs-target>
`,
standalone: false,
})
class TestCmpt {}
TestBed.configureTestingModule({declarations: [TestCmpt, NeedsTarget, TargetDir]});
const fixture = TestBed.createComponent(TestCmpt);
const cmptWithQuery = fixture.debugElement.children[0].injector.get(NeedsTarget);
fixture.detectChanges();
expect(cmptWithQuery.targets.length).toBe(1);
expect(cmptWithQuery.targets.first).toBeInstanceOf(TargetDir);
});
it('should match directives inside nested <ng-container>', () => {
@Directive({
selector: '[targetDir]',
standalone: false,
})
class TargetDir {}
@Component({
selector: 'needs-target',
template: ``,
standalone: false,
})
class NeedsTarget {
@ContentChildren(TargetDir) targets!: QueryList<HTMLElement>;
}
@Component({
selector: 'test-cmpt',
template: `
<needs-target>
<ng-container>
<ng-container>
<ng-container>
<tr targetDir></tr>
</ng-container>
</ng-container>
</ng-container>
</needs-target>
`,
standalone: false,
})
class TestCmpt {}
TestBed.configureTestingModule({declarations: [TestCmpt, NeedsTarget, TargetDir]});
const fixture = TestBed.createComponent(TestCmpt);
const cmptWithQuery = fixture.debugElement.children[0].injector.get(NeedsTarget);
fixture.detectChanges();
expect(cmptWithQuery.targets.length).toBe(1);
expect(cmptWithQuery.targets.first).toBeInstanceOf(TargetDir);
});
it('should cross child ng-container when query is declared on ng-container', () => {
@Directive({
selector: '[targetDir]',
standalone: false,
})
class TargetDir {}
@Directive({
selector: '[needs-target]',
standalone: false,
})
class NeedsTarget {
@ContentChildren(TargetDir) targets!: QueryList<HTMLElement>;
}
@Component({
selector: 'test-cmpt',
template: `
<ng-container targetDir>
<ng-container needs-target>
<ng-container>
<tr targetDir></tr>
</ng-container>
</ng-container>
</ng-container>
`,
standalone: false,
})
class TestCmpt {}
TestBed.configureTestingModule({declarations: [TestCmpt, NeedsTarget, TargetDir]});
const fixture = TestBed.createComponent(TestCmpt);
const cmptWithQuery = fixture.debugElement.children[0].injector.get(NeedsTarget);
fixture.detectChanges();
expect(cmptWithQuery.targets.length).toBe(1);
expect(cmptWithQuery.targets.first).toBeInstanceOf(TargetDir);
});
it('should match nodes when using structural directives (*syntax) on <ng-container>', () => {
@Directive({
selector: '[targetDir]',
standalone: false,
})
class TargetDir {}
@Component({
selector: 'needs-target',
template: ``,
standalone: false,
})
class NeedsTarget {
@ContentChildren(TargetDir) dirTargets!: QueryList<TargetDir>;
@ContentChildren('target') localRefsTargets!: QueryList<ElementRef>;
}
@Component({
selector: 'test-cmpt',
template: `
<needs-target>
<ng-container *ngIf="true">
<div targetDir></div>
<div #target></div>
</ng-container>
</needs-target>
`,
standalone: false,
})
class TestCmpt {}
TestBed.configureTestingModule({declarations: [TestCmpt, NeedsTarget, TargetDir]});
const fixture = TestBed.createComponent(TestCmpt);
const cmptWithQuery = fixture.debugElement.children[0].injector.get(NeedsTarget);
fixture.detectChanges();
expect(cmptWithQuery.dirTargets.length).toBe(1);
expect(cmptWithQuery.dirTargets.first).toBeInstanceOf(TargetDir);
expect(cmptWithQuery.localRefsTargets.length).toBe(1);
expect(isElementRefLike(cmptWithQuery.localRefsTargets.first)).toBeTruthy();
});
it('should match directives on <ng-container> when crossing nested <ng-container>', () => {
@Directive({
selector: '[targetDir]',
standalone: false,
})
class TargetDir {}
@Component({
selector: 'needs-target',
template: ``,
standalone: false,
})
class NeedsTarget {
@ContentChildren(TargetDir) targets!: QueryList<HTMLElement>;
}
@Component({
selector: 'test-cmpt',
template: `
<needs-target>
<ng-container>
<ng-container targetDir>
<ng-container targetDir>
<tr targetDir></tr>
</ng-container>
</ng-container>
</ng-container>
</needs-target>
`,
standalone: false,
})
class TestCmpt {}
TestBed.configureTestingModule({declarations: [TestCmpt, NeedsTarget, TargetDir]});
const fixture = TestBed.createComponent(TestCmpt);
const cmptWithQuery = fixture.debugElement.children[0].injector.get(NeedsTarget);
fixture.detectChanges();
expect(cmptWithQuery.targets.length).toBe(3);
});
}); | {
"end_byte": 49862,
"start_byte": 40427,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/query_spec.ts"
} |
angular/packages/core/test/acceptance/query_spec.ts_49866_59034 | describe('read option', () => {
@Directive({selector: '[child]', standalone: true})
class Child {}
@Directive({selector: '[otherChild]', standalone: true})
class OtherChild {}
it('should query using type predicate and read ElementRef', () => {
@Component({
standalone: true,
imports: [Child],
template: `<div child></div>`,
})
class TestCmp {
@ViewChildren(Child, {read: ElementRef}) query?: QueryList<ElementRef>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
const elToQuery = fixture.nativeElement.querySelector('div');
expect(qList.length).toBe(1);
expect(qList.first.nativeElement).toBe(elToQuery);
});
it('should query using type predicate and read another directive type', () => {
@Component({
standalone: true,
imports: [Child, OtherChild],
template: `<div child otherChild></div>`,
})
class TestCmp {
@ViewChildren(Child, {read: OtherChild}) query?: QueryList<OtherChild>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(1);
expect(qList.first).toBeInstanceOf(OtherChild);
});
it('should not add results to query if a requested token cant be read', () => {
@Component({
standalone: true,
imports: [Child],
template: `<div child></div>`,
})
class TestCmp {
@ViewChildren(Child, {read: OtherChild}) query?: QueryList<OtherChild>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(0);
});
it('should query using local ref and read ElementRef by default', () => {
@Component({
standalone: true,
template: `
<div #foo></div>
<div></div>
`,
})
class TestCmp {
@ViewChildren('foo') query?: QueryList<ElementRef>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
const elToQuery = fixture.nativeElement.querySelector('div');
expect(qList.length).toBe(1);
expect(qList.first.nativeElement).toBe(elToQuery);
});
it('should query for multiple elements and read ElementRef by default', () => {
@Component({
standalone: true,
template: `
<div #foo></div>
<div></div>
<div #bar></div>
`,
})
class TestCmp {
@ViewChildren('foo,bar') query?: QueryList<ElementRef>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
const elToQuery = fixture.nativeElement.querySelectorAll('div');
expect(qList.length).toBe(2);
expect(qList.first.nativeElement).toBe(elToQuery[0]);
expect(qList.last.nativeElement).toBe(elToQuery[2]);
});
it('should read ElementRef from an element when explicitly asked for', () => {
@Component({
standalone: true,
template: `
<div #foo></div>
<div></div>
`,
})
class TestCmp {
@ViewChildren('foo', {read: ElementRef}) query?: QueryList<ElementRef>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
const elToQuery = fixture.nativeElement.querySelector('div');
expect(qList.length).toBe(1);
expect(qList.first.nativeElement).toBe(elToQuery);
});
it('should query for <ng-container> and read ElementRef with a native element pointing to comment node', () => {
@Component({
standalone: true,
template: `<ng-container #foo></ng-container>`,
})
class TestCmp {
@ViewChildren('foo', {read: ElementRef}) query?: QueryList<ElementRef>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(1);
expect(qList.first.nativeElement.nodeType).toBe(Node.COMMENT_NODE);
});
it('should query for <ng-container> and read ElementRef without explicit read option', () => {
@Component({
standalone: true,
template: `<ng-container #foo></ng-container>`,
})
class TestCmp {
@ViewChildren('foo') query?: QueryList<ElementRef>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(1);
expect(qList.first.nativeElement.nodeType).toBe(Node.COMMENT_NODE);
});
it('should read ViewContainerRef from element nodes when explicitly asked for', () => {
@Component({
standalone: true,
template: `<div #foo></div>`,
})
class TestCmp {
@ViewChildren('foo', {read: ViewContainerRef}) query?: QueryList<ViewContainerRef>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(1);
expect(qList.first).toBeInstanceOf(ViewContainerRef);
});
it('should read ViewContainerRef from ng-template nodes when explicitly asked for', () => {
@Component({
standalone: true,
template: `<ng-template #foo></ng-template>`,
})
class TestCmp {
@ViewChildren('foo', {read: ViewContainerRef}) query?: QueryList<ViewContainerRef>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(1);
expect(qList.first).toBeInstanceOf(ViewContainerRef);
});
it('should read ElementRef with a native element pointing to comment DOM node from ng-template', () => {
@Component({
standalone: true,
template: `<ng-template #foo></ng-template>`,
})
class TestCmp {
@ViewChildren('foo', {read: ElementRef}) query?: QueryList<ElementRef>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(1);
expect(qList.first.nativeElement.nodeType).toBe(Node.COMMENT_NODE);
});
it('should read TemplateRef from ng-template by default', () => {
@Component({
standalone: true,
template: `<ng-template #foo></ng-template>`,
})
class TestCmp {
@ViewChildren('foo') query?: QueryList<TemplateRef<unknown>>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(1);
expect(qList.first).toBeInstanceOf(TemplateRef);
});
it('should read TemplateRef from ng-template when explicitly asked for', () => {
@Component({
standalone: true,
template: `<ng-template #foo></ng-template>`,
})
class TestCmp {
@ViewChildren('foo', {read: TemplateRef}) query?: QueryList<TemplateRef<unknown>>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(1);
expect(qList.first).toBeInstanceOf(TemplateRef);
});
it('should read component instance if element queried for is a component host', () => {
@Component({selector: 'child-cmp', standalone: true, template: ''})
class ChildCmp {}
@Component({
standalone: true,
imports: [ChildCmp],
template: `<child-cmp #foo></child-cmp>`,
})
class TestCmp {
@ViewChildren('foo') query?: QueryList<ChildCmp>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(1);
expect(qList.first).toBeInstanceOf(ChildCmp);
});
it('should read component instance with explicit exportAs', () => {
@Component({
selector: 'child-cmp',
exportAs: 'child',
standalone: true,
template: '',
})
class ChildCmp {}
@Component({
standalone: true,
imports: [ChildCmp],
template: `<child-cmp #foo="child"></child-cmp>`,
})
class TestCmp {
@ViewChildren('foo') query?: QueryList<ChildCmp>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(1);
expect(qList.first).toBeInstanceOf(ChildCmp);
}); | {
"end_byte": 59034,
"start_byte": 49866,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/query_spec.ts"
} |
angular/packages/core/test/acceptance/query_spec.ts_59040_67440 | it('should read directive instance if element queried for has an exported directive with a matching name', () => {
@Directive({selector: '[child]', exportAs: 'child', standalone: true})
class ChildDirective {}
@Component({
standalone: true,
imports: [ChildDirective],
template: `<div #foo="child" child></div>`,
})
class TestCmp {
@ViewChildren('foo') query?: QueryList<ChildDirective>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(1);
expect(qList.first).toBeInstanceOf(ChildDirective);
});
it('should read all matching directive instances from a given element', () => {
@Directive({selector: '[child1]', exportAs: 'child1', standalone: true})
class Child1Dir {}
@Directive({selector: '[child2]', exportAs: 'child2', standalone: true})
class Child2Dir {}
@Component({
standalone: true,
imports: [Child1Dir, Child2Dir],
template: `<div #foo="child1" child1 #bar="child2" child2></div>`,
})
class TestCmp {
@ViewChildren('foo, bar') query?: QueryList<unknown>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(2);
expect(qList.first).toBeInstanceOf(Child1Dir);
expect(qList.last).toBeInstanceOf(Child2Dir);
});
it('should read multiple locals exporting the same directive from a given element', () => {
@Directive({selector: '[child]', exportAs: 'child', standalone: true})
class ChildDir {}
@Component({
standalone: true,
imports: [ChildDir],
template: `<div child #foo="child" #bar="child"></div>`,
})
class TestCmp {
@ViewChildren('foo, bar') query?: QueryList<ChildDir>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(2);
expect(qList.first).toBeInstanceOf(ChildDir);
expect(qList.last).toBeInstanceOf(ChildDir);
});
it('should query multiple locals on the same element', () => {
@Component({
selector: 'multiple-local-refs',
template: `
<div #foo #bar id="target"></div>
<div></div>
`,
standalone: false,
})
class MultipleLocalRefsComp {
@ViewChildren('foo') fooQuery!: QueryList<any>;
@ViewChildren('bar') barQuery!: QueryList<any>;
}
const fixture = TestBed.createComponent(MultipleLocalRefsComp);
fixture.detectChanges();
const cmptInstance = fixture.componentInstance;
const targetElement = fixture.nativeElement.querySelector('#target');
const fooList = cmptInstance.fooQuery;
expect(fooList.length).toBe(1);
expect(fooList.first.nativeElement).toEqual(targetElement);
const barList = cmptInstance.barQuery;
expect(barList.length).toBe(1);
expect(barList.first.nativeElement).toEqual(targetElement);
});
it('should match on exported directive name and read a requested token', () => {
@Directive({selector: '[child]', exportAs: 'child', standalone: true})
class ChildDir {}
@Component({
standalone: true,
imports: [ChildDir],
template: `<div child #foo="child"></div>`,
})
class TestCmp {
@ViewChildren('foo', {read: ElementRef}) query?: QueryList<ElementRef>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(1);
expect(qList.first).toBeInstanceOf(ElementRef);
});
it('should support reading a mix of ElementRef and directive instances', () => {
@Directive({selector: '[child]', exportAs: 'child', standalone: true})
class ChildDir {}
@Component({
standalone: true,
imports: [ChildDir],
template: `<div #foo #bar="child" child></div>`,
})
class TestCmp {
@ViewChildren('foo, bar') query?: QueryList<unknown>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(2);
expect(qList.first).toBeInstanceOf(ElementRef);
expect(qList.last).toBeInstanceOf(ChildDir);
});
it('should not add results to selector-based query if a requested token cant be read', () => {
@Directive({selector: '[child]', standalone: true})
class ChildDir {}
@Component({
standalone: true,
imports: [],
template: `<div #foo></div>`,
})
class TestCmp {
@ViewChildren('foo', {read: ChildDir}) query?: QueryList<ChildDir>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(0);
});
it('should not add results to directive-based query if only read token matches', () => {
@Directive({selector: '[child]', standalone: true})
class ChildDir {}
@Directive({selector: '[otherChild]', standalone: true})
class OtherChildDir {}
@Component({
standalone: true,
imports: [Child],
template: `<div child></div>`,
})
class TestCmp {
@ViewChildren(OtherChild, {read: Child}) query?: QueryList<ChildDir>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(0);
});
it('should not add results to TemplateRef-based query if only read token matches', () => {
@Component({
standalone: true,
template: `<div></div>`,
})
class TestCmp {
@ViewChildren(TemplateRef, {read: ElementRef}) query?: QueryList<ElementRef>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(0);
});
it('should not add results to the query in case no match found (via TemplateRef)', () => {
@Component({
standalone: true,
template: `<div></div>`,
})
class TestCmp {
@ViewChildren(TemplateRef) query?: QueryList<TemplateRef<unknown>>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(0);
});
it('should query templates if the type is TemplateRef (and respect "read" option)', () => {
@Component({
standalone: true,
template: `
<ng-template #foo><div>Test</div></ng-template>
<ng-template #bar><div>Test</div></ng-template>
<ng-template #baz><div>Test</div></ng-template>
`,
})
class TestCmp {
@ViewChildren(TemplateRef) tplQuery?: QueryList<TemplateRef<unknown>>;
@ViewChildren(TemplateRef, {read: ElementRef}) elRefQuery?: QueryList<TemplateRef<unknown>>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const tplQuery = fixture.componentInstance.tplQuery!;
const elRefQuery = fixture.componentInstance.elRefQuery!;
expect(tplQuery.length).toBe(3);
expect(tplQuery.first).toBeInstanceOf(TemplateRef);
expect(elRefQuery.length).toBe(3);
expect(elRefQuery.first).toBeInstanceOf(ElementRef);
});
it('should match using string selector and directive as a read argument', () => {
@Component({
standalone: true,
imports: [Child],
template: `<div child #foo></div>`,
})
class TestCmp {
@ViewChildren('foo', {read: Child}) query?: QueryList<Child>;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const qList = fixture.componentInstance.query!;
expect(qList.length).toBe(1);
expect(qList.first).toBeInstanceOf(Child);
});
}); | {
"end_byte": 67440,
"start_byte": 59040,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/query_spec.ts"
} |
angular/packages/core/test/acceptance/query_spec.ts_67444_70096 | describe('observable interface', () => {
it('should allow observing changes to query list', () => {
const fixture = TestBed.createComponent(QueryCompWithChanges);
let changes = 0;
fixture.detectChanges();
fixture.componentInstance.foos.changes.subscribe((value: any) => {
changes += 1;
expect(value).toBe(fixture.componentInstance.foos);
});
// refresh without setting dirty - no emit
fixture.detectChanges();
expect(changes).toBe(0);
// refresh with setting dirty - emit
fixture.componentInstance.showing = true;
fixture.detectChanges();
expect(changes).toBe(1);
});
it('should only fire if the content of the query changes', () => {
// When views are inserted/removed the content query need to be recomputed.
// Recomputing the query may result in no changes to the query (the item added/removed was
// not part of the query). This tests asserts that the query does not fire when no changes
// occur.
TestBed.configureTestingModule({
declarations: [QueryCompWithStrictChangeEmitParent, QueryCompWithNoChanges],
});
const fixture = TestBed.createComponent(QueryCompWithNoChanges);
let changesStrict = 0;
const componentInstance = fixture.componentInstance.queryComp;
fixture.detectChanges();
componentInstance.foos.changes.subscribe((value: any) => {
// subscribe to the changes and record when changes occur.
changesStrict += 1;
});
// First verify that the subscription is working.
fixture.componentInstance.innerShowing = false;
fixture.detectChanges();
expect(changesStrict).toBe(1); // We detected a change
expect(componentInstance.foos.toArray().length).toEqual(1);
// now verify that removing a view does not needlessly fire subscription
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(changesStrict).toBe(1); // We detected a change
expect(componentInstance.foos.toArray().length).toEqual(1);
// now verify that adding a view does not needlessly fire subscription
fixture.componentInstance.showing = true;
fixture.detectChanges();
expect(changesStrict).toBe(1); // We detected a change
// Note: even though the `showing` is `true` and the second `<div>` is displayed, the
// child element of that <div> is hidden because the `innerShowing` flag is still `false`,
// so we expect only one element to be present in the `foos` array.
expect(componentInstance.foos.toArray().length).toEqual(1);
});
}); | {
"end_byte": 70096,
"start_byte": 67444,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/query_spec.ts"
} |
angular/packages/core/test/acceptance/query_spec.ts_70100_77208 | describe('view boundaries', () => {
describe('ViewContainerRef', () => {
@Directive({
selector: '[vc]',
exportAs: 'vc',
standalone: false,
})
class ViewContainerManipulatorDirective {
constructor(private _vcRef: ViewContainerRef) {}
insertTpl(tpl: TemplateRef<{}>, ctx: {}, idx?: number): ViewRef {
return this._vcRef.createEmbeddedView(tpl, ctx, idx);
}
remove(index?: number) {
this._vcRef.remove(index);
}
move(viewRef: ViewRef, index: number) {
this._vcRef.move(viewRef, index);
}
}
it('should report results in views inserted / removed by ngIf', () => {
@Component({
selector: 'test-comp',
template: `
<ng-template [ngIf]="value">
<div #foo></div>
</ng-template>
`,
standalone: false,
})
class TestComponent {
value: boolean = false;
@ViewChildren('foo') query!: QueryList<any>;
}
TestBed.configureTestingModule({declarations: [TestComponent]});
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const queryList = fixture.componentInstance.query;
expect(queryList.length).toBe(0);
fixture.componentInstance.value = true;
fixture.detectChanges();
expect(queryList.length).toBe(1);
fixture.componentInstance.value = false;
fixture.detectChanges();
expect(queryList.length).toBe(0);
});
it('should report results in views inserted / removed by ngFor', () => {
@Component({
selector: 'test-comp',
template: `
<ng-template ngFor let-item [ngForOf]="value">
<div #foo [id]="item"></div>
</ng-template>
`,
standalone: false,
})
class TestComponent {
value: string[] | undefined;
@ViewChildren('foo') query!: QueryList<any>;
}
TestBed.configureTestingModule({declarations: [TestComponent]});
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const queryList = fixture.componentInstance.query;
expect(queryList.length).toBe(0);
fixture.componentInstance.value = ['a', 'b', 'c'];
fixture.detectChanges();
expect(queryList.length).toBe(3);
// Remove the "b" element from the value.
fixture.componentInstance.value.splice(1, 1);
fixture.detectChanges();
expect(queryList.length).toBe(2);
// make sure that the "b" element has been removed from query results
expect(queryList.first.nativeElement.id).toBe('a');
expect(queryList.last.nativeElement.id).toBe('c');
});
/**
* ViewContainerRef API allows "moving" a view to the same (previous) index. Such operation
* has no observable effect on the rendered UI (displays stays the same) but internally we've
* got 2 implementation choices when it comes to "moving" a view:
* - systematically detach and insert a view - this would result in unnecessary processing
* when the previous and new indexes for the move operation are the same;
* - detect the situation where the indexes are the same and do no processing in such case.
*/
it('should NOT notify on changes when a given view is removed and re-inserted at the same index', () => {
@Component({
selector: 'test-comp',
template: `
<ng-template #tpl><div #foo>match</div></ng-template>
<ng-template vc></ng-template>
`,
standalone: false,
})
class TestComponent implements AfterViewInit {
queryListNotificationCounter = 0;
@ViewChild(ViewContainerManipulatorDirective) vc!: ViewContainerManipulatorDirective;
@ViewChild('tpl') tpl!: TemplateRef<any>;
@ViewChildren('foo') query!: QueryList<any>;
ngAfterViewInit() {
this.query.changes.subscribe(() => this.queryListNotificationCounter++);
}
}
TestBed.configureTestingModule({
declarations: [ViewContainerManipulatorDirective, TestComponent],
});
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const queryList = fixture.componentInstance.query;
const {tpl, vc} = fixture.componentInstance;
const viewRef = vc.insertTpl(tpl, {}, 0);
fixture.detectChanges();
expect(queryList.length).toBe(1);
expect(fixture.componentInstance.queryListNotificationCounter).toBe(1);
vc.move(viewRef, 0);
fixture.detectChanges();
expect(queryList.length).toBe(1);
expect(fixture.componentInstance.queryListNotificationCounter).toBe(1);
});
it('should support a mix of content queries from the declaration and embedded view', () => {
@Directive({
selector: '[query-for-lots-of-content]',
standalone: false,
})
class QueryForLotsOfContent {
@ContentChildren('foo', {descendants: true}) foos1!: QueryList<ElementRef>;
@ContentChildren('foo', {descendants: true}) foos2!: QueryList<ElementRef>;
}
@Directive({
selector: '[query-for-content]',
standalone: false,
})
class QueryForContent {
@ContentChildren('foo') foos!: QueryList<ElementRef>;
}
@Component({
selector: 'test-comp',
template: `
<div query-for-lots-of-content>
<ng-template ngFor let-item [ngForOf]="items">
<div query-for-content>
<span #foo></span>
</div>
</ng-template>
</div>
`,
standalone: false,
})
class TestComponent {
items = [1, 2];
}
TestBed.configureTestingModule({
declarations: [TestComponent, QueryForContent, QueryForLotsOfContent],
});
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const lotsOfContentEl = fixture.debugElement.query(By.directive(QueryForLotsOfContent));
const lotsOfContentInstance = lotsOfContentEl.injector.get(QueryForLotsOfContent);
const contentEl = fixture.debugElement.query(By.directive(QueryForContent));
const contentInstance = contentEl.injector.get(QueryForContent);
expect(lotsOfContentInstance.foos1.length).toBe(2);
expect(lotsOfContentInstance.foos2.length).toBe(2);
expect(contentInstance.foos.length).toBe(1);
fixture.componentInstance.items = [];
fixture.detectChanges();
expect(lotsOfContentInstance.foos1.length).toBe(0);
expect(lotsOfContentInstance.foos2.length).toBe(0);
});
// https://stackblitz.com/edit/angular-rrmmuf?file=src/app/app.component.ts | {
"end_byte": 77208,
"start_byte": 70100,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/query_spec.ts"
} |
angular/packages/core/test/acceptance/query_spec.ts_77215_83461 | it('should report results when different instances of TemplateRef are inserted into one ViewContainerRefs', () => {
@Component({
selector: 'test-comp',
template: `
<ng-template #tpl1 let-idx="idx">
<div #foo [id]="'foo1_' + idx"></div>
</ng-template>
<div #foo id="middle"></div>
<ng-template #tpl2 let-idx="idx">
<div #foo [id]="'foo2_' + idx"></div>
</ng-template>
<ng-template vc></ng-template>
`,
standalone: false,
})
class TestComponent {
@ViewChild(ViewContainerManipulatorDirective) vc!: ViewContainerManipulatorDirective;
@ViewChild('tpl1') tpl1!: TemplateRef<any>;
@ViewChild('tpl2') tpl2!: TemplateRef<any>;
@ViewChildren('foo') query!: QueryList<any>;
}
TestBed.configureTestingModule({
declarations: [ViewContainerManipulatorDirective, TestComponent],
});
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const queryList = fixture.componentInstance.query;
const {tpl1, tpl2, vc} = fixture.componentInstance;
expect(queryList.length).toBe(1);
expect(queryList.first.nativeElement.getAttribute('id')).toBe('middle');
vc.insertTpl(tpl1!, {idx: 0}, 0);
vc.insertTpl(tpl2!, {idx: 1}, 1);
fixture.detectChanges();
expect(queryList.length).toBe(3);
let qListArr = queryList.toArray();
expect(qListArr[0].nativeElement.getAttribute('id')).toBe('foo1_0');
expect(qListArr[1].nativeElement.getAttribute('id')).toBe('middle');
expect(qListArr[2].nativeElement.getAttribute('id')).toBe('foo2_1');
vc.insertTpl(tpl1!, {idx: 1}, 1);
fixture.detectChanges();
expect(queryList.length).toBe(4);
qListArr = queryList.toArray();
expect(qListArr[0].nativeElement.getAttribute('id')).toBe('foo1_0');
expect(qListArr[1].nativeElement.getAttribute('id')).toBe('foo1_1');
expect(qListArr[2].nativeElement.getAttribute('id')).toBe('middle');
expect(qListArr[3].nativeElement.getAttribute('id')).toBe('foo2_1');
vc.remove(1);
fixture.detectChanges();
expect(queryList.length).toBe(3);
qListArr = queryList.toArray();
expect(qListArr[0].nativeElement.getAttribute('id')).toBe('foo1_0');
expect(qListArr[1].nativeElement.getAttribute('id')).toBe('middle');
expect(qListArr[2].nativeElement.getAttribute('id')).toBe('foo2_1');
vc.remove(1);
fixture.detectChanges();
expect(queryList.length).toBe(2);
qListArr = queryList.toArray();
expect(qListArr[0].nativeElement.getAttribute('id')).toBe('foo1_0');
expect(qListArr[1].nativeElement.getAttribute('id')).toBe('middle');
});
// https://stackblitz.com/edit/angular-7vvo9j?file=src%2Fapp%2Fapp.component.ts
// https://stackblitz.com/edit/angular-xzwp6n
it('should report results when the same TemplateRef is inserted into different ViewContainerRefs', () => {
@Component({
selector: 'test-comp',
template: `
<ng-template #tpl let-idx="idx" let-container_idx="container_idx">
<div #foo [id]="'foo_' + container_idx + '_' + idx"></div>
</ng-template>
<ng-template vc #vi0="vc"></ng-template>
<ng-template vc #vi1="vc"></ng-template>
`,
standalone: false,
})
class TestComponent {
@ViewChild('tpl') tpl!: TemplateRef<any>;
@ViewChild('vi0') vi0!: ViewContainerManipulatorDirective;
@ViewChild('vi1') vi1!: ViewContainerManipulatorDirective;
@ViewChildren('foo') query!: QueryList<any>;
}
TestBed.configureTestingModule({
declarations: [ViewContainerManipulatorDirective, TestComponent],
});
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const queryList = fixture.componentInstance.query;
const {tpl, vi0, vi1} = fixture.componentInstance;
expect(queryList.length).toBe(0);
vi0.insertTpl(tpl!, {idx: 0, container_idx: 0}, 0);
vi1.insertTpl(tpl!, {idx: 0, container_idx: 1}, 0);
fixture.detectChanges();
expect(queryList.length).toBe(2);
let qListArr = queryList.toArray();
expect(qListArr[0].nativeElement.getAttribute('id')).toBe('foo_0_0');
expect(qListArr[1].nativeElement.getAttribute('id')).toBe('foo_1_0');
vi0.remove();
fixture.detectChanges();
expect(queryList.length).toBe(1);
qListArr = queryList.toArray();
expect(qListArr[0].nativeElement.getAttribute('id')).toBe('foo_1_0');
vi1.remove();
fixture.detectChanges();
expect(queryList.length).toBe(0);
});
// https://stackblitz.com/edit/angular-wpd6gv?file=src%2Fapp%2Fapp.component.ts
it('should report results from views inserted in a lifecycle hook', () => {
@Component({
selector: 'my-app',
template: `
<ng-template #tpl>
<span #foo id="from_tpl"></span>
</ng-template>
<ng-template [ngTemplateOutlet]="show ? tpl : null"></ng-template>
`,
standalone: false,
})
class MyApp {
show = false;
@ViewChildren('foo') query!: QueryList<any>;
}
TestBed.configureTestingModule({declarations: [MyApp], imports: [CommonModule]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
const queryList = fixture.componentInstance.query;
expect(queryList.length).toBe(0);
fixture.componentInstance.show = true;
fixture.detectChanges();
expect(queryList.length).toBe(1);
expect(queryList.first.nativeElement.id).toBe('from_tpl');
fixture.componentInstance.show = false;
fixture.detectChanges();
expect(queryList.length).toBe(0);
});
});
}); | {
"end_byte": 83461,
"start_byte": 77215,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/query_spec.ts"
} |
angular/packages/core/test/acceptance/query_spec.ts_83465_89023 | describe('non-regression', () => {
it('should query by provider super-type in an embedded view', () => {
@Directive({
selector: '[child]',
standalone: false,
})
class Child {}
@Directive({
selector: '[parent]',
providers: [{provide: Child, useExisting: Parent}],
standalone: false,
})
class Parent extends Child {}
@Component({
selector: 'test-cmpt',
template: `<ng-template [ngIf]="true"><ng-template [ngIf]="true"><div parent></div></ng-template></ng-template>`,
standalone: false,
})
class TestCmpt {
@ViewChildren(Child) instances!: QueryList<Child>;
}
TestBed.configureTestingModule({declarations: [TestCmpt, Parent, Child]});
const fixture = TestBed.createComponent(TestCmpt);
fixture.detectChanges();
expect(fixture.componentInstance.instances.length).toBe(1);
});
it('should flatten multi-provider results', () => {
class MyClass {}
@Component({
selector: 'with-multi-provider',
template: '',
providers: [
{provide: MyClass, useExisting: forwardRef(() => WithMultiProvider), multi: true},
],
standalone: false,
})
class WithMultiProvider {}
@Component({
selector: 'test-cmpt',
template: `<with-multi-provider></with-multi-provider>`,
standalone: false,
})
class TestCmpt {
@ViewChildren(MyClass) queryResults!: QueryList<WithMultiProvider>;
}
TestBed.configureTestingModule({declarations: [TestCmpt, WithMultiProvider]});
const fixture = TestBed.createComponent(TestCmpt);
fixture.detectChanges();
expect(fixture.componentInstance.queryResults.length).toBe(1);
expect(fixture.componentInstance.queryResults.first).toBeInstanceOf(WithMultiProvider);
});
it('should flatten multi-provider results when crossing ng-template', () => {
class MyClass {}
@Component({
selector: 'with-multi-provider',
template: '',
providers: [
{provide: MyClass, useExisting: forwardRef(() => WithMultiProvider), multi: true},
],
standalone: false,
})
class WithMultiProvider {}
@Component({
selector: 'test-cmpt',
template: `
<ng-template [ngIf]="true"><with-multi-provider></with-multi-provider></ng-template>
<with-multi-provider></with-multi-provider>
`,
standalone: false,
})
class TestCmpt {
@ViewChildren(MyClass) queryResults!: QueryList<WithMultiProvider>;
}
TestBed.configureTestingModule({declarations: [TestCmpt, WithMultiProvider]});
const fixture = TestBed.createComponent(TestCmpt);
fixture.detectChanges();
expect(fixture.componentInstance.queryResults.length).toBe(2);
expect(fixture.componentInstance.queryResults.first).toBeInstanceOf(WithMultiProvider);
expect(fixture.componentInstance.queryResults.last).toBeInstanceOf(WithMultiProvider);
});
it('should allow undefined provider value in a [View/Content]Child queries', () => {
@Directive({
selector: '[group]',
standalone: false,
})
class GroupDir {}
@Directive({
selector: '[undefinedGroup]',
providers: [{provide: GroupDir, useValue: undefined}],
standalone: false,
})
class UndefinedGroup {}
@Component({
template: `
<div group></div>
<ng-template [ngIf]="true">
<div undefinedGroup></div>
</ng-template>
`,
standalone: false,
})
class App {
@ViewChild(GroupDir) group!: GroupDir;
}
TestBed.configureTestingModule({
declarations: [App, GroupDir, UndefinedGroup],
imports: [CommonModule],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.group).toBeInstanceOf(GroupDir);
});
it('should allow null / undefined provider value in a [View/Content]Children queries', () => {
@Directive({
selector: '[group]',
standalone: false,
})
class GroupDir {}
@Directive({
selector: '[nullGroup]',
providers: [{provide: GroupDir, useValue: null}],
standalone: false,
})
class NullGroup {}
@Directive({
selector: '[undefinedGroup]',
providers: [{provide: GroupDir, useValue: undefined}],
standalone: false,
})
class UndefinedGroup {}
@Component({
template: `
<ng-template [ngIf]="true">
<div nullGroup></div>
</ng-template>
<div group></div>
<ng-template [ngIf]="true">
<div undefinedGroup></div>
</ng-template>
`,
standalone: false,
})
class App {
@ViewChildren(GroupDir) groups!: QueryList<GroupDir>;
}
TestBed.configureTestingModule({
declarations: [App, GroupDir, NullGroup, UndefinedGroup],
imports: [CommonModule],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryList = fixture.componentInstance.groups;
expect(queryList.length).toBe(3);
const groups = queryList.toArray();
expect(groups[0]).toBeNull();
expect(groups[1]).toBeInstanceOf(GroupDir);
expect(groups[2]).toBeUndefined();
});
}); | {
"end_byte": 89023,
"start_byte": 83465,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/query_spec.ts"
} |
angular/packages/core/test/acceptance/query_spec.ts_89027_98279 | describe('querying for string token providers', () => {
@Directive({
selector: '[text-token]',
providers: [{provide: 'Token', useExisting: TextTokenDirective}],
standalone: false,
})
class TextTokenDirective {}
it('should match string injection token in a ViewChild query', () => {
@Component({
template: '<div text-token></div>',
standalone: false,
})
class App {
@ViewChild('Token') token: any;
}
TestBed.configureTestingModule({declarations: [App, TextTokenDirective]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.token).toBeInstanceOf(TextTokenDirective);
});
it('should give precedence to local reference if both a reference and a string injection token provider match a ViewChild query', () => {
@Component({
template: '<div text-token #Token></div>',
standalone: false,
})
class App {
@ViewChild('Token') token: any;
}
TestBed.configureTestingModule({declarations: [App, TextTokenDirective]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.token).toBeInstanceOf(ElementRef);
});
it('should match string injection token in a ViewChildren query', () => {
@Component({
template: '<div text-token></div>',
standalone: false,
})
class App {
@ViewChildren('Token') tokens!: QueryList<any>;
}
TestBed.configureTestingModule({declarations: [App, TextTokenDirective]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const tokens = fixture.componentInstance.tokens;
expect(tokens.length).toBe(1);
expect(tokens.first).toBeInstanceOf(TextTokenDirective);
});
it('should match both string injection token and local reference inside a ViewChildren query', () => {
@Component({
template: '<div text-token #Token></div>',
standalone: false,
})
class App {
@ViewChildren('Token') tokens!: QueryList<any>;
}
TestBed.configureTestingModule({declarations: [App, TextTokenDirective]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.tokens.toArray()).toEqual([
jasmine.any(ElementRef),
jasmine.any(TextTokenDirective),
]);
});
it('should match string injection token in a ContentChild query', () => {
@Component({
selector: 'has-query',
template: '<ng-content></ng-content>',
standalone: false,
})
class HasQuery {
@ContentChild('Token') token: any;
}
@Component({
template: '<has-query><div text-token></div></has-query>',
standalone: false,
})
class App {
@ViewChild(HasQuery) queryComp!: HasQuery;
}
TestBed.configureTestingModule({declarations: [App, HasQuery, TextTokenDirective]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.queryComp.token).toBeInstanceOf(TextTokenDirective);
});
it('should give precedence to local reference if both a reference and a string injection token provider match a ContentChild query', () => {
@Component({
selector: 'has-query',
template: '<ng-content></ng-content>',
standalone: false,
})
class HasQuery {
@ContentChild('Token') token: any;
}
@Component({
template: '<has-query><div text-token #Token></div></has-query>',
standalone: false,
})
class App {
@ViewChild(HasQuery) queryComp!: HasQuery;
}
TestBed.configureTestingModule({declarations: [App, HasQuery, TextTokenDirective]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.queryComp.token).toBeInstanceOf(ElementRef);
});
it('should match string injection token in a ContentChildren query', () => {
@Component({
selector: 'has-query',
template: '<ng-content></ng-content>',
standalone: false,
})
class HasQuery {
@ContentChildren('Token') tokens!: QueryList<any>;
}
@Component({
template: '<has-query><div text-token></div></has-query>',
standalone: false,
})
class App {
@ViewChild(HasQuery) queryComp!: HasQuery;
}
TestBed.configureTestingModule({declarations: [App, HasQuery, TextTokenDirective]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const tokens = fixture.componentInstance.queryComp.tokens;
expect(tokens.length).toBe(1);
expect(tokens.first).toBeInstanceOf(TextTokenDirective);
});
it('should match both string injection token and local reference inside a ContentChildren query', () => {
@Component({
selector: 'has-query',
template: '<ng-content></ng-content>',
standalone: false,
})
class HasQuery {
@ContentChildren('Token') tokens!: QueryList<any>;
}
@Component({
template: '<has-query><div text-token #Token></div></has-query>',
standalone: false,
})
class App {
@ViewChild(HasQuery) queryComp!: HasQuery;
}
TestBed.configureTestingModule({declarations: [App, HasQuery, TextTokenDirective]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.queryComp.tokens.toArray()).toEqual([
jasmine.any(ElementRef),
jasmine.any(TextTokenDirective),
]);
});
it('should match string token specified through the `read` option of a view query', () => {
@Component({
template: '<div text-token #Token></div>',
standalone: false,
})
class App {
@ViewChild('Token', {read: 'Token'}) token: any;
}
TestBed.configureTestingModule({declarations: [App, TextTokenDirective]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.token).toBeInstanceOf(TextTokenDirective);
});
it('should match string token specified through the `read` option of a content query', () => {
@Component({
selector: 'has-query',
template: '<ng-content></ng-content>',
standalone: false,
})
class HasQuery {
@ContentChild('Token', {read: 'Token'}) token: any;
}
@Component({
template: '<has-query><div text-token #Token></div></has-query>',
standalone: false,
})
class App {
@ViewChild(HasQuery) queryComp!: HasQuery;
}
TestBed.configureTestingModule({declarations: [App, HasQuery, TextTokenDirective]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.queryComp.token).toBeInstanceOf(TextTokenDirective);
});
});
});
function initWithTemplate(compType: Type<any>, template: string) {
TestBed.overrideComponent(compType, {set: new Component({template})});
const fixture = TestBed.createComponent(compType);
fixture.detectChanges();
return fixture;
}
@Component({
selector: 'local-ref-query-component',
template: '<ng-content></ng-content>',
standalone: false,
})
class QueryComp {
@ViewChild('viewQuery') viewChild!: any;
@ContentChild('contentQuery') contentChild!: any;
@ViewChildren('viewQuery') viewChildren!: QueryList<any>;
@ContentChildren('contentQuery') contentChildren!: QueryList<any>;
}
@Component({
selector: 'app-comp',
template: ``,
standalone: false,
})
class AppComp {}
@Component({
selector: 'simple-comp-a',
template: '',
standalone: false,
})
class SimpleCompA {}
@Component({
selector: 'simple-comp-b',
template: '',
standalone: false,
})
class SimpleCompB {}
@Directive({
selector: '[text]',
standalone: false,
})
class TextDirective {
@Input() text = '';
}
@Component({
selector: 'static-view-query-comp',
template: `
<div [text]="text"></div>
<span #foo></span>
`,
standalone: false,
})
class StaticViewQueryComp {
private _textDir!: TextDirective;
private _foo!: ElementRef;
setEvents: string[] = [];
@ViewChild(TextDirective, {static: true})
get textDir(): TextDirective {
return this._textDir;
}
set textDir(value: TextDirective) {
this.setEvents.push('textDir set');
this._textDir = value;
}
@ViewChild('foo')
get foo(): ElementRef {
return this._foo;
}
set foo(value: ElementRef) {
this.setEvents.push('foo set');
this._foo = value;
}
text = 'some text';
}
@Component({
selector: 'subclass-static-view-query-comp',
template: `
<div [text]="text"></div>
<span #foo></span>
<div #bar></div>
<span #baz></span>
`,
standalone: false,
})
class SubclassStaticViewQueryComp extends StaticViewQueryComp {
@ViewChild('bar', {static: true}) bar!: ElementRef;
@ViewChild('baz') baz!: ElementRef;
} | {
"end_byte": 98279,
"start_byte": 89027,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/query_spec.ts"
} |
angular/packages/core/test/acceptance/query_spec.ts_98281_102459 | @Component({
selector: 'static-content-query-comp',
template: `<ng-content></ng-content>`,
standalone: false,
})
class StaticContentQueryComp {
private _textDir!: TextDirective;
private _foo!: ElementRef;
setEvents: string[] = [];
@ContentChild(TextDirective, {static: true})
get textDir(): TextDirective {
return this._textDir;
}
set textDir(value: TextDirective) {
this.setEvents.push('textDir set');
this._textDir = value;
}
@ContentChild('foo')
get foo(): ElementRef {
return this._foo;
}
set foo(value: ElementRef) {
this.setEvents.push('foo set');
this._foo = value;
}
}
@Directive({
selector: '[staticContentQueryDir]',
standalone: false,
})
class StaticContentQueryDir {
private _textDir!: TextDirective;
private _foo!: ElementRef;
setEvents: string[] = [];
@ContentChild(TextDirective, {static: true})
get textDir(): TextDirective {
return this._textDir;
}
set textDir(value: TextDirective) {
this.setEvents.push('textDir set');
this._textDir = value;
}
@ContentChild('foo')
get foo(): ElementRef {
return this._foo;
}
set foo(value: ElementRef) {
this.setEvents.push('foo set');
this._foo = value;
}
}
@Component({
selector: 'subclass-static-content-query-comp',
template: `<ng-content></ng-content>`,
standalone: false,
})
class SubclassStaticContentQueryComp extends StaticContentQueryComp {
@ContentChild('bar', {static: true}) bar!: ElementRef;
@ContentChild('baz') baz!: ElementRef;
}
@Component({
selector: 'query-with-changes',
template: `
<div *ngIf="showing" #foo></div>
`,
standalone: false,
})
export class QueryCompWithChanges {
@ViewChildren('foo') foos!: QueryList<any>;
showing = false;
}
@Component({
selector: 'query-with-no-changes',
template: `
<query-component>
<div *ngIf="true" #foo></div>
<div *ngIf="showing">
Showing me should not change the content of the query
<div *ngIf="innerShowing" #foo></div>
</div>
</query-component>
`,
standalone: false,
})
export class QueryCompWithNoChanges {
showing: boolean = true;
innerShowing: boolean = true;
queryComp!: QueryCompWithStrictChangeEmitParent;
}
@Component({
selector: 'query-component',
template: `<ng-content></ng-content>`,
standalone: false,
})
export class QueryCompWithStrictChangeEmitParent {
@ContentChildren('foo', {
descendants: true,
emitDistinctChangesOnly: true,
})
foos!: QueryList<any>;
constructor(public queryCompWithNoChanges: QueryCompWithNoChanges) {
queryCompWithNoChanges.queryComp = this;
}
}
@Component({
selector: 'query-target',
template: '<ng-content></ng-content>',
standalone: false,
})
class SuperDirectiveQueryTarget {}
@Directive({
selector: '[super-directive]',
standalone: false,
})
class SuperDirective {
@ViewChildren(SuperDirectiveQueryTarget) headers!: QueryList<SuperDirectiveQueryTarget>;
}
@Component({
template: `
<query-target>One</query-target>
<query-target>Two</query-target>
`,
standalone: false,
})
class SubComponent extends SuperDirective {}
const MY_OPTION_TOKEN = new InjectionToken<TestComponentWithToken>('ComponentWithToken');
@Component({
selector: 'my-option',
template: 'Option',
providers: [{provide: MY_OPTION_TOKEN, useExisting: TestComponentWithToken}],
standalone: false,
})
class TestComponentWithToken {}
@Component({
selector: 'test-injection-token',
template: `
<my-option></my-option>
<my-option></my-option>
<ng-content></ng-content>
`,
standalone: false,
})
class TestInjectionTokenQueries {
@ViewChild(MY_OPTION_TOKEN) viewFirstOption!: TestComponentWithToken;
@ViewChildren(MY_OPTION_TOKEN) viewOptions!: QueryList<TestComponentWithToken>;
@ContentChild(MY_OPTION_TOKEN) contentFirstOption!: TestComponentWithToken;
@ContentChildren(MY_OPTION_TOKEN) contentOptions!: QueryList<TestComponentWithToken>;
}
@Component({
template: `
<test-injection-token>
<my-option></my-option>
<my-option></my-option>
</test-injection-token>
`,
standalone: false,
})
class TestInjectionTokenContentQueries {} | {
"end_byte": 102459,
"start_byte": 98281,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/query_spec.ts"
} |
angular/packages/core/test/acceptance/router_integration_spec.ts_0_1551 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {APP_BASE_HREF} from '@angular/common';
import {NgModule} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {Router, RouterModule} from '@angular/router';
describe('router integration acceptance', () => {
// Test case that ensures that we don't regress in multi-provider ordering
// which is leveraged in the router. See: FW-1349
it('should have correct order for multiple routes declared in different modules', () => {
@NgModule({
imports: [
RouterModule.forChild([
{path: '1a:1', redirectTo: ''},
{path: '1a:2', redirectTo: ''},
]),
],
})
class Level1AModule {}
@NgModule({
imports: [
RouterModule.forChild([
{path: '1b:1', redirectTo: ''},
{path: '1b:2', redirectTo: ''},
]),
],
})
class Level1BModule {}
@NgModule({
imports: [
RouterModule.forRoot([{path: 'root', redirectTo: ''}]),
Level1AModule,
Level1BModule,
],
providers: [{provide: APP_BASE_HREF, useValue: '/'}],
})
class RootModule {}
TestBed.configureTestingModule({
imports: [RootModule],
});
expect(TestBed.inject(Router).config.map((r) => r.path)).toEqual([
'1a:1',
'1a:2',
'1b:1',
'1b:2',
'root',
]);
});
});
| {
"end_byte": 1551,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/router_integration_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_0_4487 | /**
* @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 {
Component,
ContentChildren,
Directive,
EventEmitter,
HostBinding,
HostListener,
Input,
OnChanges,
Output,
QueryList,
ViewChildren,
} from '@angular/core';
import {getDirectiveDef} from '@angular/core/src/render3/def_getters';
import {TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
describe('inheritance', () => {
it('should throw when trying to inherit a component from a directive', () => {
@Component({
selector: 'my-comp',
template: '<div></div>',
standalone: false,
})
class MyComponent {}
@Directive({
selector: '[my-dir]',
standalone: false,
})
class MyDirective extends MyComponent {}
@Component({
template: `<div my-dir></div>`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent, MyDirective],
});
expect(() => {
TestBed.createComponent(App);
}).toThrowError(
'NG0903: Directives cannot inherit Components. Directive MyDirective is attempting to extend component MyComponent',
);
});
describe('multiple children', () => {
it("should ensure that multiple child classes don't cause multiple parent execution", () => {
// Assume this inheritance:
// Base
// |
// Super
// / \
// Sub1 Sub2
//
// In the above case:
// 1. Sub1 as will walk the inheritance Sub1, Super, Base
// 2. Sub2 as will walk the inheritance Sub2, Super, Base
//
// Notice that Super, Base will get walked twice. Because inheritance works by wrapping parent
// hostBindings function in a delegate which calls the hostBindings of the directive as well
// as super, we need to ensure that we don't double wrap the hostBindings function. Doing so
// would result in calling the hostBindings multiple times (unnecessarily). This would be
// especially an issue if we have a lot of sub-classes (as is common in component libraries)
const log: string[] = [];
@Directive({
selector: '[superDir]',
standalone: false,
})
class BaseDirective {
@HostBinding('style.background-color')
get backgroundColor() {
log.push('Base.backgroundColor');
return 'white';
}
}
@Directive({
selector: '[superDir]',
standalone: false,
})
class SuperDirective extends BaseDirective {
@HostBinding('style.color')
get color() {
log.push('Super.color');
return 'blue';
}
}
@Directive({
selector: '[subDir1]',
standalone: false,
})
class Sub1Directive extends SuperDirective {
@HostBinding('style.height')
get height() {
log.push('Sub1.height');
return '200px';
}
}
@Directive({
selector: '[subDir2]',
standalone: false,
})
class Sub2Directive extends SuperDirective {
@HostBinding('style.width')
get width() {
log.push('Sub2.width');
return '100px';
}
}
@Component({
template: `<div subDir1 subDir2></div>`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, Sub1Directive, Sub2Directive, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges(false); // Don't check for no changes (so that assertion does not need
// to worry about it.)
expect(log).toEqual([
'Base.backgroundColor',
'Super.color',
'Sub1.height', //
'Base.backgroundColor',
'Super.color',
'Sub2.width', //
]);
expect(getDirectiveDef(BaseDirective)!.hostVars).toEqual(2);
expect(getDirectiveDef(SuperDirective)!.hostVars).toEqual(4);
expect(getDirectiveDef(Sub1Directive)!.hostVars).toEqual(6);
expect(getDirectiveDef(Sub2Directive)!.hostVars).toEqual(6);
});
}); | {
"end_byte": 4487,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_4491_10930 | describe('ngOnChanges', () => {
it('should be inherited when super is a directive', () => {
const log: string[] = [];
@Directive({
selector: '[superDir]',
standalone: false,
})
class SuperDirective implements OnChanges {
@Input() someInput = '';
ngOnChanges() {
log.push('on changes!');
}
}
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {}
@Component({
template: `<div subDir [someInput]="1"></div>`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited when super is a simple class', () => {
const log: string[] = [];
class SuperClass {
ngOnChanges() {
log.push('on changes!');
}
}
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperClass {
@Input() someInput = '';
}
@Component({
template: `<div subDir [someInput]="1"></div>`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited when super is a directive and grand-super is a directive', () => {
const log: string[] = [];
@Directive({
selector: '[grandSuperDir]',
standalone: false,
})
class GrandSuperDirective implements OnChanges {
@Input() someInput = '';
ngOnChanges() {
log.push('on changes!');
}
}
@Directive({
selector: '[superDir]',
standalone: false,
})
class SuperDirective extends GrandSuperDirective {}
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {}
@Component({
template: `<div subDir [someInput]="1"></div>`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective, GrandSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited when super is a directive and grand-super is a simple class', () => {
const log: string[] = [];
class GrandSuperClass {
ngOnChanges() {
log.push('on changes!');
}
}
@Directive({
selector: '[superDir]',
standalone: false,
})
class SuperDirective extends GrandSuperClass {
@Input() someInput = '';
}
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {}
@Component({
template: `<div subDir [someInput]="1"></div>`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited when super is a simple class and grand-super is a directive', () => {
const log: string[] = [];
@Directive({
selector: '[grandSuperDir]',
standalone: false,
})
class GrandSuperDirective implements OnChanges {
@Input() someInput = '';
ngOnChanges() {
log.push('on changes!');
}
}
class SuperClass extends GrandSuperDirective {}
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperClass {}
@Component({
template: `<div subDir [someInput]="1"></div>`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, SubDirective, GrandSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited when super is a simple class and grand-super is a simple class', () => {
const log: string[] = [];
class GrandSuperClass {
ngOnChanges() {
log.push('on changes!');
}
}
class SuperClass extends GrandSuperClass {}
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperClass {
@Input() someInput = '';
}
@Component({
template: `<div subDir [someInput]="1"></div>`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited from undecorated super class which inherits from decorated one', () => {
let changes = 0;
abstract class Base {
// Add an Input so that we have at least one Angular decorator on a class field.
@Input() inputBase: any;
abstract input: any;
}
abstract class UndecoratedBase extends Base {
abstract override input: any;
ngOnChanges() {
changes++;
}
}
@Component({
selector: 'my-comp',
template: '',
standalone: false,
})
class MyComp extends UndecoratedBase {
@Input() override input: any;
}
@Component({
template: '<my-comp [input]="value"></my-comp>',
standalone: false,
})
class App {
value = 'hello';
}
TestBed.configureTestingModule({declarations: [MyComp, App]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(changes).toBe(1);
});
}); | {
"end_byte": 10930,
"start_byte": 4491,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_10934_19252 | describe('of bare super class by a directive', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
class SuperDirective {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
beforeEach(() => (fired.length = 0));
it('ngOnInit', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngDoCheck', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterContentInit', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterContentChecked', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterViewInit', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterViewChecked', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngOnDestroy', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['sub destroy']);
});
}); | {
"end_byte": 19252,
"start_byte": 10934,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_19258_28824 | describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
class SuperDirective {
@Input() foo = '';
@Input() bar = '';
@Input() baz = '';
}
@Directive({
selector: '[sub-dir]',
standalone: false,
})
class SubDirective extends SuperDirective {
@Input() override baz = '';
@Input() qux = '';
}
@Component({
template: `<p sub-dir [foo]="a" [bar]="b" [baz]="c" [qux]="d"></p>`,
standalone: false,
})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir = fixture.debugElement
.query(By.directive(SubDirective))
.injector.get(SubDirective);
expect(subDir.foo).toBe('a');
expect(subDir.bar).toBe('b');
expect(subDir.baz).toBe('c');
expect(subDir.qux).toBe('d');
});
it('should not inherit transforms if inputs are re-declared', () => {
@Directive()
class Base {
@Input({transform: (v) => `${v}-transformed`}) someInput: string = '';
}
@Directive({
standalone: true,
selector: 'dir',
inputs: ['someInput'],
})
class ActualDir extends Base {}
@Component({
standalone: true,
imports: [ActualDir],
template: `<dir someInput="newValue">`,
})
class TestCmp {}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const actualDir = fixture.debugElement
.query(By.directive(ActualDir))
.injector.get(ActualDir);
expect(actualDir.someInput).toEqual('newValue');
});
it('should inherit transforms if inputs are aliased', () => {
@Directive()
class Base {
@Input({transform: (v) => `${v}-transformed`, alias: 'publicName'}) fieldName: string =
'';
}
@Directive({
standalone: true,
selector: 'dir',
})
class ActualDir extends Base {}
@Component({
standalone: true,
imports: [ActualDir],
template: `<dir publicName="newValue">`,
})
class TestCmp {}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const actualDir = fixture.debugElement
.query(By.directive(ActualDir))
.injector.get(ActualDir);
expect(actualDir.fieldName).toEqual('newValue-transformed');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
class SuperDirective {
@Output() foo = new EventEmitter<string>();
}
@Directive({
selector: '[sub-dir]',
standalone: false,
})
class SubDirective extends SuperDirective {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<div sub-dir (foo)="handleFoo($event)"></div>
`,
standalone: false,
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
class SuperDirective {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
@Directive({
selector: '[sub-dir]',
standalone: false,
})
class SubDirective extends SuperDirective {}
@Component({
template: `
<p sub-dir>test</p>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(SubDirective));
expect(queryResult.nativeElement.tagName).toBe('P');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
class SuperDirective {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
@Directive({
selector: '[sub-dir]',
standalone: false,
})
class SubDirective extends SuperDirective {}
@Component({
template: `
<p sub-dir superTitle="test">test</p>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(SubDirective));
expect(queryResult.nativeElement.title).toBe('test!!!');
});
});
describe('ContentChildren', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({
selector: '[child-dir]',
standalone: false,
})
class ChildDir {}
class SuperDirective {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Directive({
selector: '[sub-dir]',
standalone: false,
})
class SubDirective extends SuperDirective {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<ul sub-dir>
<li child-dir>one</li>
<li child-dir>two</li>
</ul>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, SubDirective, ChildDir],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
});
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
describe('of a directive by another directive', | {
"end_byte": 28824,
"start_byte": 19258,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_28825_38821 | () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
beforeEach(() => (fired.length = 0));
it('ngOnInit', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngDoCheck', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterContentInit', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterContentChecked', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterViewInit', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterViewChecked', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngOnDestroy', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['sub destroy']);
});
});
describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
@Input() foo = '';
@Input() bar = '';
@Input() baz = '';
}
@Directive({
selector: '[sub-dir]',
standalone: false,
})
class SubDirective extends SuperDirective {
@Input() override baz = '';
@Input() qux = '';
}
@Component({
template: `<p sub-dir [foo]="a" [bar]="b" [baz]="c" [qux]="d"></p>`,
standalone: false,
})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir = fixture.debugElement
.query(By.directive(SubDirective))
.injector.get(SubDirective);
expect(subDir.foo).toBe('a');
expect(subDir.bar).toBe('b');
expect(subDir.baz).toBe('c');
expect(subDir.qux).toBe('d');
});
}); | {
"end_byte": 38821,
"start_byte": 28825,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_38827_45440 | describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
@Output() foo = new EventEmitter<string>();
}
@Directive({
selector: '[sub-dir]',
standalone: false,
})
class SubDirective extends SuperDirective {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<div sub-dir (foo)="handleFoo($event)"></div>
`,
standalone: false,
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
@Directive({
selector: '[sub-dir]',
standalone: false,
})
class SubDirective extends SuperDirective {}
@Component({
template: `
<p sub-dir>test</p>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(SubDirective));
expect(queryResult.nativeElement.tagName).toBe('P');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
@Directive({
selector: '[sub-dir]',
standalone: false,
})
class SubDirective extends SuperDirective {}
@Component({
template: `
<p sub-dir superTitle="test">test</p>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(SubDirective));
expect(queryResult.nativeElement.title).toBe('test!!!');
});
});
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({
selector: '[child-dir]',
standalone: false,
})
class ChildDir {}
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Directive({
selector: '[sub-dir]',
standalone: false,
})
class SubDirective extends SuperDirective {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<ul sub-dir>
<li child-dir>one</li>
<li child-dir>two</li>
</ul>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, SubDirective, ChildDir, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
}); | {
"end_byte": 45440,
"start_byte": 38827,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_45444_54082 | describe('of a directive by a bare class then by another directive', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperSuperDirective {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
class SuperDirective extends SuperSuperDirective {}
beforeEach(() => (fired.length = 0));
it('ngOnInit', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngDoCheck', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterContentInit', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterContentChecked', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterViewInit', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterViewChecked', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngOnDestroy', () => {
@Directive({
selector: '[subDir]',
standalone: false,
})
class SubDirective extends SuperDirective {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['sub destroy']);
});
}); | {
"end_byte": 54082,
"start_byte": 45444,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_54088_63471 | describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperSuperDirective {
@Input() foo = '';
@Input() baz = '';
}
class SuperDirective extends SuperSuperDirective {
@Input() bar = '';
}
@Directive({
selector: '[sub-dir]',
standalone: false,
})
class SubDirective extends SuperDirective {
@Input() override baz = '';
@Input() qux = '';
}
@Component({
selector: 'my-app',
template: `<p sub-dir [foo]="a" [bar]="b" [baz]="c" [qux]="d"></p>`,
standalone: false,
})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir = fixture.debugElement
.query(By.directive(SubDirective))
.injector.get(SubDirective);
expect(subDir.foo).toBe('a');
expect(subDir.bar).toBe('b');
expect(subDir.baz).toBe('c');
expect(subDir.qux).toBe('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperSuperDirective {
@Output() foo = new EventEmitter<string>();
}
class SuperDirective extends SuperSuperDirective {
@Output() bar = new EventEmitter<string>();
}
@Directive({
selector: '[sub-dir]',
standalone: false,
})
class SubDirective extends SuperDirective {
ngOnInit() {
this.foo.emit('test1');
this.bar.emit('test2');
}
}
@Component({
template: `
<div sub-dir (foo)="handleFoo($event)" (bar)="handleBar($event)"></div>
`,
standalone: false,
})
class App {
foo = '';
bar = '';
handleFoo(event: string) {
this.foo = event;
}
handleBar(event: string) {
this.bar = event;
}
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test1');
expect(app.bar).toBe('test2');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperSuperDirective {
@HostBinding('style.color') color = 'red';
}
class SuperDirective extends SuperSuperDirective {
@HostBinding('style.backgroundColor') bg = 'black';
}
@Directive({
selector: '[sub-dir]',
standalone: false,
})
class SubDirective extends SuperDirective {}
@Component({
template: `
<p sub-dir>test</p>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(SubDirective));
expect(queryResult.nativeElement.tagName).toBe('P');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperSuperDirective {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
class SuperDirective extends SuperSuperDirective {
@HostBinding('accessKey')
get boundAltKey() {
return this.superAccessKey + '???';
}
@Input() superAccessKey = '';
}
@Directive({
selector: '[sub-dir]',
standalone: false,
})
class SubDirective extends SuperDirective {}
@Component({
template: `
<p sub-dir superTitle="test1" superAccessKey="test2">test</p>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const p: HTMLParagraphElement = fixture.debugElement.query(
By.directive(SubDirective),
).nativeElement;
expect(p.title).toBe('test1!!!');
expect(p.accessKey).toBe('test2???');
});
});
it('should inherit ContentChildren queries', () => {
let foundChildDir1s: QueryList<ChildDir1>;
let foundChildDir2s: QueryList<ChildDir2>;
@Directive({
selector: '[child-dir-one]',
standalone: false,
})
class ChildDir1 {}
@Directive({
selector: '[child-dir-two]',
standalone: false,
})
class ChildDir2 {}
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperSuperDirective {
@ContentChildren(ChildDir1) childDir1s!: QueryList<ChildDir1>;
}
class SuperDirective extends SuperSuperDirective {
@ContentChildren(ChildDir1) childDir2s!: QueryList<ChildDir2>;
}
@Directive({
selector: '[sub-dir]',
standalone: false,
})
class SubDirective extends SuperDirective {
ngAfterViewInit() {
foundChildDir1s = this.childDir1s;
foundChildDir2s = this.childDir2s;
}
}
@Component({
template: `
<ul sub-dir>
<li child-dir-one child-dir-two>one</li>
<li child-dir-one>two</li>
<li child-dir-two>three</li>
</ul>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, SubDirective, ChildDir1, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundChildDir1s!.length).toBe(2);
expect(foundChildDir2s!.length).toBe(2);
});
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property | {
"end_byte": 63471,
"start_byte": 54088,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_63476_72184 | // TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
describe('of bare super class by a component', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
class SuperComponent {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
beforeEach(() => (fired.length = 0));
it('ngOnInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngDoCheck', () => {
@Directive({
selector: 'my-comp',
standalone: false,
})
class MyComponent extends SuperComponent {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterContentInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterContentChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterViewInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterViewChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngOnDestroy', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['sub destroy']);
});
}); | {
"end_byte": 72184,
"start_byte": 63476,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_72190_79992 | describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
class SuperComponent {
@Input() foo = '';
@Input() bar = '';
@Input() baz = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
@Input() override baz = '';
@Input() qux = '';
}
@Component({
template: `<my-comp [foo]="a" [bar]="b" [baz]="c" [qux]="d"></my-comp>`,
standalone: false,
})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir: MyComponent = fixture.debugElement.query(
By.directive(MyComponent),
).componentInstance;
expect(subDir.foo).toEqual('a');
expect(subDir.bar).toEqual('b');
expect(subDir.baz).toEqual('c');
expect(subDir.qux).toEqual('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
class SuperComponent {
@Output() foo = new EventEmitter<string>();
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<my-comp (foo)="handleFoo($event)"></my-comp>
`,
standalone: false,
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
class SuperComponent {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {}
@Component({
template: `
<my-comp>test</my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
class SuperComponent {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {}
@Component({
template: `
<my-comp superTitle="test">test</my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.title).toBe('test!!!');
});
});
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({
selector: '[child-dir]',
standalone: false,
})
class ChildDir {}
class SuperComponent {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({
selector: 'my-comp',
template: `<ul><ng-content></ng-content></ul>`,
standalone: false,
})
class MyComponent extends SuperComponent {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp>
<li child-dir>one</li>
<li child-dir>two</li>
</my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
}); | {
"end_byte": 79992,
"start_byte": 72190,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_79996_88777 | describe('of a directive inherited by a component', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
beforeEach(() => (fired.length = 0));
it('ngOnInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperDirective {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngDoCheck', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperDirective {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterContentInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperDirective {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterContentChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperDirective {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterViewInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperDirective {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterViewChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperDirective {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngOnDestroy', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperDirective {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['sub destroy']);
});
}); | {
"end_byte": 88777,
"start_byte": 79996,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_88783_98215 | describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
@Input() foo = '';
@Input() bar = '';
@Input() baz = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperDirective {
@Input() override baz = '';
@Input() qux = '';
}
@Component({
template: `<my-comp [foo]="a" [bar]="b" [baz]="c" [qux]="d"></my-comp>`,
standalone: false,
})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir: MyComponent = fixture.debugElement.query(
By.directive(MyComponent),
).componentInstance;
expect(subDir.foo).toEqual('a');
expect(subDir.bar).toEqual('b');
expect(subDir.baz).toEqual('c');
expect(subDir.qux).toEqual('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
@Output() foo = new EventEmitter<string>();
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperDirective {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<my-comp (foo)="handleFoo($event)"></my-comp>
`,
standalone: false,
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperDirective {}
@Component({
template: `
<my-comp>test</my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperDirective {}
@Component({
template: `
<my-comp superTitle="test">test</my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.title).toBe('test!!!');
});
});
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({
selector: '[child-dir]',
standalone: false,
})
class ChildDir {}
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({
selector: 'my-comp',
template: `<ul><ng-content></ng-content></ul>`,
standalone: false,
})
class MyComponent extends SuperDirective {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp>
<li child-dir>one</li>
<li child-dir>two</li>
</my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperDirective, ChildDir],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
it('should inherit ViewChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({
selector: '[child-dir]',
standalone: false,
})
class ChildDir {}
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
@ViewChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({
selector: 'my-comp',
template: `
<ul>
<li child-dir *ngFor="let item of items">{{item}}</li>
</ul>
`,
standalone: false,
})
class MyComponent extends SuperDirective {
items = [1, 2, 3, 4, 5];
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp></my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(5);
});
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property | {
"end_byte": 98215,
"start_byte": 88783,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_98220_107091 | // TODO: sub has ContentChild and super has ContentChildren on same property
});
describe('of a directive inherited by a bare class and then by a component', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
class BareClass extends SuperDirective {}
beforeEach(() => (fired.length = 0));
it('ngOnInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends BareClass {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngDoCheck', () => {
@Directive({
selector: 'my-comp',
standalone: false,
})
class MyComponent extends BareClass {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterContentInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends BareClass {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterContentChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends BareClass {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterViewInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends BareClass {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterViewChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends BareClass {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngOnDestroy', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends BareClass {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['sub destroy']);
});
}); | {
"end_byte": 107091,
"start_byte": 98220,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_107097_116565 | describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
@Input() foo = '';
@Input() baz = '';
}
class BareClass extends SuperDirective {
@Input() bar = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends BareClass {
@Input() override baz = '';
@Input() qux = '';
}
@Component({
template: `<my-comp [foo]="a" [bar]="b" [baz]="c" [qux]="d"></my-comp>`,
standalone: false,
})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, BareClass, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir: MyComponent = fixture.debugElement.query(
By.directive(MyComponent),
).componentInstance;
expect(subDir.foo).toEqual('a');
expect(subDir.bar).toEqual('b');
expect(subDir.baz).toEqual('c');
expect(subDir.qux).toEqual('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
@Output() foo = new EventEmitter<string>();
}
class BareClass extends SuperDirective {}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends BareClass {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<my-comp (foo)="handleFoo($event)"></my-comp>
`,
standalone: false,
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
class BareClass extends SuperDirective {}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends BareClass {}
@Component({
template: `
<my-comp>test</my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
class BareClass extends SuperDirective {
@HostBinding('accessKey')
get boundAccessKey() {
return this.superAccessKey + '???';
}
@Input() superAccessKey = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends BareClass {}
@Component({
template: `
<my-comp superTitle="test1" superAccessKey="test2">test</my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, SuperDirective, BareClass, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.title).toBe('test1!!!');
expect(queryResult.nativeElement.accessKey).toBe('test2???');
});
});
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({
selector: '[child-dir]',
standalone: false,
})
class ChildDir {}
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
class BareClass extends SuperDirective {}
@Component({
selector: 'my-comp',
template: `<ul><ng-content></ng-content></ul>`,
standalone: false,
})
class MyComponent extends BareClass {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp>
<li child-dir>one</li>
<li child-dir>two</li>
</my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
it('should inherit ViewChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({
selector: '[child-dir]',
standalone: false,
})
class ChildDir {}
@Directive({
selector: '[super-dir]',
standalone: false,
})
class SuperDirective {
@ViewChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
class BareClass extends SuperDirective {}
@Component({
selector: 'my-comp',
template: `
<ul>
<li child-dir *ngFor="let item of items">{{item}}</li>
</ul>
`,
standalone: false,
})
class MyComponent extends BareClass {
items = [1, 2, 3, 4, 5];
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp></my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(5);
});
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property | {
"end_byte": 116565,
"start_byte": 107097,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_116570_126014 | // TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
describe('of a component inherited by a component', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
standalone: false,
})
class SuperComponent {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
beforeEach(() => (fired.length = 0));
it('ngOnInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngDoCheck', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterContentInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterContentChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterViewInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterViewChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngOnDestroy', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['sub destroy']);
});
}); | {
"end_byte": 126014,
"start_byte": 116570,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_126020_134707 | describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
standalone: false,
})
class SuperComponent {
@Input() foo = '';
@Input() bar = '';
@Input() baz = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
@Input() override baz = '';
@Input() qux = '';
}
@Component({
template: `<my-comp [foo]="a" [bar]="b" [baz]="c" [qux]="d"></my-comp>`,
standalone: false,
})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir: MyComponent = fixture.debugElement.query(
By.directive(MyComponent),
).componentInstance;
expect(subDir.foo).toEqual('a');
expect(subDir.bar).toEqual('b');
expect(subDir.baz).toEqual('c');
expect(subDir.qux).toEqual('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
standalone: false,
})
class SuperComponent {
@Output() foo = new EventEmitter<string>();
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<my-comp (foo)="handleFoo($event)"></my-comp>
`,
standalone: false,
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('animations', () => {
it('should work with inherited host bindings and animations', () => {
@Component({
selector: 'super-comp',
template: '<div>super-comp</div>',
host: {
'[@animation]': 'colorExp',
},
animations: [trigger('animation', [state('color', style({color: 'red'}))])],
standalone: false,
})
class SuperComponent {
colorExp = 'color';
}
@Component({
selector: 'my-comp',
template: `<div>my-comp</div>`,
standalone: false,
})
class MyComponent extends SuperComponent {}
@Component({
template: '<my-comp>app</my-comp>',
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent],
imports: [NoopAnimationsModule],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.css('my-comp'));
expect(queryResult.nativeElement.style.color).toBe('red');
});
it('should compose animations (from super class)', () => {
@Component({
selector: 'super-comp',
template: '...',
animations: [
trigger('animation1', [state('color', style({color: 'red'}))]),
trigger('animation2', [state('opacity', style({opacity: '0.5'}))]),
],
standalone: false,
})
class SuperComponent {}
@Component({
selector: 'my-comp',
template: '<div>my-comp</div>',
host: {
'[@animation1]': 'colorExp',
'[@animation2]': 'opacityExp',
'[@animation3]': 'bgExp',
},
animations: [
trigger('animation1', [state('color', style({color: 'blue'}))]),
trigger('animation3', [state('bg', style({backgroundColor: 'green'}))]),
],
standalone: false,
})
class MyComponent extends SuperComponent {
colorExp = 'color';
opacityExp = 'opacity';
bgExp = 'bg';
}
@Component({
template: '<my-comp>app</my-comp>',
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent],
imports: [NoopAnimationsModule],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.css('my-comp'));
expect(queryResult.nativeElement.style.color).toBe('blue');
expect(queryResult.nativeElement.style.opacity).toBe('0.5');
expect(queryResult.nativeElement.style.backgroundColor).toBe('green');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
standalone: false,
})
class SuperComponent {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {}
@Component({
template: `
<my-comp>test</my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
standalone: false,
})
class SuperComponent {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {}
@Component({
template: `
<my-comp superTitle="test">test</my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.title).toBe('test!!!');
});
}); | {
"end_byte": 134707,
"start_byte": 126020,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_134713_141054 | it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({
selector: '[child-dir]',
standalone: false,
})
class ChildDir {}
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
standalone: false,
})
class SuperComponent {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({
selector: 'my-comp',
template: `<ul><ng-content></ng-content></ul>`,
standalone: false,
})
class MyComponent extends SuperComponent {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp>
<li child-dir>one</li>
<li child-dir>two</li>
</my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent, ChildDir],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
it('should inherit ViewChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({
selector: '[child-dir]',
standalone: false,
})
class ChildDir {}
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
standalone: false,
})
class SuperComponent {
@ViewChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({
selector: 'my-comp',
template: `
<ul>
<li child-dir *ngFor="let item of items">{{item}}</li>
</ul>
`,
standalone: false,
})
class MyComponent extends SuperComponent {
items = [1, 2, 3, 4, 5];
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp></my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(5);
});
it('should inherit host listeners from base class once', () => {
const events: string[] = [];
@Component({
selector: 'app-base',
template: 'base',
standalone: false,
})
class BaseComponent {
@HostListener('click')
clicked() {
events.push('BaseComponent.clicked');
}
}
@Component({
selector: 'app-child',
template: 'child',
standalone: false,
})
class ChildComponent extends BaseComponent {
// additional host listeners are defined here to have `hostBindings` function generated on
// component def, which would trigger `hostBindings` functions merge operation in
// InheritDefinitionFeature logic (merging Child and Base host binding functions)
@HostListener('focus')
focused() {}
override clicked() {
events.push('ChildComponent.clicked');
}
}
@Component({
selector: 'app-grand-child',
template: 'grand-child',
standalone: false,
})
class GrandChildComponent extends ChildComponent {
// additional host listeners are defined here to have `hostBindings` function generated on
// component def, which would trigger `hostBindings` functions merge operation in
// InheritDefinitionFeature logic (merging GrandChild and Child host binding functions)
@HostListener('blur')
blurred() {}
override clicked() {
events.push('GrandChildComponent.clicked');
}
}
@Component({
selector: 'root-app',
template: `
<app-base></app-base>
<app-child></app-child>
<app-grand-child></app-grand-child>
`,
standalone: false,
})
class RootApp {}
const components = [BaseComponent, ChildComponent, GrandChildComponent];
TestBed.configureTestingModule({
declarations: [RootApp, ...components],
});
const fixture = TestBed.createComponent(RootApp);
fixture.detectChanges();
components.forEach((component) => {
fixture.debugElement.query(By.directive(component)).nativeElement.click();
});
expect(events).toEqual([
'BaseComponent.clicked',
'ChildComponent.clicked',
'GrandChildComponent.clicked',
]);
});
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
}); | {
"end_byte": 141054,
"start_byte": 134713,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_141058_149957 | describe('of a component inherited by a bare class then by a component', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
standalone: false,
})
class SuperSuperComponent {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
class SuperComponent extends SuperSuperComponent {}
beforeEach(() => (fired.length = 0));
it('ngOnInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngDoCheck', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterContentInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterContentChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterViewInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngAfterViewChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['super destroy']);
});
it('ngOnDestroy', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
standalone: false,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual(['sub destroy']);
});
}); | {
"end_byte": 149957,
"start_byte": 141058,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_149963_158868 | describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
standalone: false,
})
class SuperSuperComponent {
@Input() foo = '';
@Input() baz = '';
}
class BareClass extends SuperSuperComponent {
@Input() bar = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends BareClass {
@Input() override baz = '';
@Input() qux = '';
}
@Component({
template: `<my-comp [foo]="a" [bar]="b" [baz]="c" [qux]="d"></my-comp>`,
standalone: false,
})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperSuperComponent, BareClass],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const myComp: MyComponent = fixture.debugElement.query(
By.directive(MyComponent),
).componentInstance;
expect(myComp.foo).toEqual('a');
expect(myComp.bar).toEqual('b');
expect(myComp.baz).toEqual('c');
expect(myComp.qux).toEqual('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
standalone: false,
})
class SuperSuperComponent {
@Output() foo = new EventEmitter<string>();
}
class SuperComponent extends SuperSuperComponent {
@Output() bar = new EventEmitter<string>();
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {
ngOnInit() {
this.foo.emit('test1');
this.bar.emit('test2');
}
}
@Component({
template: `
<my-comp (foo)="handleFoo($event)" (bar)="handleBar($event)"></my-comp>
`,
standalone: false,
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
bar = '';
handleBar(event: string) {
this.bar = event;
}
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent, SuperSuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test1');
expect(app.bar).toBe('test2');
});
});
describe('animations', () => {
it('should compose animations across multiple inheritance levels', () => {
@Component({
selector: 'super-comp',
template: '...',
host: {
'[@animation1]': 'colorExp',
'[@animation2]': 'opacityExp',
},
animations: [
trigger('animation1', [state('color', style({color: 'red'}))]),
trigger('animation2', [state('opacity', style({opacity: '0.5'}))]),
],
standalone: false,
})
class SuperComponent {
colorExp = 'color';
opacityExp = 'opacity';
}
@Component({
selector: 'intermediate-comp',
template: '...',
standalone: false,
})
class IntermediateComponent extends SuperComponent {}
@Component({
selector: 'my-comp',
template: '<div>my-comp</div>',
host: {
'[@animation1]': 'colorExp',
'[@animation3]': 'bgExp',
},
animations: [
trigger('animation1', [state('color', style({color: 'blue'}))]),
trigger('animation3', [state('bg', style({backgroundColor: 'green'}))]),
],
standalone: false,
})
class MyComponent extends IntermediateComponent {
override colorExp = 'color';
override opacityExp = 'opacity';
bgExp = 'bg';
}
@Component({
template: '<my-comp>app</my-comp>',
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent, IntermediateComponent, SuperComponent],
imports: [NoopAnimationsModule],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.css('my-comp'));
expect(queryResult.nativeElement.style.color).toBe('blue');
expect(queryResult.nativeElement.style.opacity).toBe('0.5');
expect(queryResult.nativeElement.style.backgroundColor).toBe('green');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
standalone: false,
})
class SuperSuperComponent {
@HostBinding('style.color') color = 'red';
}
class SuperComponent extends SuperSuperComponent {
@HostBinding('style.backgroundColor') bg = 'black';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {}
@Component({
template: `
<my-comp>test</my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent, SuperSuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
standalone: false,
})
class SuperSuperComponent {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
class SuperComponent extends SuperSuperComponent {
@HostBinding('accessKey')
get boundAccessKey() {
return this.superAccessKey + '???';
}
@Input() superAccessKey = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
standalone: false,
})
class MyComponent extends SuperComponent {}
@Component({
template: `
<my-comp superTitle="test1" superAccessKey="test2">test</my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent, SuperSuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.title).toBe('test1!!!');
expect(queryResult.nativeElement.accessKey).toBe('test2???');
});
}); | {
"end_byte": 158868,
"start_byte": 149963,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/inherit_definition_feature_spec.ts_158874_162836 | it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({
selector: '[child-dir]',
standalone: false,
})
class ChildDir {}
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
standalone: false,
})
class SuperComponent {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({
selector: 'my-comp',
template: `<ul><ng-content></ng-content></ul>`,
standalone: false,
})
class MyComponent extends SuperComponent {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp>
<li child-dir>one</li>
<li child-dir>two</li>
</my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent, ChildDir],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
it('should inherit ViewChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({
selector: '[child-dir]',
standalone: false,
})
class ChildDir {}
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
standalone: false,
})
class SuperComponent {
@ViewChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({
selector: 'my-comp',
template: `
<ul>
<li child-dir *ngFor="let item of items">{{item}}</li>
</ul>
`,
standalone: false,
})
class MyComponent extends SuperComponent {
items = [1, 2, 3, 4, 5];
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp></my-comp>
`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(5);
});
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
}); | {
"end_byte": 162836,
"start_byte": 158874,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/inherit_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/change_detection_signals_in_zones_spec.ts_0_5858 | /**
* @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 {NgFor, NgIf} from '@angular/common';
import {
ApplicationRef,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
computed,
Directive,
ElementRef,
inject,
Input,
signal,
TemplateRef,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import {ReactiveNode, SIGNAL} from '@angular/core/primitives/signals';
import {TestBed} from '@angular/core/testing';
describe('CheckAlways components', () => {
it('can read a signal', () => {
@Component({
template: `{{value()}}`,
standalone: true,
})
class CheckAlwaysCmp {
value = signal('initial');
}
const fixture = TestBed.createComponent(CheckAlwaysCmp);
const instance = fixture.componentInstance;
fixture.detectChanges();
expect(fixture.nativeElement.textContent.trim()).toEqual('initial');
instance.value.set('new');
fixture.detectChanges();
expect(instance.value()).toBe('new');
});
it('should properly remove stale dependencies from the signal graph', () => {
@Component({
template: `{{show() ? name() + ' aged ' + age() : 'anonymous'}}`,
standalone: true,
})
class CheckAlwaysCmp {
name = signal('John');
age = signal(25);
show = signal(true);
}
const fixture = TestBed.createComponent(CheckAlwaysCmp);
const instance = fixture.componentInstance;
fixture.detectChanges();
expect(fixture.nativeElement.textContent.trim()).toEqual('John aged 25');
instance.show.set(false);
fixture.detectChanges();
expect(fixture.nativeElement.textContent.trim()).toEqual('anonymous');
instance.name.set('Bob');
fixture.detectChanges();
expect(fixture.nativeElement.textContent.trim()).toEqual('anonymous');
instance.show.set(true);
fixture.detectChanges();
expect(fixture.nativeElement.textContent.trim()).toEqual('Bob aged 25');
});
it('is not "shielded" by a non-dirty OnPush parent', () => {
const value = signal('initial');
@Component({
template: `{{value()}}`,
standalone: true,
selector: 'check-always',
})
class CheckAlwaysCmp {
value = value;
}
@Component({
template: `<check-always />`,
standalone: true,
imports: [CheckAlwaysCmp],
changeDetection: ChangeDetectionStrategy.OnPush,
})
class OnPushParent {}
const fixture = TestBed.createComponent(OnPushParent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent.trim()).toEqual('initial');
value.set('new');
fixture.detectChanges();
expect(fixture.nativeElement.textContent.trim()).toBe('new');
});
it('continues to refresh views until none are dirty', () => {
const aVal = signal('initial');
const bVal = signal('initial');
let updateAValDuringAChangeDetection = false;
@Component({
template: '{{val()}}',
standalone: true,
selector: 'a-comp',
})
class A {
val = aVal;
}
@Component({
template: '{{val()}}',
standalone: true,
selector: 'b-comp',
})
class B {
val = bVal;
ngAfterViewChecked() {
// Set value in parent view after this view is checked
// Without signals, this is ExpressionChangedAfterItWasChecked
if (updateAValDuringAChangeDetection) {
aVal.set('new');
}
}
}
@Component({template: '<a-comp />-<b-comp />', standalone: true, imports: [A, B]})
class App {}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.nativeElement.innerText).toContain('initial-initial');
bVal.set('new');
fixture.detectChanges();
expect(fixture.nativeElement.innerText).toContain('initial-new');
updateAValDuringAChangeDetection = true;
bVal.set('newer');
fixture.detectChanges();
expect(fixture.nativeElement.innerText).toContain('new-newer');
});
it('refreshes root view until it is no longer dirty', () => {
const val = signal(0);
let incrementAfterCheckedUntil = 0;
@Component({
template: '',
selector: 'child',
standalone: true,
})
class Child {
ngDoCheck() {
// Update signal in parent view every time we check the child view
// (ExpressionChangedAfterItWasCheckedError but not for signals)
if (val() < incrementAfterCheckedUntil) {
val.update((v) => ++v);
}
}
}
@Component({template: '{{val()}}<child />', standalone: true, imports: [Child]})
class App {
val = val;
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.nativeElement.innerText).toContain('0');
incrementAfterCheckedUntil = 10;
fixture.detectChanges();
expect(fixture.nativeElement.innerText).toContain('10');
incrementAfterCheckedUntil = Number.MAX_SAFE_INTEGER;
expect(() => fixture.detectChanges()).toThrowError(/Infinite/);
});
it('refreshes all views attached to ApplicationRef until no longer dirty', () => {
const val = signal(0);
@Component({
template: '{{val()}}',
standalone: true,
})
class App {
val = val;
ngOnInit() {
this.val.update((v) => v + 1);
}
}
const fixture = TestBed.createComponent(App);
const fixture2 = TestBed.createComponent(App);
const appRef = TestBed.inject(ApplicationRef);
appRef.attachView(fixture.componentRef.hostView);
appRef.attachView(fixture2.componentRef.hostView);
appRef.tick();
expect(fixture.nativeElement.innerText).toEqual('2');
expect(fixture2.nativeElement.innerText).toEqual('2');
});
}); | {
"end_byte": 5858,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_signals_in_zones_spec.ts"
} |
angular/packages/core/test/acceptance/change_detection_signals_in_zones_spec.ts_5860_14927 | describe('OnPush components with signals', () => {
it('marks view dirty', () => {
@Component({
template: `{{value()}}{{incrementTemplateExecutions()}}`,
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
})
class OnPushCmp {
numTemplateExecutions = 0;
value = signal('initial');
incrementTemplateExecutions() {
this.numTemplateExecutions++;
return '';
}
}
const fixture = TestBed.createComponent(OnPushCmp);
const instance = fixture.componentInstance;
fixture.detectChanges();
expect(instance.numTemplateExecutions).toBe(1);
expect(fixture.nativeElement.textContent.trim()).toEqual('initial');
fixture.detectChanges();
// Should not be dirty, should not execute template
expect(instance.numTemplateExecutions).toBe(1);
instance.value.set('new');
fixture.detectChanges();
expect(instance.numTemplateExecutions).toBe(2);
expect(instance.value()).toBe('new');
});
it("does not refresh a component when a signal notifies but isn't actually updated", () => {
@Component({
template: `{{memo()}}{{incrementTemplateExecutions()}}`,
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
})
class OnPushCmp {
numTemplateExecutions = 0;
value = signal({value: 'initial'});
memo = computed(() => this.value().value, {equal: Object.is});
incrementTemplateExecutions() {
this.numTemplateExecutions++;
return '';
}
}
const fixture = TestBed.createComponent(OnPushCmp);
const instance = fixture.componentInstance;
fixture.detectChanges();
expect(instance.numTemplateExecutions).toBe(1);
expect(fixture.nativeElement.textContent.trim()).toEqual('initial');
instance.value.update((v) => ({...v}));
fixture.detectChanges();
expect(instance.numTemplateExecutions).toBe(1);
instance.value.update((v) => ({value: 'new'}));
fixture.detectChanges();
expect(instance.numTemplateExecutions).toBe(2);
expect(fixture.nativeElement.textContent.trim()).toEqual('new');
});
it('should not mark components as dirty when signal is read in a constructor of a child component', () => {
const state = signal('initial');
@Component({
selector: 'child',
template: `child`,
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
})
class ChildReadingSignalCmp {
constructor() {
state();
}
}
@Component({
template: `
{{incrementTemplateExecutions()}}
<!-- Template constructed to execute child component constructor in the update pass of a host component -->
<ng-template [ngIf]="true"><child></child></ng-template>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [NgIf, ChildReadingSignalCmp],
})
class OnPushCmp {
numTemplateExecutions = 0;
incrementTemplateExecutions() {
this.numTemplateExecutions++;
return '';
}
}
const fixture = TestBed.createComponent(OnPushCmp);
const instance = fixture.componentInstance;
fixture.detectChanges();
expect(instance.numTemplateExecutions).toBe(1);
expect(fixture.nativeElement.textContent.trim()).toEqual('child');
// The "state" signal is not accesses in the template's update function anywhere so it
// shouldn't mark components as dirty / impact change detection.
state.set('new');
fixture.detectChanges();
expect(instance.numTemplateExecutions).toBe(1);
});
it('should not mark components as dirty when signal is read in an input of a child component', () => {
const state = signal('initial');
@Component({
selector: 'with-input-setter',
standalone: true,
template: '{{test}}',
})
class WithInputSetter {
test = '';
@Input()
set testInput(newValue: string) {
this.test = state() + ':' + newValue;
}
}
@Component({
template: `
{{incrementTemplateExecutions()}}
<!-- Template constructed to execute child component constructor in the update pass of a host component -->
<ng-template [ngIf]="true"><with-input-setter [testInput]="'input'" /></ng-template>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [NgIf, WithInputSetter],
})
class OnPushCmp {
numTemplateExecutions = 0;
incrementTemplateExecutions() {
this.numTemplateExecutions++;
return '';
}
}
const fixture = TestBed.createComponent(OnPushCmp);
const instance = fixture.componentInstance;
fixture.detectChanges();
expect(instance.numTemplateExecutions).toBe(1);
expect(fixture.nativeElement.textContent.trim()).toEqual('initial:input');
// The "state" signal is not accesses in the template's update function anywhere so it
// shouldn't mark components as dirty / impact change detection.
state.set('new');
fixture.detectChanges();
expect(instance.numTemplateExecutions).toBe(1);
expect(fixture.nativeElement.textContent.trim()).toEqual('initial:input');
});
it('should not mark components as dirty when signal is read in a query result setter', () => {
const state = signal('initial');
@Component({
selector: 'with-query-setter',
standalone: true,
template: '<div #el>child</div>',
})
class WithQuerySetter {
el: unknown;
@ViewChild('el', {static: true})
set elQuery(result: unknown) {
// read a signal in a setter
state();
this.el = result;
}
}
@Component({
template: `
{{incrementTemplateExecutions()}}
<!-- Template constructed to execute child component constructor in the update pass of a host component -->
<ng-template [ngIf]="true"><with-query-setter /></ng-template>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [NgIf, WithQuerySetter],
})
class OnPushCmp {
numTemplateExecutions = 0;
incrementTemplateExecutions() {
this.numTemplateExecutions++;
return '';
}
}
const fixture = TestBed.createComponent(OnPushCmp);
const instance = fixture.componentInstance;
fixture.detectChanges();
expect(instance.numTemplateExecutions).toBe(1);
expect(fixture.nativeElement.textContent.trim()).toEqual('child');
// The "state" signal is not accesses in the template's update function anywhere so it
// shouldn't mark components as dirty / impact change detection.
state.set('new');
fixture.detectChanges();
expect(instance.numTemplateExecutions).toBe(1);
});
it('can read a signal in a host binding in root view', () => {
const useBlue = signal(false);
@Component({
template: `{{incrementTemplateExecutions()}}`,
selector: 'child',
host: {'[class.blue]': 'useBlue()'},
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
})
class MyCmp {
useBlue = useBlue;
numTemplateExecutions = 0;
incrementTemplateExecutions() {
this.numTemplateExecutions++;
return '';
}
}
const fixture = TestBed.createComponent(MyCmp);
fixture.detectChanges();
expect(fixture.nativeElement.outerHTML).not.toContain('blue');
expect(fixture.componentInstance.numTemplateExecutions).toBe(1);
useBlue.set(true);
fixture.detectChanges();
expect(fixture.nativeElement.outerHTML).toContain('blue');
expect(fixture.componentInstance.numTemplateExecutions).toBe(1);
});
it('can read a signal in a host binding', () => {
@Component({
template: `{{incrementTemplateExecutions()}}`,
selector: 'child',
host: {'[class.blue]': 'useBlue()'},
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
})
class ChildCmp {
useBlue = signal(false);
numTemplateExecutions = 0;
incrementTemplateExecutions() {
this.numTemplateExecutions++;
return '';
}
}
@Component({
template: `<child />`,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [ChildCmp],
standalone: true,
})
class ParentCmp {}
const fixture = TestBed.createComponent(ParentCmp);
const child = fixture.debugElement.query((p) => p.componentInstance instanceof ChildCmp);
const childInstance = child.componentInstance as ChildCmp;
fixture.detectChanges();
expect(childInstance.numTemplateExecutions).toBe(1);
expect(child.nativeElement.outerHTML).not.toContain('blue');
childInstance.useBlue.set(true);
fixture.detectChanges();
// We should not re-execute the child template. It didn't change, the host bindings did.
expect(childInstance.numTemplateExecutions).toBe(1);
expect(child.nativeElement.outerHTML).toContain('blue');
}); | {
"end_byte": 14927,
"start_byte": 5860,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_signals_in_zones_spec.ts"
} |
angular/packages/core/test/acceptance/change_detection_signals_in_zones_spec.ts_14931_19959 | it('can have signals in both template and host bindings', () => {
@Component({
template: ``,
selector: 'child',
host: {'[class.blue]': 'useBlue()'},
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
})
class ChildCmp {
useBlue = signal(false);
}
@Component({
template: `<child /> {{parentSignalValue()}}`,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [ChildCmp],
standalone: true,
selector: 'parent',
})
class ParentCmp {
parentSignalValue = signal('initial');
}
// Wrapper component so we can effectively test ParentCmp being marked dirty
@Component({
template: `<parent />`,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [ParentCmp],
standalone: true,
})
class TestWrapper {}
const fixture = TestBed.createComponent(TestWrapper);
const parent = fixture.debugElement.query((p) => p.componentInstance instanceof ParentCmp)
.componentInstance as ParentCmp;
const child = fixture.debugElement.query((p) => p.componentInstance instanceof ChildCmp)
.componentInstance as ChildCmp;
fixture.detectChanges();
expect(fixture.nativeElement.outerHTML).toContain('initial');
expect(fixture.nativeElement.outerHTML).not.toContain('blue');
child.useBlue.set(true);
fixture.detectChanges();
expect(fixture.nativeElement.outerHTML).toContain('blue');
// Set the signal in the parent again and ensure it gets updated
parent.parentSignalValue.set('new');
fixture.detectChanges();
expect(fixture.nativeElement.outerHTML).toContain('new');
// Set the signal in the child host binding again and ensure it is still updated
child.useBlue.set(false);
fixture.detectChanges();
expect(fixture.nativeElement.outerHTML).not.toContain('blue');
});
it('should be able to write to signals during change-detecting a given template, in advance()', () => {
const counter = signal(0);
@Directive({
standalone: true,
selector: '[misunderstood]',
})
class MisunderstoodDir {
ngOnInit(): void {
counter.update((c) => c + 1);
}
}
@Component({
selector: 'test-component',
standalone: true,
imports: [MisunderstoodDir],
template: `
{{counter()}}<div misunderstood></div>{{ 'force advance()' }}
`,
})
class TestCmp {
counter = counter;
}
const fixture = TestBed.createComponent(TestCmp);
// CheckNoChanges should not throw ExpressionChanged error
// and signal value is updated to latest value with 1 `detectChanges`
fixture.detectChanges();
expect(fixture.nativeElement.innerText).toContain('1');
expect(fixture.nativeElement.innerText).toContain('force advance()');
});
it('should allow writing to signals during change-detecting a given template, at the end', () => {
const counter = signal(0);
@Directive({
standalone: true,
selector: '[misunderstood]',
})
class MisunderstoodDir {
ngOnInit(): void {
counter.update((c) => c + 1);
}
}
@Component({
selector: 'test-component',
standalone: true,
imports: [MisunderstoodDir],
template: `
{{counter()}}<div misunderstood></div>
`,
})
class TestCmp {
counter = counter;
}
const fixture = TestBed.createComponent(TestCmp);
// CheckNoChanges should not throw ExpressionChanged error
// and signal value is updated to latest value with 1 `detectChanges`
fixture.detectChanges();
expect(fixture.nativeElement.innerText).toBe('1');
});
it('should allow writing to signals in afterViewInit', () => {
@Component({
template: '{{loading()}}',
standalone: true,
})
class MyComp {
loading = signal(true);
// Classic example of what would have caused ExpressionChanged...Error
ngAfterViewInit() {
this.loading.set(false);
}
}
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.nativeElement.innerText).toBe('false');
});
it('does not refresh view if signal marked dirty but did not change', () => {
const val = signal('initial', {equal: () => true});
@Component({
template: '{{val()}}{{incrementChecks()}}',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
})
class App {
val = val;
templateExecutions = 0;
incrementChecks() {
this.templateExecutions++;
}
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.templateExecutions).toBe(1);
expect(fixture.nativeElement.innerText).toContain('initial');
val.set('new');
fixture.detectChanges();
expect(fixture.componentInstance.templateExecutions).toBe(1);
expect(fixture.nativeElement.innerText).toContain('initial');
}); | {
"end_byte": 19959,
"start_byte": 14931,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_signals_in_zones_spec.ts"
} |
angular/packages/core/test/acceptance/change_detection_signals_in_zones_spec.ts_19963_27052 | describe('embedded views', () => {
describe('with a signal read after view creation during an update pass', () => {
it('should work with native control flow', () => {
@Component({
template: `
@if (true) { }
{{val()}}
`,
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
})
class MyComp {
val = signal('initial');
}
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
fixture.componentInstance.val.set('new');
fixture.detectChanges();
expect(fixture.nativeElement.innerText).toBe('new');
});
it('should work with createEmbeddedView', () => {
@Component({
template: `
<ng-template #template></ng-template>
{{createEmbeddedView(template)}}
{{val()}}
`,
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
})
class MyComp {
val = signal('initial');
vcr = inject(ViewContainerRef);
createEmbeddedView(ref: TemplateRef<{}>) {
this.vcr.createEmbeddedView(ref);
}
}
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
fixture.componentInstance.val.set('new');
fixture.detectChanges();
expect(fixture.nativeElement.innerText).toBe('new');
});
});
it('refreshes an embedded view in a component', () => {
@Component({
selector: 'signal-component',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [NgIf],
template: `<div *ngIf="true"> {{value()}} </div>`,
})
class SignalComponent {
value = signal('initial');
}
const fixture = TestBed.createComponent(SignalComponent);
fixture.detectChanges();
fixture.componentInstance.value.set('new');
fixture.detectChanges();
expect(trim(fixture.nativeElement.textContent)).toEqual('new');
});
it('refreshes multiple embedded views in a component', () => {
@Component({
selector: 'signal-component',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [NgFor],
template: `<div *ngFor="let i of [1,2,3]"> {{value()}} </div>`,
})
class SignalComponent {
value = signal('initial');
}
const fixture = TestBed.createComponent(SignalComponent);
fixture.detectChanges();
fixture.componentInstance.value.set('new');
fixture.detectChanges();
expect(trim(fixture.nativeElement.textContent)).toEqual('new new new');
});
it('refreshes entire component, including embedded views, when signal updates', () => {
@Component({
selector: 'signal-component',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [NgIf],
template: `
{{componentSignal()}}
<div *ngIf="true"> {{incrementExecutions()}} </div>
`,
})
class SignalComponent {
embeddedViewExecutions = 0;
componentSignal = signal('initial');
incrementExecutions() {
this.embeddedViewExecutions++;
return '';
}
}
const fixture = TestBed.createComponent(SignalComponent);
fixture.detectChanges();
expect(fixture.componentInstance.embeddedViewExecutions).toEqual(1);
fixture.componentInstance.componentSignal.set('new');
fixture.detectChanges();
expect(trim(fixture.nativeElement.textContent)).toEqual('new');
// OnPush/Default components are checked as a whole so the embedded view is also checked again
expect(fixture.componentInstance.embeddedViewExecutions).toEqual(2);
});
it('re-executes deep embedded template if signal updates', () => {
@Component({
selector: 'signal-component',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [NgIf],
template: `
<div *ngIf="true">
<div *ngIf="true">
<div *ngIf="true">
{{value()}}
</div>
</div>
</div>
`,
})
class SignalComponent {
value = signal('initial');
}
const fixture = TestBed.createComponent(SignalComponent);
fixture.detectChanges();
fixture.componentInstance.value.set('new');
fixture.detectChanges();
expect(trim(fixture.nativeElement.textContent)).toEqual('new');
});
it('tracks signal updates if embedded view is change detected directly', () => {
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ng-template #template>{{value()}}</ng-template>
`,
standalone: true,
})
class Test {
value = signal('initial');
@ViewChild('template', {static: true, read: TemplateRef})
template!: TemplateRef<{}>;
@ViewChild('template', {static: true, read: ViewContainerRef})
vcr!: ViewContainerRef;
}
const fixture = TestBed.createComponent(Test);
const appRef = TestBed.inject(ApplicationRef);
appRef.attachView(fixture.componentRef.hostView);
appRef.tick();
const viewRef = fixture.componentInstance.vcr.createEmbeddedView(
fixture.componentInstance.template,
);
viewRef.detectChanges();
expect(fixture.nativeElement.innerText).toContain('initial');
fixture.componentInstance.value.set('new');
appRef.tick();
expect(fixture.nativeElement.innerText).toContain('new');
});
it('tracks signal updates if embedded view is change detected directly before attaching', () => {
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ng-template #template>{{value()}}</ng-template>
`,
standalone: true,
})
class Test {
value = signal('initial');
@ViewChild('template', {static: true, read: TemplateRef})
template!: TemplateRef<{}>;
@ViewChild('template', {static: true, read: ViewContainerRef})
vcr!: ViewContainerRef;
element = inject(ElementRef);
}
const fixture = TestBed.createComponent(Test);
const appRef = TestBed.inject(ApplicationRef);
appRef.attachView(fixture.componentRef.hostView);
appRef.tick();
const viewRef = fixture.componentInstance.template.createEmbeddedView(
fixture.componentInstance.template,
);
fixture.componentInstance.element.nativeElement.appendChild(viewRef.rootNodes[0]);
viewRef.detectChanges();
expect(fixture.nativeElement.innerText).toContain('initial');
fixture.componentInstance.vcr.insert(viewRef);
fixture.componentInstance.value.set('new');
appRef.tick();
expect(fixture.nativeElement.innerText).toContain('new');
});
}); | {
"end_byte": 27052,
"start_byte": 19963,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_signals_in_zones_spec.ts"
} |
angular/packages/core/test/acceptance/change_detection_signals_in_zones_spec.ts_27056_32487 | describe('shielded by non-dirty OnPush', () => {
@Component({
selector: 'signal-component',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
template: `{{value()}}`,
})
class SignalComponent {
value = signal('initial');
afterViewCheckedRuns = 0;
constructor(readonly cdr: ChangeDetectorRef) {}
ngAfterViewChecked() {
this.afterViewCheckedRuns++;
}
}
@Component({
selector: 'on-push-parent',
template: `
<signal-component></signal-component>
{{incrementChecks()}}`,
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [SignalComponent],
})
class OnPushParent {
@ViewChild(SignalComponent) signalChild!: SignalComponent;
viewExecutions = 0;
constructor(readonly cdr: ChangeDetectorRef) {}
incrementChecks() {
this.viewExecutions++;
}
}
it('refreshes when signal changes, but does not refresh non-dirty parent', () => {
const fixture = TestBed.createComponent(OnPushParent);
fixture.detectChanges();
expect(fixture.componentInstance.viewExecutions).toEqual(1);
fixture.componentInstance.signalChild.value.set('new');
fixture.detectChanges();
expect(fixture.componentInstance.viewExecutions).toEqual(1);
expect(trim(fixture.nativeElement.textContent)).toEqual('new');
});
it('does not refresh when detached', () => {
const fixture = TestBed.createComponent(OnPushParent);
fixture.detectChanges();
fixture.componentInstance.signalChild.value.set('new');
fixture.componentInstance.signalChild.cdr.detach();
fixture.detectChanges();
expect(trim(fixture.nativeElement.textContent)).toEqual('initial');
});
it('refreshes when reattached if already dirty', () => {
const fixture = TestBed.createComponent(OnPushParent);
fixture.detectChanges();
fixture.componentInstance.signalChild.value.set('new');
fixture.componentInstance.signalChild.cdr.detach();
fixture.detectChanges();
expect(trim(fixture.nativeElement.textContent)).toEqual('initial');
fixture.componentInstance.signalChild.cdr.reattach();
fixture.detectChanges();
expect(trim(fixture.nativeElement.textContent)).toEqual('new');
});
// Note: Design decision for signals because that's how the hooks work today
// We have considered actually running a component's `afterViewChecked` hook if it's refreshed
// in targeted mode (meaning the parent did not refresh) and could change this decision.
it('does not run afterViewChecked hooks because parent view was not dirty (those hooks are executed by the parent)', () => {
const fixture = TestBed.createComponent(OnPushParent);
fixture.detectChanges();
// hook run once on initialization
expect(fixture.componentInstance.signalChild.afterViewCheckedRuns).toBe(1);
fixture.componentInstance.signalChild.value.set('new');
fixture.detectChanges();
expect(trim(fixture.nativeElement.textContent)).toEqual('new');
// hook did not run again because host view was not refreshed
expect(fixture.componentInstance.signalChild.afterViewCheckedRuns).toBe(1);
});
});
it('can refresh the root of change detection if updated after checked', () => {
const val = signal(1);
@Component({
template: '',
selector: 'child',
standalone: true,
})
class Child {
ngOnInit() {
val.set(2);
}
}
@Component({
template: '{{val()}} <child />',
imports: [Child],
standalone: true,
})
class SignalComponent {
val = val;
cdr = inject(ChangeDetectorRef);
}
const fixture = TestBed.createComponent(SignalComponent);
fixture.componentInstance.cdr.detectChanges();
expect(fixture.nativeElement.innerText).toEqual('2');
});
it('destroys all signal consumers when destroying the view tree', () => {
const val = signal(1);
const double = computed(() => val() * 2);
@Component({
template: '{{double()}}',
selector: 'child',
standalone: true,
})
class Child {
double = double;
}
@Component({
template: '|{{double()}}|<child />|',
imports: [Child],
standalone: true,
})
class SignalComponent {
double = double;
}
const fixture = TestBed.createComponent(SignalComponent);
fixture.detectChanges();
expect(fixture.nativeElement.innerText).toEqual('|2|2|');
const node = double[SIGNAL] as ReactiveNode;
expect(node.dirty).toBe(false);
// Change the signal to verify that the computed is dirtied while being read from the template.
val.set(2);
expect(node.dirty).toBe(true);
fixture.detectChanges();
expect(node.dirty).toBe(false);
expect(fixture.nativeElement.innerText).toEqual('|4|4|');
// Destroy the view tree to verify that the computed is unconnected from the graph for all
// views.
fixture.destroy();
expect(node.dirty).toBe(false);
// Writing further updates to the signal should not cause the computed to become dirty, since it
// is no longer being observed.
val.set(3);
expect(node.dirty).toBe(false);
});
});
function trim(text: string | null): string {
return text ? text.replace(/[\s\n]+/gm, ' ').trim() : '';
} | {
"end_byte": 32487,
"start_byte": 27056,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/change_detection_signals_in_zones_spec.ts"
} |
angular/packages/core/test/acceptance/control_flow_switch_spec.ts_0_6410 | /**
* @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 {ChangeDetectorRef, Component, inject, Pipe, PipeTransform} from '@angular/core';
import {TestBed} from '@angular/core/testing';
// Basic shared pipe used during testing.
@Pipe({name: 'multiply', pure: true, standalone: true})
class MultiplyPipe implements PipeTransform {
transform(value: number, amount: number) {
return value * amount;
}
}
describe('control flow - switch', () => {
it('should show a template based on a matching case', () => {
@Component({
standalone: true,
template: `
@switch (case) {
@case (0) {case 0}
@case (1) {case 1}
@default {default}
}
`,
})
class TestComponent {
case = 0;
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('case 0');
fixture.componentInstance.case = 1;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('case 1');
fixture.componentInstance.case = 5;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('default');
});
it('should be able to use a pipe in the switch expression', () => {
@Component({
standalone: true,
imports: [MultiplyPipe],
template: `
@switch (case | multiply:2) {
@case (0) {case 0}
@case (2) {case 2}
@default {default}
}
`,
})
class TestComponent {
case = 0;
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('case 0');
fixture.componentInstance.case = 1;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('case 2');
fixture.componentInstance.case = 5;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('default');
});
it('should be able to use a pipe in the case expression', () => {
@Component({
standalone: true,
imports: [MultiplyPipe],
template: `
@switch (case) {
@case (1 | multiply:2) {case 2}
@case (2 | multiply:2) {case 4}
@default {default}
}
`,
})
class TestComponent {
case = 0;
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('default');
fixture.componentInstance.case = 4;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('case 4');
fixture.componentInstance.case = 2;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('case 2');
});
it('should be able to use pipes injecting ChangeDetectorRef in switch blocks', () => {
@Pipe({name: 'test', standalone: true})
class TestPipe implements PipeTransform {
changeDetectorRef = inject(ChangeDetectorRef);
transform(value: any) {
return value;
}
}
@Component({
standalone: true,
template: `
@switch (case | test) {
@case (0 | test) {Zero}
@case (1 | test) {One}
}
`,
imports: [TestPipe],
})
class TestComponent {
case = 1;
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('One');
});
it('should project @switch cases into appropriate slots when selectors are used for all cases', () => {
@Component({
standalone: true,
selector: 'test',
template:
'case 1: (<ng-content select="[case_1]"/>), case 2: (<ng-content select="[case_2]"/>), case 3: (<ng-content select="[case_3]"/>)',
})
class TestComponent {}
@Component({
standalone: true,
imports: [TestComponent],
template: `
<test>
@switch (value) {
@case (1) {
<span case_1>value 1</span>
}
@case (2) {
<span case_2>value 2</span>
}
@case (3) {
<span case_3>value 3</span>
}
}
</test>
`,
})
class App {
value = 1;
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('case 1: (value 1), case 2: (), case 3: ()');
fixture.componentInstance.value = 2;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('case 1: (), case 2: (value 2), case 3: ()');
fixture.componentInstance.value = 3;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('case 1: (), case 2: (), case 3: (value 3)');
});
it('should project @switch cases into appropriate slots when selectors are used for some cases', () => {
@Component({
standalone: true,
selector: 'test',
template:
'case 1: (<ng-content select="[case_1]"/>), case 2: (<ng-content />), case 3: (<ng-content select="[case_3]"/>)',
})
class TestComponent {}
@Component({
standalone: true,
imports: [TestComponent],
template: `
<test>
@switch (value) {
@case (1) {
<span case_1>value 1</span>
}
@case (2) {
<span>value 2</span>
}
@case (3) {
<span case_3>value 3</span>
}
}
</test>
`,
})
class App {
value = 1;
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('case 1: (value 1), case 2: (), case 3: ()');
fixture.componentInstance.value = 2;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('case 1: (), case 2: (value 2), case 3: ()');
fixture.componentInstance.value = 3;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('case 1: (), case 2: (), case 3: (value 3)');
});
});
| {
"end_byte": 6410,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/control_flow_switch_spec.ts"
} |
angular/packages/core/test/acceptance/exports_spec.ts_0_8648 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Component,
Directive,
DoCheck,
Input,
OnChanges,
OnInit,
SimpleChanges,
Type,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
describe('exports', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
AppComp,
ComponentToReference,
DirToReference,
DirToReferenceWithPreOrderHooks,
DirWithCompInput,
],
});
});
it('should support export of DOM element', () => {
const fixture = initWithTemplate(AppComp, '<input value="one" #myInput> {{ myInput.value }}');
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('<input value="one"> one');
});
it('should support basic export of component', () => {
const fixture = initWithTemplate(
AppComp,
'<comp-to-ref #myComp></comp-to-ref> {{ myComp.name }}',
);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('<comp-to-ref></comp-to-ref> Nancy');
});
it('should work with directives with exportAs set', () => {
const fixture = initWithTemplate(AppComp, '<div dir #myDir="dir"></div> {{ myDir.name }}');
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('<div dir=""></div> Drew');
});
describe('input changes in hooks', () => {
it('should support forward reference', () => {
const fixture = initWithTemplate(
AppComp,
'<div dir-on-change #myDir="dirOnChange" [in]="true"></div> {{ myDir.name }}',
);
fixture.detectChanges();
expect(fixture.nativeElement.firstChild.title).toBe('Drew!?@'); // div element
expect(fixture.nativeElement.lastChild.textContent).toContain('Drew!?@'); // text node
});
it('should not support backward reference', () => {
expect(() => {
const fixture = initWithTemplate(
AppComp,
'{{ myDir.name }} <div dir-on-change #myDir="dirOnChange" [in]="true"></div>',
);
fixture.detectChanges();
}).toThrowError(
/ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.*AppComp/,
);
});
it('should not support reference on the same node', () => {
expect(() => {
const fixture = initWithTemplate(
AppComp,
'<div dir-on-change #myDir="dirOnChange" [in]="true" [id]="myDir.name"></div>',
);
fixture.detectChanges();
}).toThrowError(
/ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.*AppComp/,
);
});
it('should support input referenced by host binding on that directive', () => {
const fixture = initWithTemplate(
AppComp,
'<div dir-on-change #myDir="dirOnChange" [in]="true"></div>',
);
fixture.detectChanges();
expect(fixture.nativeElement.firstChild.title).toBe('Drew!?@');
});
});
it('should throw if export name is not found', () => {
expect(() => {
const fixture = initWithTemplate(AppComp, '<div #myDir="dir"></div>');
fixture.detectChanges();
}).toThrowError(/Export of name 'dir' not found!/);
});
it('should support component instance fed into directive', () => {
const fixture = initWithTemplate(
AppComp,
'<comp-to-ref #myComp></comp-to-ref> <div [dirWithInput]="myComp"></div>',
);
fixture.detectChanges();
const myComp = fixture.debugElement.children[0].injector.get(ComponentToReference);
const dirWithInput = fixture.debugElement.children[1].injector.get(DirWithCompInput);
expect(dirWithInput.comp).toEqual(myComp);
});
it('should point to the first declared ref', () => {
const fixture = initWithTemplate(
AppComp,
`
<div>
<input value="First" #ref />
<input value="Second" #ref />
<input value="Third" #ref />
<span>{{ ref.value }}</span>
</div>
`,
);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('span').innerHTML).toBe('First');
});
describe('forward refs', () => {
it('should work with basic text bindings', () => {
const fixture = initWithTemplate(AppComp, '{{ myInput.value}} <input value="one" #myInput>');
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('one <input value="one">');
});
it('should work with element properties', () => {
const fixture = initWithTemplate(
AppComp,
'<div [title]="myInput.value"></div> <input value="one" #myInput>',
);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('<div title="one"></div><input value="one">');
});
it('should work with element attrs', () => {
const fixture = initWithTemplate(
AppComp,
'<div [attr.aria-label]="myInput.value"></div> <input value="one" #myInput>',
);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual(
'<div aria-label="one"></div><input value="one">',
);
});
it('should work with element classes', () => {
const fixture = initWithTemplate(
AppComp,
'<div [class.red]="myInput.checked"></div> <input type="checkbox" checked #myInput>',
);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toContain('<div class="red"></div>');
});
it('should work with component refs', () => {
const fixture = initWithTemplate(
AppComp,
'<div [dirWithInput]="myComp"></div><comp-to-ref #myComp></comp-to-ref>',
);
fixture.detectChanges();
const dirWithInput = fixture.debugElement.children[0].injector.get(DirWithCompInput);
const myComp = fixture.debugElement.children[1].injector.get(ComponentToReference);
expect(dirWithInput.comp).toEqual(myComp);
});
it('should work with multiple forward refs', () => {
const fixture = initWithTemplate(
AppComp,
'{{ myInput.value }} {{ myComp.name }} <comp-to-ref #myComp></comp-to-ref> <input value="one" #myInput>',
);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual(
'one Nancy <comp-to-ref></comp-to-ref><input value="one">',
);
});
it('should support local refs in nested dynamic views', () => {
const fixture = initWithTemplate(
AppComp,
`
<input value="one" #outerInput>
<div *ngIf="outer">
{{ outerInput.value }}
<input value = "two" #innerInput>
<div *ngIf="inner">
{{ outerInput.value }} - {{ innerInput.value}}
</div>
</div>
`,
);
fixture.detectChanges();
fixture.componentInstance.outer = true;
fixture.componentInstance.inner = true;
fixture.detectChanges();
// result should be <input value="one"><div>one <input value="two"><div>one - two</div></div>
// but contains bindings comments for ngIf
// so we check the outer div
expect(fixture.nativeElement.innerHTML).toContain('one <input value="two">');
// and the inner div
expect(fixture.nativeElement.innerHTML).toContain('one - two');
});
});
});
function initWithTemplate(compType: Type<any>, template: string) {
TestBed.overrideComponent(compType, {set: new Component({template})});
return TestBed.createComponent(compType);
}
@Component({
selector: 'comp-to-ref',
template: '',
standalone: false,
})
class ComponentToReference {
name = 'Nancy';
}
@Component({
selector: 'app-comp',
template: ``,
standalone: false,
})
class AppComp {
outer = false;
inner = false;
}
@Directive({
selector: '[dir]',
exportAs: 'dir',
standalone: false,
})
class DirToReference {
name = 'Drew';
}
@Directive({
selector: '[dirWithInput]',
standalone: false,
})
class DirWithCompInput {
@Input('dirWithInput') comp: ComponentToReference | null = null;
}
@Directive({
selector: '[dir-on-change]',
exportAs: 'dirOnChange',
host: {'[title]': 'name'},
standalone: false,
})
class DirToReferenceWithPreOrderHooks implements OnInit, OnChanges, DoCheck {
@Input() in: any = null;
name = 'Drew';
ngOnChanges(changes: SimpleChanges) {
this.name += '!';
}
ngOnInit() {
this.name += '?';
}
ngDoCheck() {
this.name += '@';
}
}
| {
"end_byte": 8648,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/exports_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_0_2355 | /**
* @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 {
assertInInjectionContext,
Attribute,
ChangeDetectorRef,
Component,
ComponentRef,
createEnvironmentInjector,
createNgModule,
Directive,
ElementRef,
ENVIRONMENT_INITIALIZER,
EnvironmentInjector,
EventEmitter,
forwardRef,
Host,
HOST_TAG_NAME,
HostAttributeToken,
HostBinding,
importProvidersFrom,
ImportProvidersSource,
inject,
Inject,
Injectable,
InjectFlags,
InjectionToken,
InjectOptions,
INJECTOR,
Injector,
Input,
LOCALE_ID,
makeEnvironmentProviders,
ModuleWithProviders,
NgModule,
NgModuleRef,
NgZone,
Optional,
Output,
Pipe,
PipeTransform,
Provider,
runInInjectionContext,
Self,
SkipSelf,
TemplateRef,
Type,
ViewChild,
ViewContainerRef,
ViewEncapsulation,
ViewRef,
ɵcreateInjector as createInjector,
ɵDEFAULT_LOCALE_ID as DEFAULT_LOCALE_ID,
ɵINJECTOR_SCOPE,
ɵInternalEnvironmentProviders as InternalEnvironmentProviders,
} from '@angular/core';
import {RuntimeError, RuntimeErrorCode} from '@angular/core/src/errors';
import {ViewRef as ViewRefInternal} from '@angular/core/src/render3/view_ref';
import {TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {BehaviorSubject} from 'rxjs';
const getProvidersByToken = (
providers: Provider[],
token: Type<unknown> | InjectionToken<unknown>,
): Provider[] => providers.filter((provider) => (provider as any).provide === token);
const hasProviderWithToken = (providers: Provider[], token: InjectionToken<unknown>): boolean =>
getProvidersByToken(providers, token).length > 0;
const collectEnvironmentInitializerProviders = (providers: Provider[]) =>
getProvidersByToken(providers, ENVIRONMENT_INITIALIZER);
function unwrappedImportProvidersFrom(...sources: ImportProvidersSource[]): Provider[] {
const providers = (importProvidersFrom(...sources) as unknown as InternalEnvironmentProviders)
.ɵproviders;
if (providers.some((provider) => 'ɵproviders' in provider)) {
throw new Error(`Unexpected nested EnvironmentProviders in test`);
}
return providers as Provider[];
}
desc | {
"end_byte": 2355,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_2357_10348 | be('importProvidersFrom', () => {
// Set of tokens used in various tests.
const A = new InjectionToken('A');
const B = new InjectionToken('B');
const C = new InjectionToken('C');
const D = new InjectionToken('D');
it('should collect providers from NgModules', () => {
@NgModule({
providers: [
{provide: C, useValue: 'C'},
{provide: D, useValue: 'D'},
],
})
class MyModule2 {}
@NgModule({
imports: [MyModule2],
providers: [
{provide: A, useValue: 'A'},
{provide: B, useValue: 'B'},
],
})
class MyModule {}
const providers = unwrappedImportProvidersFrom(MyModule);
// 4 tokens (A, B, C, D) + 2 providers for each NgModule:
// - the definition type itself
// - `INJECTOR_DEF_TYPES`
// - `ENVIRONMENT_INITIALIZER`
expect(providers.length).toBe(10);
expect(hasProviderWithToken(providers, A)).toBe(true);
expect(hasProviderWithToken(providers, B)).toBe(true);
expect(hasProviderWithToken(providers, C)).toBe(true);
expect(hasProviderWithToken(providers, D)).toBe(true);
// Expect 2 `ENVIRONMENT_INITIALIZER` providers: one for `MyModule`, another was `MyModule2`
expect(collectEnvironmentInitializerProviders(providers).length).toBe(2);
});
it('should collect providers from directly imported ModuleWithProviders', () => {
@NgModule({})
class Module {}
const providers = unwrappedImportProvidersFrom({
ngModule: Module,
providers: [{provide: A, useValue: 'A'}],
});
expect(hasProviderWithToken(providers, A)).toBe(true);
});
it('should collect all providers when a module is used twice with different providers (via ModuleWithProviders)', () => {
@NgModule({
providers: [
{provide: A, useValue: 'A'}, //
],
})
class ModuleA {}
@NgModule({imports: [ModuleA]})
class ModuleB {
static forRoot(): ModuleWithProviders<ModuleB> {
return {ngModule: ModuleB, providers: [{provide: B, useValue: 'B'}]};
}
static forChild(): ModuleWithProviders<ModuleB> {
return {ngModule: ModuleB, providers: [{provide: C, useValue: 'C'}]};
}
}
const providers = unwrappedImportProvidersFrom(ModuleB.forRoot(), ModuleB.forChild());
// Expect 2 `ENVIRONMENT_INITIALIZER` providers: one for `ModuleA`, another one for `ModuleB`
expect(collectEnvironmentInitializerProviders(providers).length).toBe(2);
// Expect exactly 1 provider for each module: `ModuleA` and `ModuleB`
expect(getProvidersByToken(providers, ModuleA).length).toBe(1);
expect(getProvidersByToken(providers, ModuleB).length).toBe(1);
// Expect all tokens to be collected.
expect(hasProviderWithToken(providers, A)).toBe(true);
expect(hasProviderWithToken(providers, B)).toBe(true);
expect(hasProviderWithToken(providers, C)).toBe(true);
});
it('should process nested arrays within a provider set of ModuleWithProviders type', () => {
@NgModule()
class ModuleA {
static forRoot(): ModuleWithProviders<ModuleA> {
return {
ngModule: ModuleA,
providers: [
{provide: A, useValue: 'A'},
// Nested arrays inside the list of providers:
[{provide: B, useValue: 'B'}, [{provide: C, useValue: 'C'}]],
],
};
}
}
const providers = unwrappedImportProvidersFrom(ModuleA.forRoot());
// Expect 1 `ENVIRONMENT_INITIALIZER` provider (for `ModuleA`)
expect(collectEnvironmentInitializerProviders(providers).length).toBe(1);
// Expect exactly 1 provider for `ModuleA`
expect(getProvidersByToken(providers, ModuleA).length).toBe(1);
// Expect all tokens to be collected.
expect(hasProviderWithToken(providers, A)).toBe(true);
expect(hasProviderWithToken(providers, B)).toBe(true);
expect(hasProviderWithToken(providers, C)).toBe(true);
});
it('should process nested arrays within provider set of an imported ModuleWithProviders type', () => {
@NgModule()
class ModuleA {
static forRoot(): ModuleWithProviders<ModuleA> {
return {
ngModule: ModuleA,
providers: [
{provide: A, useValue: 'A'},
// Nested arrays inside the list of providers:
[{provide: B, useValue: 'B'}, [{provide: C, useValue: 'C'}]],
],
};
}
}
@NgModule({imports: [ModuleA.forRoot()]})
class ModuleB {}
const providers = unwrappedImportProvidersFrom(ModuleB);
// Expect 2 `ENVIRONMENT_INITIALIZER` providers: one for `ModuleA`, another one for `ModuleB`
expect(collectEnvironmentInitializerProviders(providers).length).toBe(2);
// Expect exactly 1 provider for each module: `ModuleA` and `ModuleB`
expect(getProvidersByToken(providers, ModuleA).length).toBe(1);
expect(getProvidersByToken(providers, ModuleB).length).toBe(1);
// Expect all tokens to be collected.
expect(hasProviderWithToken(providers, A)).toBe(true);
expect(hasProviderWithToken(providers, B)).toBe(true);
expect(hasProviderWithToken(providers, C)).toBe(true);
});
it('should collect providers defined via `@NgModule.providers` when ModuleWithProviders type is used', () => {
@NgModule({
providers: [
{provide: A, useValue: 'Original A'}, //
{provide: B, useValue: 'B'}, //
{provide: D, useValue: 'Original D', multi: true},
],
})
class ModuleA {
static forRoot(): ModuleWithProviders<ModuleA> {
return {
ngModule: ModuleA,
providers: [
{provide: A, useValue: 'Overridden A'}, //
{provide: C, useValue: 'C'}, //
{provide: D, useValue: 'Extra D', multi: true},
],
};
}
}
const providers = unwrappedImportProvidersFrom(ModuleA.forRoot());
// Expect all tokens to be collected.
expect(hasProviderWithToken(providers, A)).toBe(true);
expect(hasProviderWithToken(providers, B)).toBe(true);
expect(hasProviderWithToken(providers, C)).toBe(true);
expect(hasProviderWithToken(providers, D)).toBe(true);
const parentEnvInjector = TestBed.inject(EnvironmentInjector);
const injector = createEnvironmentInjector(providers, parentEnvInjector);
// Verify that overridden token A has the right value.
expect(injector.get(A)).toBe('Overridden A');
// Verify that a multi-provider has both values.
expect(injector.get(D)).toEqual(['Original D', 'Extra D']);
});
it('should not be allowed in component providers', () => {
@NgModule({})
class Module {}
expect(() => {
@Component({
selector: 'test-cmp',
template: '',
// The double array here is necessary to escape the compile-time error, via Provider's
// `any[]` option.
providers: [[importProvidersFrom(Module)]],
standalone: false,
})
class Cmp {}
TestBed.createComponent(Cmp);
}).toThrowError(/NG0207/);
});
it('should import providers from an array of NgModules (may be nested)', () => {
@NgModule({providers: [{provide: A, useValue: 'A'}]})
class ModuleA {}
@NgModule({providers: [{provide: B, useValue: 'B'}]})
class ModuleB {}
const providers = unwrappedImportProvidersFrom([ModuleA, [ModuleB]]);
expect(hasProviderWithToken(providers, A)).toBeTrue();
expect(hasProviderWithToken(providers, B)).toBeTrue();
});
it('should throw when trying to import providers from standalone components', () => {
@NgModule({providers: [{provide: A, useValue: 'A'}]})
class ModuleA {}
@Component({
standalone: true,
template: '',
imports: [ModuleA],
})
class StandaloneCmp {}
expect(() => {
importProvidersFrom(StandaloneCmp);
}).toThrowError(
'NG0800: Importing providers supports NgModule or ModuleWithProviders but got a standalone component "StandaloneCmp"',
);
});
});
desc | {
"end_byte": 10348,
"start_byte": 2357,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_10350_14435 | be('EnvironmentProviders', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
const environmentProviders = makeEnvironmentProviders([
{
provide: TOKEN,
useValue: 'token!',
},
]);
it('should be accepted by TestBed providers', () => {
TestBed.configureTestingModule({
providers: [environmentProviders],
});
expect(TestBed.inject(TOKEN)).toEqual('token!');
});
it('should be accepted by @NgModule & createNgModule', () => {
@NgModule({
providers: [environmentProviders],
})
class TestModule {}
const inj = createNgModule(TestModule).injector;
expect(inj.get(TOKEN)).toEqual('token!');
});
it('should be accepted by @NgModule & TestBed imports', () => {
@NgModule({
providers: [environmentProviders],
})
class TestModule {}
TestBed.configureTestingModule({
imports: [TestModule],
});
expect(TestBed.inject(TOKEN)).toEqual('token!');
});
it('should be accepted in ModuleWithProviders & createNgModule', () => {
@NgModule({})
class EmptyModule {}
const mwp: ModuleWithProviders<EmptyModule> = {
ngModule: EmptyModule,
providers: [environmentProviders],
};
@NgModule({
imports: [mwp],
})
class TestModule {}
const inj = createNgModule(TestModule).injector;
expect(inj.get(TOKEN)).toEqual('token!');
});
it('should be accepted by createEnvironmentInjector', () => {
TestBed.configureTestingModule({});
const inj = createEnvironmentInjector(
[environmentProviders],
TestBed.inject(EnvironmentInjector),
);
expect(inj.get(TOKEN)).toEqual('token!');
});
it('should be accepted as additional input to makeEnvironmentProviders', () => {
const wrappedProviders = makeEnvironmentProviders([environmentProviders]);
TestBed.configureTestingModule({});
const inj = createEnvironmentInjector([wrappedProviders], TestBed.inject(EnvironmentInjector));
expect(inj.get(TOKEN)).toEqual('token!');
});
it('should be overridable by TestBed overrides', () => {
TestBed.configureTestingModule({
providers: [environmentProviders],
});
TestBed.overrideProvider(TOKEN, {
useValue: 'overridden!',
});
expect(TestBed.inject(TOKEN)).toEqual('overridden!');
});
it('should be rejected by @Component.providers', () => {
@Component({
providers: [environmentProviders as any],
standalone: false,
})
class TestCmp {
readonly token = inject(TOKEN);
}
expect(() => TestBed.createComponent(TestCmp)).toThrowError(/NG0207/);
});
});
describe('di', () => {
describe('no dependencies', () => {
it('should create directive with no deps', () => {
@Directive({
selector: '[dir]',
exportAs: 'dir',
standalone: false,
})
class MyDirective {
value = 'Created';
}
@Component({
template: '<div dir #dir="dir">{{ dir.value }}</div>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({declarations: [MyDirective, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div');
expect(divElement.textContent).toContain('Created');
});
});
describe('multi providers', () => {
it('should process ModuleWithProvider providers after module imports', () => {
const testToken = new InjectionToken<string[]>('test-multi');
@NgModule({providers: [{provide: testToken, useValue: 'A', multi: true}]})
class TestModuleA {}
@NgModule({providers: [{provide: testToken, useValue: 'B', multi: true}]})
class TestModuleB {}
TestBed.configureTestingModule({
imports: [
{
ngModule: TestModuleA,
providers: [{provide: testToken, useValue: 'C', multi: true}],
},
TestModuleB,
],
});
expect(TestBed.inject(testToken)).toEqual(['A', 'B', 'C']);
});
});
de | {
"end_byte": 14435,
"start_byte": 10350,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_14439_22413 | be('directive injection', () => {
let log: string[] = [];
@Directive({
selector: '[dirB]',
exportAs: 'dirB',
standalone: false,
})
class DirectiveB {
@Input() value = 'DirB';
constructor() {
log.push(this.value);
}
}
beforeEach(() => (log = []));
it('should create directive with intra view dependencies', () => {
@Directive({
selector: '[dirA]',
exportAs: 'dirA',
standalone: false,
})
class DirectiveA {
value = 'DirA';
}
@Directive({
selector: '[dirC]',
exportAs: 'dirC',
standalone: false,
})
class DirectiveC {
value: string;
constructor(dirA: DirectiveA, dirB: DirectiveB) {
this.value = dirA.value + dirB.value;
}
}
@Component({
template: `
<div dirA>
<span dirB dirC #dir="dirC">{{ dir.value }}</span>
</div>
`,
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, DirectiveC, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('span');
expect(divElement.textContent).toContain('DirADirB');
});
it('should instantiate injected directives in dependency order', () => {
@Directive({
selector: '[dirA]',
standalone: false,
})
class DirectiveA {
value = 'dirA';
constructor(dirB: DirectiveB) {
log.push(`DirA (dep: ${dirB.value})`);
}
}
@Component({
template: '<div dirA dirB></div>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(log).toEqual(['DirB', 'DirA (dep: DirB)']);
});
it('should fallback to the module injector', () => {
@Directive({
selector: '[dirA]',
standalone: false,
})
class DirectiveA {
value = 'dirA';
constructor(dirB: DirectiveB) {
log.push(`DirA (dep: ${dirB.value})`);
}
}
// - dirB is know to the node injectors
// - then when dirA tries to inject dirB, it will check the node injector first tree
// - if not found, it will check the module injector tree
@Component({
template: '<div dirB></div><div dirA></div>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({
declarations: [DirectiveA, DirectiveB, MyComp],
providers: [{provide: DirectiveB, useValue: {value: 'module'}}],
});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(log).toEqual(['DirB', 'DirA (dep: module)']);
});
it('should instantiate injected directives before components', () => {
@Component({
selector: 'my-comp',
template: '',
standalone: false,
})
class MyComp {
constructor(dirB: DirectiveB) {
log.push(`Comp (dep: ${dirB.value})`);
}
}
@Component({
template: '<my-comp dirB></my-comp>',
standalone: false,
})
class MyApp {}
TestBed.configureTestingModule({declarations: [DirectiveB, MyComp, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
expect(log).toEqual(['DirB', 'Comp (dep: DirB)']);
});
it('should inject directives in the correct order in a for loop', () => {
@Directive({
selector: '[dirA]',
standalone: false,
})
class DirectiveA {
constructor(dir: DirectiveB) {
log.push(`DirA (dep: ${dir.value})`);
}
}
@Component({
template: '<div dirA dirB *ngFor="let i of array"></div>',
standalone: false,
})
class MyComp {
array = [1, 2, 3];
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(log).toEqual([
'DirB',
'DirA (dep: DirB)',
'DirB',
'DirA (dep: DirB)',
'DirB',
'DirA (dep: DirB)',
]);
});
it('should instantiate directives with multiple out-of-order dependencies', () => {
@Directive({
selector: '[dirA]',
standalone: false,
})
class DirectiveA {
value = 'DirA';
constructor() {
log.push(this.value);
}
}
@Directive({
selector: '[dirC]',
standalone: false,
})
class DirectiveC {
value = 'DirC';
constructor() {
log.push(this.value);
}
}
@Directive({
selector: '[dirB]',
standalone: false,
})
class DirectiveB {
constructor(dirA: DirectiveA, dirC: DirectiveC) {
log.push(`DirB (deps: ${dirA.value} and ${dirC.value})`);
}
}
@Component({
template: '<div dirA dirB dirC></div>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, DirectiveC, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(log).toEqual(['DirA', 'DirC', 'DirB (deps: DirA and DirC)']);
});
it('should instantiate in the correct order for complex case', () => {
@Directive({
selector: '[dirC]',
standalone: false,
})
class DirectiveC {
value = 'DirC';
constructor(dirB: DirectiveB) {
log.push(`DirC (dep: ${dirB.value})`);
}
}
@Directive({
selector: '[dirA]',
standalone: false,
})
class DirectiveA {
value = 'DirA';
constructor(dirC: DirectiveC) {
log.push(`DirA (dep: ${dirC.value})`);
}
}
@Directive({
selector: '[dirD]',
standalone: false,
})
class DirectiveD {
value = 'DirD';
constructor(dirA: DirectiveA) {
log.push(`DirD (dep: ${dirA.value})`);
}
}
@Component({
selector: 'my-comp',
template: '',
standalone: false,
})
class MyComp {
constructor(dirD: DirectiveD) {
log.push(`Comp (dep: ${dirD.value})`);
}
}
@Component({
template: '<my-comp dirA dirB dirC dirD></my-comp>',
standalone: false,
})
class MyApp {}
TestBed.configureTestingModule({
declarations: [DirectiveA, DirectiveB, DirectiveC, DirectiveD, MyComp, MyApp],
});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
expect(log).toEqual([
'DirB',
'DirC (dep: DirB)',
'DirA (dep: DirC)',
'DirD (dep: DirA)',
'Comp (dep: DirD)',
]);
});
it('should instantiate in correct order with mixed parent and peer dependencies', () => {
@Component({
template: '<div dirA dirB dirC></div>',
standalone: false,
})
class MyApp {
value = 'App';
}
@Directive({
selector: '[dirA]',
standalone: false,
})
class DirectiveA {
constructor(dirB: DirectiveB, app: MyApp) {
log.push(`DirA (deps: ${dirB.value} and ${app.value})`);
}
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
expect(log).toEqual(['DirB', 'DirA (deps: DirB and App)']);
});
| {
"end_byte": 22413,
"start_byte": 14439,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_22419_32000 | ould not use a parent when peer dep is available', () => {
let count = 1;
@Directive({
selector: '[dirB]',
standalone: false,
})
class DirectiveB {
count: number;
constructor() {
log.push(`DirB`);
this.count = count++;
}
}
@Directive({
selector: '[dirA]',
standalone: false,
})
class DirectiveA {
constructor(dirB: DirectiveB) {
log.push(`DirA (dep: DirB - ${dirB.count})`);
}
}
@Component({
selector: 'my-comp',
template: '<div dirA dirB></div>',
standalone: false,
})
class MyComp {}
@Component({
template: '<my-comp dirB></my-comp>',
standalone: false,
})
class MyApp {}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
expect(log).toEqual(['DirB', 'DirB', 'DirA (dep: DirB - 2)']);
});
describe('dependencies in parent views', () => {
@Directive({
selector: '[dirA]',
exportAs: 'dirA',
standalone: false,
})
class DirectiveA {
injector: Injector;
constructor(
public dirB: DirectiveB,
public vcr: ViewContainerRef,
) {
this.injector = vcr.injector;
}
}
@Component({
selector: 'my-comp',
template: '<div dirA #dir="dirA">{{ dir.dirB.value }}</div>',
standalone: false,
})
class MyComp {}
it('should find dependencies on component hosts', () => {
@Component({
template: '<my-comp dirB></my-comp>',
standalone: false,
})
class MyApp {}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div');
expect(divElement.textContent).toEqual('DirB');
});
it('should find dependencies for directives in embedded views', () => {
@Component({
template: `<div dirB>
<div *ngIf="showing">
<div dirA #dir="dirA">{{ dir.dirB.value }}</div>
</div>
</div>`,
standalone: false,
})
class MyApp {
showing = false;
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.componentInstance.showing = true;
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div');
expect(divElement.textContent).toEqual('DirB');
});
it('should find dependencies of directives nested deeply in inline views', () => {
@Component({
template: `<div dirB>
<ng-container *ngIf="!skipContent">
<ng-container *ngIf="!skipContent2">
<div dirA #dir="dirA">{{ dir.dirB.value }}</div>
</ng-container>
</ng-container>
</div>`,
standalone: false,
})
class MyApp {
skipContent = false;
skipContent2 = false;
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div');
expect(divElement.textContent).toEqual('DirB');
});
it('should find dependencies in declaration tree of ng-template (not insertion tree)', () => {
@Directive({
selector: '[structuralDir]',
standalone: false,
})
class StructuralDirective {
@Input() tmp!: TemplateRef<any>;
constructor(public vcr: ViewContainerRef) {}
create() {
this.vcr.createEmbeddedView(this.tmp);
}
}
@Component({
template: `<div dirB value="declaration">
<ng-template #foo>
<div dirA #dir="dirA">{{ dir.dirB.value }}</div>
</ng-template>
</div>
<div dirB value="insertion">
<div structuralDir [tmp]="foo"></div>
<!-- insertion point -->
</div>`,
standalone: false,
})
class MyComp {
@ViewChild(StructuralDirective) structuralDir!: StructuralDirective;
}
TestBed.configureTestingModule({
declarations: [StructuralDirective, DirectiveA, DirectiveB, MyComp],
});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
fixture.componentInstance.structuralDir.create();
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div[value=insertion]');
expect(divElement.textContent).toEqual('declaration');
});
it('should create injectors on second template pass', () => {
@Component({
template: `<div>
<my-comp dirB></my-comp>
<my-comp dirB></my-comp>
</div>`,
standalone: false,
})
class MyApp {}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div');
expect(divElement.textContent).toEqual('DirBDirB');
});
it('should create injectors and host bindings in same view', () => {
@Directive({
selector: '[hostBindingDir]',
standalone: false,
})
class HostBindingDirective {
@HostBinding('id') id = 'foo';
}
@Component({
template: `<div dirB hostBindingDir>
<p dirA #dir="dirA">{{ dir.dirB.value }}</p>
</div>`,
standalone: false,
})
class MyApp {
@ViewChild(HostBindingDirective) hostBindingDir!: HostBindingDirective;
@ViewChild(DirectiveA) dirA!: DirectiveA;
}
TestBed.configureTestingModule({
declarations: [DirectiveA, DirectiveB, HostBindingDirective, MyApp],
});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div');
expect(divElement.textContent).toEqual('DirB');
expect(divElement.id).toEqual('foo');
const dirA = fixture.componentInstance.dirA;
expect(dirA.vcr.injector).toEqual(dirA.injector);
const hostBindingDir = fixture.componentInstance.hostBindingDir;
hostBindingDir.id = 'bar';
fixture.detectChanges();
expect(divElement.id).toBe('bar');
});
it('dynamic components should find dependencies when parent is projected', () => {
@Directive({
selector: '[dirA]',
standalone: false,
})
class DirA {}
@Directive({
selector: '[dirB]',
standalone: false,
})
class DirB {}
@Component({
selector: 'child',
template: '',
standalone: false,
})
class Child {
constructor(
@Optional() readonly dirA: DirA,
@Optional() readonly dirB: DirB,
) {}
}
@Component({
selector: 'projector',
template: '<ng-content></ng-content>',
standalone: false,
})
class Projector {}
@Component({
template: `
<projector>
<div dirA>
<ng-container #childOrigin></ng-container>
<ng-container #childOriginWithDirB dirB></ng-container>
</div>
</projector>`,
standalone: false,
})
class MyApp {
@ViewChild('childOrigin', {read: ViewContainerRef, static: true})
childOrigin!: ViewContainerRef;
@ViewChild('childOriginWithDirB', {read: ViewContainerRef, static: true})
childOriginWithDirB!: ViewContainerRef;
addChild() {
return this.childOrigin.createComponent(Child);
}
addChildWithDirB() {
return this.childOriginWithDirB.createComponent(Child);
}
}
const fixture = TestBed.configureTestingModule({
declarations: [Child, DirA, DirB, Projector, MyApp],
}).createComponent(MyApp);
const child = fixture.componentInstance.addChild();
expect(child).toBeDefined();
expect(child.instance.dirA)
.withContext('dirA should be found. It is on the parent of the viewContainerRef.')
.not.toBeNull();
const child2 = fixture.componentInstance.addChildWithDirB();
expect(child2).toBeDefined();
expect(child2.instance.dirA)
.withContext('dirA should be found. It is on the parent of the viewContainerRef.')
.not.toBeNull();
expect(child2.instance.dirB)
.withContext(
'dirB appears on the ng-container and should not be found because the ' +
'viewContainerRef.createComponent node is inserted next to the container.',
)
.toBeNull();
});
});
| {
"end_byte": 32000,
"start_byte": 22419,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_32006_41248 | ould throw if directive is not found anywhere', () => {
@Directive({
selector: '[dirB]',
standalone: false,
})
class DirectiveB {
constructor() {}
}
@Directive({
selector: '[dirA]',
standalone: false,
})
class DirectiveA {
constructor(siblingDir: DirectiveB) {}
}
@Component({
template: '<div dirA></div>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp]});
expect(() => TestBed.createComponent(MyComp)).toThrowError(/No provider for DirectiveB/);
});
it('should throw if directive is not found in ancestor tree', () => {
@Directive({
selector: '[dirB]',
standalone: false,
})
class DirectiveB {
constructor() {}
}
@Directive({
selector: '[dirA]',
standalone: false,
})
class DirectiveA {
constructor(siblingDir: DirectiveB) {}
}
@Component({
template: '<div dirA></div><div dirB></div>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp]});
expect(() => TestBed.createComponent(MyComp)).toThrowError(/No provider for DirectiveB/);
});
it('should not have access to the directive injector in a standalone injector from within a directive-level provider factory', () => {
// https://github.com/angular/angular/issues/42651
class TestA {
constructor(public injector: string) {}
}
class TestB {
constructor(public a: TestA) {}
}
function createTestB() {
// Setup a standalone injector that provides `TestA`, which is resolved from a
// standalone child injector that requests `TestA` as a dependency for `TestB`.
// Although we're inside a directive factory and therefore have access to the
// directive-level injector, `TestA` has to be resolved from the standalone injector.
const parent = Injector.create({
providers: [{provide: TestA, useFactory: () => new TestA('standalone'), deps: []}],
name: 'TestA',
});
const child = Injector.create({
providers: [{provide: TestB, useClass: TestB, deps: [TestA]}],
parent,
name: 'TestB',
});
return child.get(TestB);
}
@Component({
template: '',
providers: [
{provide: TestA, useFactory: () => new TestA('component'), deps: []},
{provide: TestB, useFactory: createTestB},
],
standalone: false,
})
class MyComp {
constructor(public readonly testB: TestB) {}
}
TestBed.configureTestingModule({declarations: [MyComp]});
const cmp = TestBed.createComponent(MyComp);
expect(cmp.componentInstance.testB).toBeInstanceOf(TestB);
expect(cmp.componentInstance.testB.a.injector).toBe('standalone');
});
it('should not have access to the directive injector in a standalone injector from within a directive-level provider factory', () => {
class TestA {
constructor(public injector: string) {}
}
class TestB {
constructor(public a: TestA | null) {}
}
function createTestB() {
// Setup a standalone injector that provides `TestB` with an optional dependency of
// `TestA`. Since `TestA` is not provided by the standalone injector it should resolve
// to null; both the NgModule providers and the component-level providers should not
// be considered.
const injector = Injector.create({
providers: [{provide: TestB, useClass: TestB, deps: [[TestA, new Optional()]]}],
name: 'TestB',
});
return injector.get(TestB);
}
@Component({
template: '',
providers: [
{provide: TestA, useFactory: () => new TestA('component'), deps: []},
{provide: TestB, useFactory: createTestB},
],
standalone: false,
})
class MyComp {
constructor(public readonly testB: TestB) {}
}
TestBed.configureTestingModule({
declarations: [MyComp],
providers: [{provide: TestA, useFactory: () => new TestA('module'), deps: []}],
});
const cmp = TestBed.createComponent(MyComp);
expect(cmp.componentInstance.testB).toBeInstanceOf(TestB);
expect(cmp.componentInstance.testB.a).toBeNull();
});
it('should throw if directive tries to inject itself', () => {
@Directive({
selector: '[dirA]',
standalone: false,
})
class DirectiveA {
constructor(siblingDir: DirectiveA) {}
}
@Component({
template: '<div dirA></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', () => {
@Directive({
selector: '[dirB]',
standalone: false,
})
class DirectiveB {
@Input('dirB') value = '';
}
describe('Optional', () => {
@Directive({
selector: '[dirA]',
standalone: false,
})
class DirectiveA {
constructor(@Optional() public dirB: DirectiveB) {}
}
it('should not throw if dependency is @Optional (module injector)', () => {
@Component({
template: '<div dirA></div>',
standalone: false,
})
class MyComp {
@ViewChild(DirectiveA) dirA!: DirectiveA;
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const dirA = fixture.componentInstance.dirA;
expect(dirA.dirB).toBeNull();
});
it('should return null if @Optional dependency has @Self flag', () => {
@Directive({
selector: '[dirC]',
standalone: false,
})
class DirectiveC {
constructor(@Optional() @Self() public dirB: DirectiveB) {}
}
@Component({
template: '<div dirC></div>',
standalone: false,
})
class MyComp {
@ViewChild(DirectiveC) dirC!: DirectiveC;
}
TestBed.configureTestingModule({declarations: [DirectiveC, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const dirC = fixture.componentInstance.dirC;
expect(dirC.dirB).toBeNull();
});
it('should not throw if dependency is @Optional but defined elsewhere', () => {
@Directive({
selector: '[dirC]',
standalone: false,
})
class DirectiveC {
constructor(@Optional() public dirB: DirectiveB) {}
}
@Component({
template: '<div dirB></div><div dirC></div>',
standalone: false,
})
class MyComp {
@ViewChild(DirectiveC) dirC!: DirectiveC;
}
TestBed.configureTestingModule({declarations: [DirectiveB, DirectiveC, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const dirC = fixture.componentInstance.dirC;
expect(dirC.dirB).toBeNull();
});
it('should imply @Optional in presence of a default value', () => {
const NON_EXISTING_PROVIDER = new InjectionToken<string>('non-existing');
@Component({
template: '',
standalone: false,
})
class MyComp {
value: string | undefined;
constructor(injector: Injector) {
this.value = injector.get(NON_EXISTING_PROVIDER, 'default', InjectFlags.Host);
}
}
const injector = Injector.create({providers: []});
expect(injector.get(NON_EXISTING_PROVIDER, 'default', InjectFlags.Host)).toBe('default');
const fixture = TestBed.createComponent(MyComp);
expect(fixture.componentInstance.value).toBe('default');
});
});
it('should check only the current node with @Self', () => {
@Directive({
selector: '[dirA]',
standalone: false,
})
class DirectiveA {
constructor(@Self() public dirB: DirectiveB) {}
}
@Component({
template: '<div dirB><div dirA></div></div>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp]});
expect(() => TestBed.createComponent(MyComp)).toThrowError(
/NG0201: No provider for DirectiveB found in NodeInjector/,
);
});
| {
"end_byte": 41248,
"start_byte": 32006,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_41256_52248 | be('SkipSelf', () => {
describe('Injectors', () => {
it('should support @SkipSelf when injecting Injectors', () => {
@Component({
selector: 'parent',
template: '<child></child>',
providers: [
{
provide: 'token',
useValue: 'PARENT',
},
],
standalone: false,
})
class ParentComponent {}
@Component({
selector: 'child',
template: '...',
providers: [
{
provide: 'token',
useValue: 'CHILD',
},
],
standalone: false,
})
class ChildComponent {
constructor(
public injector: Injector,
@SkipSelf() public parentInjector: Injector,
) {}
}
TestBed.configureTestingModule({
declarations: [ParentComponent, ChildComponent],
});
const fixture = TestBed.createComponent(ParentComponent);
fixture.detectChanges();
const childComponent = fixture.debugElement.query(
By.directive(ChildComponent),
).componentInstance;
expect(childComponent.injector.get('token')).toBe('CHILD');
expect(childComponent.parentInjector.get('token')).toBe('PARENT');
});
it('should lookup module injector in case @SkipSelf is used and no suitable Injector found in element injector tree', () => {
let componentInjector: Injector;
let moduleInjector: Injector;
@Component({
selector: 'child',
template: '...',
providers: [
{
provide: 'token',
useValue: 'CHILD',
},
],
standalone: false,
})
class MyComponent {
constructor(@SkipSelf() public injector: Injector) {
componentInjector = injector;
}
}
@NgModule({
declarations: [MyComponent],
providers: [
{
provide: 'token',
useValue: 'NG_MODULE',
},
],
})
class MyModule {
constructor(public injector: Injector) {
moduleInjector = injector;
}
}
TestBed.configureTestingModule({
imports: [MyModule],
});
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
expect(componentInjector!.get('token')).toBe('NG_MODULE');
expect(moduleInjector!.get('token')).toBe('NG_MODULE');
});
it('should respect @Host in case @SkipSelf is used and no suitable Injector found in element injector tree', () => {
let componentInjector: Injector;
let moduleInjector: Injector;
@Component({
selector: 'child',
template: '...',
providers: [
{
provide: 'token',
useValue: 'CHILD',
},
],
standalone: false,
})
class MyComponent {
constructor(@Host() @SkipSelf() public injector: Injector) {
componentInjector = injector;
}
}
@NgModule({
declarations: [MyComponent],
providers: [
{
provide: 'token',
useValue: 'NG_MODULE',
},
],
})
class MyModule {
constructor(public injector: Injector) {
moduleInjector = injector;
}
}
TestBed.configureTestingModule({
imports: [MyModule],
});
expect(() => TestBed.createComponent(MyComponent)).toThrowError(
/NG0201: No provider for Injector found in NodeInjector/,
);
});
it('should throw when injecting Injectors using @SkipSelf and @Host and no Injectors are available in a current view', () => {
@Component({
selector: 'parent',
template: '<child></child>',
providers: [
{
provide: 'token',
useValue: 'PARENT',
},
],
standalone: false,
})
class ParentComponent {}
@Component({
selector: 'child',
template: '...',
providers: [
{
provide: 'token',
useValue: 'CHILD',
},
],
standalone: false,
})
class ChildComponent {
constructor(@Host() @SkipSelf() public injector: Injector) {}
}
TestBed.configureTestingModule({
declarations: [ParentComponent, ChildComponent],
});
const expectedErrorMessage = /NG0201: No provider for Injector found in NodeInjector/;
expect(() => TestBed.createComponent(ParentComponent)).toThrowError(
expectedErrorMessage,
);
});
it('should not throw when injecting Injectors using @SkipSelf, @Host, and @Optional and no Injectors are available in a current view', () => {
@Component({
selector: 'parent',
template: '<child></child>',
providers: [
{
provide: 'token',
useValue: 'PARENT',
},
],
standalone: false,
})
class ParentComponent {}
@Component({
selector: 'child',
template: '...',
providers: [
{
provide: 'token',
useValue: 'CHILD',
},
],
standalone: false,
})
class ChildComponent {
constructor(@Host() @SkipSelf() @Optional() public injector: Injector) {}
}
TestBed.configureTestingModule({
declarations: [ParentComponent, ChildComponent],
});
const expectedErrorMessage = /NG0201: No provider for Injector found in NodeInjector/;
expect(() => TestBed.createComponent(ParentComponent)).not.toThrowError(
expectedErrorMessage,
);
});
});
describe('ElementRef', () => {
// While tokens like `ElementRef` make sense only in a context of a NodeInjector,
// ViewEngine also used `ModuleInjector` tree to lookup such tokens. In Ivy we replicate
// this behavior for now to avoid breaking changes.
it('should lookup module injector in case @SkipSelf is used for `ElementRef` token and Component has no parent', () => {
let componentElement: ElementRef;
let moduleElement: ElementRef;
@Component({
template: '<div>component</div>',
standalone: false,
})
class MyComponent {
constructor(@SkipSelf() public el: ElementRef) {
componentElement = el;
}
}
@NgModule({
declarations: [MyComponent],
providers: [
{
provide: ElementRef,
useValue: {from: 'NG_MODULE'},
},
],
})
class MyModule {
constructor(public el: ElementRef) {
moduleElement = el;
}
}
TestBed.configureTestingModule({
imports: [MyModule],
});
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
expect((moduleElement! as any).from).toBe('NG_MODULE');
expect((componentElement! as any).from).toBe('NG_MODULE');
});
it('should return host node when @SkipSelf is used for `ElementRef` token and Component has no parent node', () => {
let parentElement: ElementRef;
let componentElement: ElementRef;
@Component({
selector: 'child',
template: '...',
standalone: false,
})
class MyComponent {
constructor(@SkipSelf() public el: ElementRef) {
componentElement = el;
}
}
@Component({
template: '<child></child>',
standalone: false,
})
class ParentComponent {
constructor(public el: ElementRef) {
parentElement = el;
}
}
TestBed.configureTestingModule({
imports: [CommonModule],
declarations: [ParentComponent, MyComponent],
});
const fixture = TestBed.createComponent(ParentComponent);
fixture.detectChanges();
expect(componentElement!).toEqual(parentElement!);
});
it('should @SkipSelf on child directive node when injecting ElementRef on nested parent directive', () => {
let parentRef: ElementRef;
let childRef: ElementRef;
@Directive({
selector: '[parent]',
standalone: false,
})
class ParentDirective {
constructor(elementRef: ElementRef) {
parentRef = elementRef;
}
}
@Directive({
selector: '[child]',
standalone: false,
})
class ChildDirective {
constructor(@SkipSelf() elementRef: ElementRef) {
childRef = elementRef;
}
}
@Component({
template: '<div parent>parent <span child>child</span></div>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({
declarations: [ParentDirective, ChildDirective, MyComp],
});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
// Assert against the `nativeElement` since Ivy always returns a new ElementRef.
expect(childRef!.nativeElement).toBe(parentRef!.nativeElement);
expect(childRef!.nativeElement.tagName).toBe('DIV');
});
});
| {
"end_byte": 52248,
"start_byte": 41256,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_52258_59899 | be('@SkipSelf when parent contains embedded views', () => {
it('should work for `ElementRef` token', () => {
let requestedElementRef: ElementRef;
@Component({
selector: 'child',
template: '...',
standalone: false,
})
class ChildComponent {
constructor(@SkipSelf() public elementRef: ElementRef) {
requestedElementRef = elementRef;
}
}
@Component({
selector: 'root',
template: '<div><child *ngIf="true"></child></div>',
standalone: false,
})
class ParentComponent {}
TestBed.configureTestingModule({
imports: [CommonModule],
declarations: [ParentComponent, ChildComponent],
});
const fixture = TestBed.createComponent(ParentComponent);
fixture.detectChanges();
expect(requestedElementRef!.nativeElement).toEqual(fixture.nativeElement.firstChild);
expect(requestedElementRef!.nativeElement.tagName).toEqual('DIV');
});
it('should work for `ElementRef` token with expanded *ngIf', () => {
let requestedElementRef: ElementRef;
@Component({
selector: 'child',
template: '...',
standalone: false,
})
class ChildComponent {
constructor(@SkipSelf() public elementRef: ElementRef) {
requestedElementRef = elementRef;
}
}
@Component({
selector: 'root',
template: '<div><ng-template [ngIf]="true"><child></child></ng-template></div>',
standalone: false,
})
class ParentComponent {}
TestBed.configureTestingModule({
imports: [CommonModule],
declarations: [ParentComponent, ChildComponent],
});
const fixture = TestBed.createComponent(ParentComponent);
fixture.detectChanges();
expect(requestedElementRef!.nativeElement).toEqual(fixture.nativeElement.firstChild);
expect(requestedElementRef!.nativeElement.tagName).toEqual('DIV');
});
it('should work for `ViewContainerRef` token', () => {
let requestedRef: ViewContainerRef;
@Component({
selector: 'child',
template: '...',
standalone: false,
})
class ChildComponent {
constructor(@SkipSelf() public ref: ViewContainerRef) {
requestedRef = ref;
}
}
@Component({
selector: 'root',
template: '<div><child *ngIf="true"></child></div>',
standalone: false,
})
class ParentComponent {}
TestBed.configureTestingModule({
imports: [CommonModule],
declarations: [ParentComponent, ChildComponent],
});
const fixture = TestBed.createComponent(ParentComponent);
fixture.detectChanges();
expect(requestedRef!.element.nativeElement).toBe(fixture.nativeElement.firstChild);
expect(requestedRef!.element.nativeElement.tagName).toBe('DIV');
});
it('should work for `ChangeDetectorRef` token', () => {
let requestedChangeDetectorRef: ChangeDetectorRef;
@Component({
selector: 'child',
template: '...',
standalone: false,
})
class ChildComponent {
constructor(@SkipSelf() public changeDetectorRef: ChangeDetectorRef) {
requestedChangeDetectorRef = changeDetectorRef;
}
}
@Component({
selector: 'root',
template: '<child *ngIf="true"></child>',
standalone: false,
})
class ParentComponent {}
TestBed.configureTestingModule({
imports: [CommonModule],
declarations: [ParentComponent, ChildComponent],
});
const fixture = TestBed.createComponent(ParentComponent);
fixture.detectChanges();
const {context} = requestedChangeDetectorRef! as ViewRefInternal<ParentComponent>;
expect(context).toBe(fixture.componentInstance);
});
// this works consistently between VE and Ivy
it('should work for Injectors', () => {
let childComponentInjector: Injector;
let parentComponentInjector: Injector;
@Component({
selector: 'parent',
template: '<child *ngIf="true"></child>',
providers: [
{
provide: 'token',
useValue: 'PARENT',
},
],
standalone: false,
})
class ParentComponent {
constructor(public injector: Injector) {
parentComponentInjector = injector;
}
}
@Component({
selector: 'child',
template: '...',
providers: [
{
provide: 'token',
useValue: 'CHILD',
},
],
standalone: false,
})
class ChildComponent {
constructor(@SkipSelf() public injector: Injector) {
childComponentInjector = injector;
}
}
TestBed.configureTestingModule({
declarations: [ParentComponent, ChildComponent],
});
const fixture = TestBed.createComponent(ParentComponent);
fixture.detectChanges();
expect(childComponentInjector!.get('token')).toBe(
parentComponentInjector!.get('token'),
);
});
it('should work for Injectors with expanded *ngIf', () => {
let childComponentInjector: Injector;
let parentComponentInjector: Injector;
@Component({
selector: 'parent',
template: '<ng-template [ngIf]="true"><child></child></ng-template>',
providers: [
{
provide: 'token',
useValue: 'PARENT',
},
],
standalone: false,
})
class ParentComponent {
constructor(public injector: Injector) {
parentComponentInjector = injector;
}
}
@Component({
selector: 'child',
template: '...',
providers: [
{
provide: 'token',
useValue: 'CHILD',
},
],
standalone: false,
})
class ChildComponent {
constructor(@SkipSelf() public injector: Injector) {
childComponentInjector = injector;
}
}
TestBed.configureTestingModule({
declarations: [ParentComponent, ChildComponent],
});
const fixture = TestBed.createComponent(ParentComponent);
fixture.detectChanges();
expect(childComponentInjector!.get('token')).toBe(
parentComponentInjector!.get('token'),
);
});
});
| {
"end_byte": 59899,
"start_byte": 52258,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_59909_68666 | be('TemplateRef', () => {
// SkipSelf doesn't make sense to use with TemplateRef since you
// can't inject TemplateRef on a regular element and you can initialize
// a child component on a nested `<ng-template>` only when a component/directive
// on a parent `<ng-template>` is initialized.
it('should throw when using @SkipSelf for TemplateRef', () => {
@Directive({
selector: '[dir]',
exportAs: 'dir',
standalone: false,
})
class MyDir {
constructor(@SkipSelf() public templateRef: TemplateRef<any>) {}
}
@Component({
selector: '[child]',
template: '<ng-template dir></ng-template>',
standalone: false,
})
class ChildComp {
constructor(public templateRef: TemplateRef<any>) {}
@ViewChild(MyDir) directive!: MyDir;
}
@Component({
selector: 'root',
template: '<div child></div>',
standalone: false,
})
class MyComp {
@ViewChild(ChildComp) child!: ChildComp;
}
TestBed.configureTestingModule({
imports: [CommonModule],
declarations: [MyDir, ChildComp, MyComp],
});
const expectedErrorMessage = /NG0201: No provider for TemplateRef found/;
expect(() => {
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
}).toThrowError(expectedErrorMessage);
});
it('should throw when SkipSelf and no parent TemplateRef', () => {
@Directive({
selector: '[dirA]',
exportAs: 'dirA',
standalone: false,
})
class DirA {
constructor(@SkipSelf() public templateRef: TemplateRef<any>) {}
}
@Component({
selector: 'root',
template: '<ng-template dirA></ng-template>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({
imports: [CommonModule],
declarations: [DirA, MyComp],
});
const expectedErrorMessage = /NG0201: No provider for TemplateRef found/;
expect(() => {
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
}).toThrowError(expectedErrorMessage);
});
it('should not throw when SkipSelf and Optional', () => {
let directiveTemplateRef;
@Directive({
selector: '[dirA]',
exportAs: 'dirA',
standalone: false,
})
class DirA {
constructor(@SkipSelf() @Optional() templateRef: TemplateRef<any>) {
directiveTemplateRef = templateRef;
}
}
@Component({
selector: 'root',
template: '<ng-template dirA></ng-template>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({
imports: [CommonModule],
declarations: [DirA, MyComp],
});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(directiveTemplateRef).toBeNull();
});
it('should not throw when SkipSelf, Optional, and Host', () => {
@Directive({
selector: '[dirA]',
exportAs: 'dirA',
standalone: false,
})
class DirA {
constructor(@SkipSelf() @Optional() @Host() public templateRef: TemplateRef<any>) {}
}
@Component({
selector: 'root',
template: '<ng-template dirA></ng-template>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({
imports: [CommonModule],
declarations: [DirA, MyComp],
});
expect(() => TestBed.createComponent(MyComp)).not.toThrowError();
});
});
describe('ViewContainerRef', () => {
it('should support @SkipSelf when injecting ViewContainerRef', () => {
let parentViewContainer: ViewContainerRef;
let childViewContainer: ViewContainerRef;
@Directive({
selector: '[parent]',
standalone: false,
})
class ParentDirective {
constructor(vc: ViewContainerRef) {
parentViewContainer = vc;
}
}
@Directive({
selector: '[child]',
standalone: false,
})
class ChildDirective {
constructor(@SkipSelf() vc: ViewContainerRef) {
childViewContainer = vc;
}
}
@Component({
template: '<div parent>parent <span child>child</span></div>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({
declarations: [ParentDirective, ChildDirective, MyComp],
});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
// Assert against the `element` since Ivy always returns a new ViewContainerRef.
expect(childViewContainer!.element.nativeElement).toBe(
parentViewContainer!.element.nativeElement,
);
expect(parentViewContainer!.element.nativeElement.tagName).toBe('DIV');
});
it('should get ViewContainerRef using @SkipSelf and @Host', () => {
let parentViewContainer: ViewContainerRef;
let childViewContainer: ViewContainerRef;
@Directive({
selector: '[parent]',
standalone: false,
})
class ParentDirective {
constructor(vc: ViewContainerRef) {
parentViewContainer = vc;
}
}
@Directive({
selector: '[child]',
standalone: false,
})
class ChildDirective {
constructor(@SkipSelf() @Host() vc: ViewContainerRef) {
childViewContainer = vc;
}
}
@Component({
template: '<div parent>parent <span child>child</span></div>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({
declarations: [ParentDirective, ChildDirective, MyComp],
});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(childViewContainer!.element.nativeElement).toBe(
parentViewContainer!.element.nativeElement,
);
expect(parentViewContainer!.element.nativeElement.tagName).toBe('DIV');
});
it('should get ViewContainerRef using @SkipSelf and @Host on parent', () => {
let parentViewContainer: ViewContainerRef;
@Directive({
selector: '[parent]',
standalone: false,
})
class ParentDirective {
constructor(@SkipSelf() vc: ViewContainerRef) {
parentViewContainer = vc;
}
}
@Component({
template: '<div parent>parent</div>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({declarations: [ParentDirective, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(parentViewContainer!.element.nativeElement.tagName).toBe('DIV');
});
it('should throw when injecting ViewContainerRef using @SkipSelf and no ViewContainerRef are available in a current view', () => {
@Component({
template: '<span>component</span>',
standalone: false,
})
class MyComp {
constructor(@SkipSelf() vc: ViewContainerRef) {}
}
TestBed.configureTestingModule({declarations: [MyComp]});
expect(() => TestBed.createComponent(MyComp)).toThrowError(
/No provider for ViewContainerRef/,
);
});
});
| {
"end_byte": 68666,
"start_byte": 59909,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_68676_78551 | be('ChangeDetectorRef', () => {
it('should support @SkipSelf when injecting ChangeDetectorRef', () => {
let parentRef: ChangeDetectorRef | undefined;
let childRef: ChangeDetectorRef | undefined;
@Directive({
selector: '[parent]',
standalone: false,
})
class ParentDirective {
constructor(cdr: ChangeDetectorRef) {
parentRef = cdr;
}
}
@Directive({
selector: '[child]',
standalone: false,
})
class ChildDirective {
constructor(@SkipSelf() cdr: ChangeDetectorRef) {
childRef = cdr;
}
}
@Component({
template: '<div parent>parent <span child>child</span></div>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({
declarations: [ParentDirective, ChildDirective, MyComp],
});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
// Assert against the `rootNodes` since Ivy always returns a new ChangeDetectorRef.
expect((parentRef as ViewRefInternal<any>).rootNodes).toEqual(
(childRef as ViewRefInternal<any>).rootNodes,
);
});
it('should inject host component ChangeDetectorRef when @SkipSelf', () => {
let childRef: ChangeDetectorRef | undefined;
@Component({
selector: 'child',
template: '...',
standalone: false,
})
class ChildComp {
constructor(@SkipSelf() cdr: ChangeDetectorRef) {
childRef = cdr;
}
}
@Component({
template: '<div><child></child></div>',
standalone: false,
})
class MyComp {
constructor(public cdr: ChangeDetectorRef) {}
}
TestBed.configureTestingModule({declarations: [ChildComp, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
// Assert against the `rootNodes` since Ivy always returns a new ChangeDetectorRef.
expect((childRef as ViewRefInternal<any>).rootNodes).toEqual(
(fixture.componentInstance.cdr as ViewRefInternal<any>).rootNodes,
);
});
it('should throw when ChangeDetectorRef and @SkipSelf and not found', () => {
@Component({
template: '<div></div>',
standalone: false,
})
class MyComponent {
constructor(@SkipSelf() public injector: ChangeDetectorRef) {}
}
@NgModule({
declarations: [MyComponent],
})
class MyModule {}
TestBed.configureTestingModule({
imports: [MyModule],
});
expect(() => TestBed.createComponent(MyComponent)).toThrowError(
/No provider for ChangeDetectorRef/,
);
});
it('should lookup module injector in case @SkipSelf is used for `ChangeDetectorRef` token and Component has no parent', () => {
let componentCDR: ChangeDetectorRef;
let moduleCDR: ChangeDetectorRef;
@Component({
selector: 'child',
template: '...',
standalone: false,
})
class MyComponent {
constructor(@SkipSelf() public injector: ChangeDetectorRef) {
componentCDR = injector;
}
}
@NgModule({
declarations: [MyComponent],
providers: [
{
provide: ChangeDetectorRef,
useValue: {from: 'NG_MODULE'},
},
],
})
class MyModule {
constructor(public injector: ChangeDetectorRef) {
moduleCDR = injector;
}
}
TestBed.configureTestingModule({
imports: [MyModule],
});
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
expect((moduleCDR! as any).from).toBe('NG_MODULE');
expect((componentCDR! as any).from).toBe('NG_MODULE');
});
});
describe('viewProviders', () => {
it('should support @SkipSelf when using viewProviders', () => {
@Component({
selector: 'child',
template: '{{ blah | json }}<br />{{ foo | json }}<br />{{ bar | json }}',
providers: [{provide: 'Blah', useValue: 'Blah as Provider'}],
viewProviders: [
{provide: 'Foo', useValue: 'Foo as ViewProvider'},
{provide: 'Bar', useValue: 'Bar as ViewProvider'},
],
standalone: false,
})
class Child {
constructor(
@Inject('Blah') public blah: String,
@Inject('Foo') public foo: String,
@SkipSelf() @Inject('Bar') public bar: String,
) {}
}
@Component({
selector: 'parent',
template: '<ng-content></ng-content>',
providers: [
{provide: 'Blah', useValue: 'Blah as provider'},
{provide: 'Bar', useValue: 'Bar as Provider'},
],
viewProviders: [
{provide: 'Foo', useValue: 'Foo as ViewProvider'},
{provide: 'Bar', useValue: 'Bar as ViewProvider'},
],
standalone: false,
})
class Parent {}
@Component({
selector: 'my-app',
template: '<parent><child></child></parent>',
standalone: false,
})
class MyApp {
@ViewChild(Parent) parent!: Parent;
@ViewChild(Child) child!: Child;
}
TestBed.configureTestingModule({declarations: [Child, Parent, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
const child = fixture.componentInstance.child;
expect(child.bar).toBe('Bar as Provider');
});
it('should throw when @SkipSelf and no accessible viewProvider', () => {
@Component({
selector: 'child',
template: '{{ blah | json }}<br />{{ foo | json }}<br />{{ bar | json }}',
providers: [{provide: 'Blah', useValue: 'Blah as Provider'}],
viewProviders: [
{provide: 'Foo', useValue: 'Foo as ViewProvider'},
{provide: 'Bar', useValue: 'Bar as ViewProvider'},
],
standalone: false,
})
class Child {
constructor(
@Inject('Blah') public blah: String,
@Inject('Foo') public foo: String,
@SkipSelf() @Inject('Bar') public bar: String,
) {}
}
@Component({
selector: 'parent',
template: '<ng-content></ng-content>',
providers: [{provide: 'Blah', useValue: 'Blah as provider'}],
viewProviders: [
{provide: 'Foo', useValue: 'Foo as ViewProvider'},
{provide: 'Bar', useValue: 'Bar as ViewProvider'},
],
standalone: false,
})
class Parent {}
@Component({
selector: 'my-app',
template: '<parent><child></child></parent>',
standalone: false,
})
class MyApp {}
TestBed.configureTestingModule({declarations: [Child, Parent, MyApp]});
expect(() => TestBed.createComponent(MyApp)).toThrowError(/No provider for Bar/);
});
it('should not throw when @SkipSelf and @Optional with no accessible viewProvider', () => {
@Component({
selector: 'child',
template: '{{ blah | json }}<br />{{ foo | json }}<br />{{ bar | json }}',
providers: [{provide: 'Blah', useValue: 'Blah as Provider'}],
viewProviders: [
{provide: 'Foo', useValue: 'Foo as ViewProvider'},
{provide: 'Bar', useValue: 'Bar as ViewProvider'},
],
standalone: false,
})
class Child {
constructor(
@Inject('Blah') public blah: String,
@Inject('Foo') public foo: String,
@SkipSelf() @Optional() @Inject('Bar') public bar: String,
) {}
}
@Component({
selector: 'parent',
template: '<ng-content></ng-content>',
providers: [{provide: 'Blah', useValue: 'Blah as provider'}],
viewProviders: [
{provide: 'Foo', useValue: 'Foo as ViewProvider'},
{provide: 'Bar', useValue: 'Bar as ViewProvider'},
],
standalone: false,
})
class Parent {}
@Component({
selector: 'my-app',
template: '<parent><child></child></parent>',
standalone: false,
})
class MyApp {}
TestBed.configureTestingModule({declarations: [Child, Parent, MyApp]});
expect(() => TestBed.createComponent(MyApp)).not.toThrowError(/No provider for Bar/);
});
});
});
| {
"end_byte": 78551,
"start_byte": 68676,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_78559_85993 | be('@Host', () => {
@Directive({
selector: '[dirA]',
standalone: false,
})
class DirectiveA {
constructor(@Host() public dirB: DirectiveB) {}
}
@Directive({
selector: '[dirString]',
standalone: false,
})
class DirectiveString {
constructor(@Host() public s: String) {}
}
it('should find viewProviders on the host itself', () => {
@Component({
selector: 'my-comp',
template: '<div dirString></div>',
viewProviders: [{provide: String, useValue: 'Foo'}],
standalone: false,
})
class MyComp {
@ViewChild(DirectiveString) dirString!: DirectiveString;
}
@Component({
template: '<my-comp></my-comp>',
standalone: false,
})
class MyApp {
@ViewChild(MyComp) myComp!: MyComp;
}
TestBed.configureTestingModule({declarations: [DirectiveString, MyComp, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
const dirString = fixture.componentInstance.myComp.dirString;
expect(dirString.s).toBe('Foo');
});
it('should not find providers on the host itself', () => {
@Component({
selector: 'my-comp',
template: '<div dirString></div>',
providers: [{provide: String, useValue: 'Foo'}],
standalone: false,
})
class MyComp {}
@Component({
template: '<my-comp></my-comp>',
standalone: false,
})
class MyApp {}
TestBed.configureTestingModule({declarations: [DirectiveString, MyComp, MyApp]});
expect(() => TestBed.createComponent(MyApp)).toThrowError(
'NG0201: No provider for String found in NodeInjector. Find more at https://angular.dev/errors/NG0201',
);
});
it('should not find other directives on the host itself', () => {
@Component({
selector: 'my-comp',
template: '<div dirA></div>',
standalone: false,
})
class MyComp {}
@Component({
template: '<my-comp dirB></my-comp>',
standalone: false,
})
class MyApp {}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp, MyApp]});
expect(() => TestBed.createComponent(MyApp)).toThrowError(
/NG0201: No provider for DirectiveB found in NodeInjector/,
);
});
it('should not find providers on the host itself if in inline view', () => {
@Component({
selector: 'my-comp',
template: '<ng-container *ngIf="showing"><div dirA></div></ng-container>',
standalone: false,
})
class MyComp {
showing = false;
}
@Component({
template: '<my-comp dirB></my-comp>',
standalone: false,
})
class MyApp {
@ViewChild(MyComp) myComp!: MyComp;
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
expect(() => {
fixture.componentInstance.myComp.showing = true;
fixture.detectChanges();
}).toThrowError(/NG0201: No provider for DirectiveB found in NodeInjector/);
});
it('should find providers across embedded views if not passing component boundary', () => {
@Component({
template: '<div dirB><div *ngIf="showing" dirA></div></div>',
standalone: false,
})
class MyApp {
showing = false;
@ViewChild(DirectiveA) dirA!: DirectiveA;
@ViewChild(DirectiveB) dirB!: DirectiveB;
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
fixture.componentInstance.showing = true;
fixture.detectChanges();
const dirA = fixture.componentInstance.dirA;
const dirB = fixture.componentInstance.dirB;
expect(dirA.dirB).toBe(dirB);
});
it('should not find component above the host', () => {
@Component({
template: '<my-comp></my-comp>',
standalone: false,
})
class MyApp {}
@Directive({
selector: '[dirComp]',
standalone: false,
})
class DirectiveComp {
constructor(@Host() public comp: MyApp) {}
}
@Component({
selector: 'my-comp',
template: '<div dirComp></div>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({declarations: [DirectiveComp, MyComp, MyApp]});
expect(() => TestBed.createComponent(MyApp)).toThrowError(
'NG0201: No provider for MyApp found in NodeInjector. Find more at https://angular.dev/errors/NG0201',
);
});
describe('regression', () => {
// based on https://stackblitz.com/edit/angular-riss8k?file=src/app/app.component.ts
it('should allow directives with Host flag to inject view providers from containing component', () => {
class ControlContainer {}
let controlContainers: ControlContainer[] = [];
let injectedControlContainer: ControlContainer | null = null;
@Directive({
selector: '[group]',
providers: [{provide: ControlContainer, useExisting: GroupDirective}],
standalone: false,
})
class GroupDirective {
constructor() {
controlContainers.push(this);
}
}
@Directive({
selector: '[control]',
standalone: false,
})
class ControlDirective {
constructor(@Host() @SkipSelf() @Inject(ControlContainer) parent: ControlContainer) {
injectedControlContainer = parent;
}
}
@Component({
selector: 'my-comp',
template: '<input control>',
viewProviders: [{provide: ControlContainer, useExisting: GroupDirective}],
standalone: false,
})
class MyComp {}
@Component({
template: `
<div group>
<my-comp></my-comp>
</div>
`,
standalone: false,
})
class MyApp {}
TestBed.configureTestingModule({
declarations: [GroupDirective, ControlDirective, MyComp, MyApp],
});
const fixture = TestBed.createComponent(MyApp);
expect(fixture.nativeElement.innerHTML).toBe(
'<div group=""><my-comp><input control=""></my-comp></div>',
);
expect(controlContainers).toEqual([injectedControlContainer!]);
});
});
});
| {
"end_byte": 85993,
"start_byte": 78559,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_86001_93651 | be('`InjectFlags` support in NodeInjector', () => {
it('should support Optional flag in NodeInjector', () => {
const NON_EXISTING_PROVIDER = new InjectionToken<string>('non-existing');
@Component({
template: '...',
standalone: false,
})
class MyComp {
tokenViaInjector;
constructor(
public injector: Injector,
@Inject(NON_EXISTING_PROVIDER) @Optional() public tokenViaConstructor: string,
) {
this.tokenViaInjector = this.injector.get(
NON_EXISTING_PROVIDER,
null,
InjectFlags.Optional,
);
}
}
TestBed.configureTestingModule({declarations: [MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.componentInstance.tokenViaInjector).toBe(null);
expect(fixture.componentInstance.tokenViaInjector).toBe(
fixture.componentInstance.tokenViaConstructor,
);
});
it('should support SkipSelf flag in NodeInjector', () => {
const TOKEN = new InjectionToken<string>('token');
@Component({
selector: 'parent',
template: '<child></child>',
providers: [
{
provide: TOKEN,
useValue: 'PARENT',
},
],
standalone: false,
})
class ParentComponent {}
@Component({
selector: 'child',
template: '...',
providers: [
{
provide: TOKEN,
useValue: 'CHILD',
},
],
standalone: false,
})
class ChildComponent {
tokenViaInjector;
constructor(
public injector: Injector,
@Inject(TOKEN) @SkipSelf() public tokenViaConstructor: string,
) {
this.tokenViaInjector = this.injector.get(TOKEN, null, InjectFlags.SkipSelf);
}
}
TestBed.configureTestingModule({
declarations: [ParentComponent, ChildComponent],
});
const fixture = TestBed.createComponent(ParentComponent);
fixture.detectChanges();
const childComponent = fixture.debugElement.query(
By.directive(ChildComponent),
).componentInstance;
expect(childComponent.tokenViaInjector).toBe('PARENT');
expect(childComponent.tokenViaConstructor).toBe(childComponent.tokenViaInjector);
});
it('should support Host flag in NodeInjector', () => {
const TOKEN = new InjectionToken<string>('token');
@Directive({
selector: '[dirString]',
standalone: false,
})
class DirectiveString {
tokenViaInjector;
constructor(
public injector: Injector,
@Inject(TOKEN) @Host() public tokenViaConstructor: string,
) {
this.tokenViaInjector = this.injector.get(TOKEN, null, InjectFlags.Host);
}
}
@Component({
template: '<div dirString></div>',
viewProviders: [{provide: TOKEN, useValue: 'Foo'}],
standalone: false,
})
class MyComp {
@ViewChild(DirectiveString) dirString!: DirectiveString;
}
TestBed.configureTestingModule({declarations: [DirectiveString, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const dirString = fixture.componentInstance.dirString;
expect(dirString.tokenViaConstructor).toBe('Foo');
expect(dirString.tokenViaConstructor).toBe(dirString.tokenViaInjector!);
});
it('should support multiple flags in NodeInjector', () => {
@Directive({
selector: '[dirA]',
standalone: false,
})
class DirectiveA {}
@Directive({
selector: '[dirB]',
standalone: false,
})
class DirectiveB {
tokenSelfViaInjector;
tokenHostViaInjector;
constructor(
public injector: Injector,
@Inject(DirectiveA) @Self() @Optional() public tokenSelfViaConstructor: DirectiveA,
@Inject(DirectiveA) @Host() @Optional() public tokenHostViaConstructor: DirectiveA,
) {
this.tokenSelfViaInjector = this.injector.get(
DirectiveA,
null,
InjectFlags.Self | InjectFlags.Optional,
);
this.tokenHostViaInjector = this.injector.get(
DirectiveA,
null,
InjectFlags.Host | InjectFlags.Optional,
);
}
}
@Component({
template: '<div dirB></div>',
standalone: false,
})
class MyComp {
@ViewChild(DirectiveB) dirB!: DirectiveB;
}
TestBed.configureTestingModule({declarations: [DirectiveB, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const dirB = fixture.componentInstance.dirB;
expect(dirB.tokenSelfViaInjector).toBeNull();
expect(dirB.tokenSelfViaInjector).toBe(dirB.tokenSelfViaConstructor);
expect(dirB.tokenHostViaInjector).toBeNull();
expect(dirB.tokenHostViaInjector).toBe(dirB.tokenHostViaConstructor);
});
});
});
});
describe('Tree shakable injectors', () => {
it('should support tree shakable injectors scopes', () => {
@Injectable({providedIn: 'any'})
class AnyService {
constructor(public injector: Injector) {}
}
@Injectable({providedIn: 'root'})
class RootService {
constructor(public injector: Injector) {}
}
@Injectable({providedIn: 'platform'})
class PlatformService {
constructor(public injector: Injector) {}
}
const testBedInjector: Injector = TestBed.get(Injector);
const childInjector = Injector.create({providers: [], parent: testBedInjector});
const anyService = childInjector.get(AnyService);
expect(anyService.injector).toBe(childInjector);
const rootService = childInjector.get(RootService);
expect(rootService.injector.get(ɵINJECTOR_SCOPE)).toBe('root');
const platformService = childInjector.get(PlatformService);
expect(platformService.injector.get(ɵINJECTOR_SCOPE)).toBe('platform');
});
it('should create a provider that uses `forwardRef` inside `providedIn`', () => {
@Injectable()
class ProviderDep {
getNumber() {
return 3;
}
}
@Injectable({providedIn: forwardRef(() => Module)})
class Provider {
constructor(private _dep: ProviderDep) {
this.value = this._dep.getNumber() + 2;
}
value;
}
@Component({
template: '',
standalone: false,
})
class Comp {
constructor(public provider: Provider) {}
}
@NgModule({declarations: [Comp], exports: [Comp], providers: [ProviderDep]})
class Module {}
TestBed.configureTestingModule({imports: [Module]});
const fixture = TestBed.createComponent(Comp);
expect(fixture.componentInstance.provider.value).toBe(5);
});
});
desc | {
"end_byte": 93651,
"start_byte": 86001,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_93655_102376 | ('service injection', () => {
it('should create instance even when no injector present', () => {
@Injectable({providedIn: 'root'})
class MyService {
value = 'MyService';
}
@Component({
template: '<div>{{myService.value}}</div>',
standalone: false,
})
class MyComp {
constructor(public myService: MyService) {}
}
TestBed.configureTestingModule({declarations: [MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div');
expect(divElement.textContent).toEqual('MyService');
});
it('should support sub-classes with no @Injectable decorator', () => {
@Injectable()
class Dependency {}
@Injectable()
class SuperClass {
constructor(public dep: Dependency) {}
}
// Note, no @Injectable decorators for these two classes
class SubClass extends SuperClass {}
class SubSubClass extends SubClass {}
@Component({
template: '',
standalone: false,
})
class MyComp {
constructor(public myService: SuperClass) {}
}
TestBed.configureTestingModule({
declarations: [MyComp],
providers: [{provide: SuperClass, useClass: SubSubClass}, Dependency],
});
const warnSpy = spyOn(console, 'warn');
const fixture = TestBed.createComponent(MyComp);
expect(fixture.componentInstance.myService.dep instanceof Dependency).toBe(true);
expect(warnSpy).toHaveBeenCalledWith(
`DEPRECATED: DI is instantiating a token "SubSubClass" that inherits its @Injectable decorator but does not provide one itself.\n` +
`This will become an error in a future version of Angular. Please add @Injectable() to the "SubSubClass" class.`,
);
});
it('should instantiate correct class when undecorated class extends an injectable', () => {
@Injectable()
class MyService {
id = 1;
}
class MyRootService extends MyService {
override id = 2;
}
@Component({
template: '',
standalone: false,
})
class App {}
TestBed.configureTestingModule({declarations: [App], providers: [MyRootService]});
const warnSpy = spyOn(console, 'warn');
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const provider = TestBed.inject(MyRootService);
expect(provider instanceof MyRootService).toBe(true);
expect(provider.id).toBe(2);
expect(warnSpy).toHaveBeenCalledWith(
`DEPRECATED: DI is instantiating a token "MyRootService" that inherits its @Injectable decorator but does not provide one itself.\n` +
`This will become an error in a future version of Angular. Please add @Injectable() to the "MyRootService" class.`,
);
});
it('should inject services in constructor with overloads', () => {
@Injectable({providedIn: 'root'})
class MyService {}
@Injectable({providedIn: 'root'})
class MyOtherService {}
@Component({
template: '',
standalone: false,
})
class MyComp {
constructor(myService: MyService);
constructor(
public myService: MyService,
@Optional() public myOtherService?: MyOtherService,
) {}
}
TestBed.configureTestingModule({declarations: [MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.componentInstance.myService instanceof MyService).toBe(true);
expect(fixture.componentInstance.myOtherService instanceof MyOtherService).toBe(true);
});
});
describe('service injection with useClass', () => {
@Injectable({providedIn: 'root'})
class BarServiceDep {
name = 'BarServiceDep';
}
@Injectable({providedIn: 'root'})
class BarService {
constructor(public dep: BarServiceDep) {}
getMessage() {
return 'bar';
}
}
@Injectable({providedIn: 'root'})
class FooServiceDep {
name = 'FooServiceDep';
}
@Injectable({providedIn: 'root', useClass: BarService})
class FooService {
constructor(public dep: FooServiceDep) {}
getMessage() {
return 'foo';
}
}
it('should use @Injectable useClass config when token is not provided', () => {
let provider: FooService | BarService;
@Component({
template: '',
standalone: false,
})
class App {
constructor(service: FooService) {
provider = service;
}
}
TestBed.configureTestingModule({declarations: [App]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(provider!.getMessage()).toBe('bar');
expect(provider!.dep.name).toBe('BarServiceDep');
});
it('should use constructor config directly when token is explicitly provided via useClass', () => {
let provider: FooService | BarService;
@Component({
template: '',
standalone: false,
})
class App {
constructor(service: FooService) {
provider = service;
}
}
TestBed.configureTestingModule({
declarations: [App],
providers: [{provide: FooService, useClass: FooService}],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(provider!.getMessage()).toBe('foo');
});
it('should inject correct provider when re-providing an injectable that has useClass', () => {
let directProvider: FooService | BarService;
let overriddenProvider: FooService | BarService;
@Component({
template: '',
standalone: false,
})
class App {
constructor(@Inject('stringToken') overriddenService: FooService, service: FooService) {
overriddenProvider = overriddenService;
directProvider = service;
}
}
TestBed.configureTestingModule({
declarations: [App],
providers: [{provide: 'stringToken', useClass: FooService}],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(directProvider!.getMessage()).toBe('bar');
expect(overriddenProvider!.getMessage()).toBe('foo');
expect(directProvider!.dep.name).toBe('BarServiceDep');
expect(overriddenProvider!.dep.name).toBe('FooServiceDep');
});
it('should use constructor config directly when token is explicitly provided as a type provider', () => {
let provider: FooService | BarService;
@Component({
template: '',
standalone: false,
})
class App {
constructor(service: FooService) {
provider = service;
}
}
TestBed.configureTestingModule({declarations: [App], providers: [FooService]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(provider!.getMessage()).toBe('foo');
expect(provider!.dep.name).toBe('FooServiceDep');
});
});
describe('inject', () => {
it('should inject from parent view', () => {
@Directive({
selector: '[parentDir]',
standalone: false,
})
class ParentDirective {}
@Directive({
selector: '[childDir]',
exportAs: 'childDir',
standalone: false,
})
class ChildDirective {
value: string;
constructor(public parent: ParentDirective) {
this.value = parent.constructor.name;
}
}
@Directive({
selector: '[child2Dir]',
exportAs: 'child2Dir',
standalone: false,
})
class Child2Directive {
value: boolean;
constructor(parent: ParentDirective, child: ChildDirective) {
this.value = parent === child.parent;
}
}
@Component({
template: `<div parentDir>
<ng-container *ngIf="showing">
<span childDir child2Dir #child1="childDir" #child2="child2Dir">{{ child1.value }}-{{ child2.value }}</span>
</ng-container>
</div>`,
standalone: false,
})
class MyComp {
showing = true;
}
TestBed.configureTestingModule({
declarations: [ParentDirective, ChildDirective, Child2Directive, MyComp],
});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div');
expect(divElement.textContent).toBe('ParentDirective-true');
});
});
desc | {
"end_byte": 102376,
"start_byte": 93655,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_102380_109563 | ('Special tokens', () => {
describe('Injector', () => {
it('should inject the injector', () => {
@Directive({
selector: '[injectorDir]',
standalone: false,
})
class InjectorDir {
constructor(public injector: Injector) {}
}
@Directive({
selector: '[otherInjectorDir]',
standalone: false,
})
class OtherInjectorDir {
constructor(
public otherDir: InjectorDir,
public injector: Injector,
) {}
}
@Component({
template: '<div injectorDir otherInjectorDir></div>',
standalone: false,
})
class MyComp {
@ViewChild(InjectorDir) injectorDir!: InjectorDir;
@ViewChild(OtherInjectorDir) otherInjectorDir!: OtherInjectorDir;
}
TestBed.configureTestingModule({declarations: [InjectorDir, OtherInjectorDir, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div');
const injectorDir = fixture.componentInstance.injectorDir;
const otherInjectorDir = fixture.componentInstance.otherInjectorDir;
expect(injectorDir.injector.get(ElementRef).nativeElement).toBe(divElement);
expect(otherInjectorDir.injector.get(ElementRef).nativeElement).toBe(divElement);
expect(otherInjectorDir.injector.get(InjectorDir)).toBe(injectorDir);
expect(injectorDir.injector).not.toBe(otherInjectorDir.injector);
});
it('should inject INJECTOR', () => {
@Directive({
selector: '[injectorDir]',
standalone: false,
})
class InjectorDir {
constructor(@Inject(INJECTOR) public injector: Injector) {}
}
@Component({
template: '<div injectorDir></div>',
standalone: false,
})
class MyComp {
@ViewChild(InjectorDir) injectorDir!: InjectorDir;
}
TestBed.configureTestingModule({declarations: [InjectorDir, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div');
const injectorDir = fixture.componentInstance.injectorDir;
expect(injectorDir.injector.get(ElementRef).nativeElement).toBe(divElement);
expect(injectorDir.injector.get(Injector).get(ElementRef).nativeElement).toBe(divElement);
expect(injectorDir.injector.get(INJECTOR).get(ElementRef).nativeElement).toBe(divElement);
});
});
describe('ElementRef', () => {
it('should create directive with ElementRef dependencies', () => {
@Directive({
selector: '[dir]',
standalone: false,
})
class MyDir {
value: string;
constructor(public elementRef: ElementRef) {
this.value = (elementRef.constructor as any).name;
}
}
@Directive({
selector: '[otherDir]',
standalone: false,
})
class MyOtherDir {
isSameInstance: boolean;
constructor(
public elementRef: ElementRef,
public directive: MyDir,
) {
this.isSameInstance = elementRef === directive.elementRef;
}
}
@Component({
template: '<div dir otherDir></div>',
standalone: false,
})
class MyComp {
@ViewChild(MyDir) directive!: MyDir;
@ViewChild(MyOtherDir) otherDirective!: MyOtherDir;
}
TestBed.configureTestingModule({declarations: [MyDir, MyOtherDir, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div');
const directive = fixture.componentInstance.directive;
const otherDirective = fixture.componentInstance.otherDirective;
expect(directive.value).toContain('ElementRef');
expect(directive.elementRef.nativeElement).toEqual(divElement);
expect(otherDirective.elementRef.nativeElement).toEqual(divElement);
// Each ElementRef instance should be unique
expect(otherDirective.isSameInstance).toBe(false);
});
it('should create ElementRef with comment if requesting directive is on <ng-template> node', () => {
@Directive({
selector: '[dir]',
standalone: false,
})
class MyDir {
value: string;
constructor(public elementRef: ElementRef<Node>) {
this.value = (elementRef.constructor as any).name;
}
}
@Component({
template: '<ng-template dir></ng-template>',
standalone: false,
})
class MyComp {
@ViewChild(MyDir) directive!: MyDir;
}
TestBed.configureTestingModule({declarations: [MyDir, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const directive = fixture.componentInstance.directive;
expect(directive.value).toContain('ElementRef');
// the nativeElement should be a comment
expect(directive.elementRef.nativeElement.nodeType).toEqual(Node.COMMENT_NODE);
});
it('should be available if used in conjunction with other tokens', () => {
@Injectable()
class ServiceA {
subject: any;
constructor(protected zone: NgZone) {
this.subject = new BehaviorSubject<any>(1);
// trigger change detection
zone.run(() => {
this.subject.next(2);
});
}
}
@Directive({
selector: '[dir]',
standalone: false,
})
class DirectiveA {
constructor(
public service: ServiceA,
public elementRef: ElementRef,
) {}
}
@Component({
selector: 'child',
template: `<div id="test-id" dir></div>`,
standalone: false,
})
class ChildComp {
@ViewChild(DirectiveA) directive!: DirectiveA;
}
@Component({
selector: 'root',
template: '...',
standalone: false,
})
class RootComp {
public childCompRef!: ComponentRef<ChildComp>;
constructor(public vcr: ViewContainerRef) {}
create() {
this.childCompRef = this.vcr.createComponent(ChildComp);
this.childCompRef.changeDetectorRef.detectChanges();
}
}
TestBed.configureTestingModule({
declarations: [DirectiveA, RootComp, ChildComp],
providers: [ServiceA],
});
const fixture = TestBed.createComponent(RootComp);
fixture.autoDetectChanges();
fixture.componentInstance.create();
const {elementRef} = fixture.componentInstance.childCompRef.instance.directive;
expect(elementRef.nativeElement.id).toBe('test-id');
});
});
de | {
"end_byte": 109563,
"start_byte": 102380,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_109569_115656 | ('TemplateRef', () => {
@Directive({
selector: '[dir]',
exportAs: 'dir',
standalone: false,
})
class MyDir {
value: string;
constructor(public templateRef: TemplateRef<any>) {
this.value = (templateRef.constructor as any).name;
}
}
it('should create directive with TemplateRef dependencies', () => {
@Directive({
selector: '[otherDir]',
exportAs: 'otherDir',
standalone: false,
})
class MyOtherDir {
isSameInstance: boolean;
constructor(
public templateRef: TemplateRef<any>,
public directive: MyDir,
) {
this.isSameInstance = templateRef === directive.templateRef;
}
}
@Component({
template: '<ng-template dir otherDir #dir="dir" #otherDir="otherDir"></ng-template>',
standalone: false,
})
class MyComp {
@ViewChild(MyDir) directive!: MyDir;
@ViewChild(MyOtherDir) otherDirective!: MyOtherDir;
}
TestBed.configureTestingModule({declarations: [MyDir, MyOtherDir, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const directive = fixture.componentInstance.directive;
const otherDirective = fixture.componentInstance.otherDirective;
expect(directive.value).toContain('TemplateRef');
expect(directive.templateRef).not.toBeNull();
expect(otherDirective.templateRef).not.toBeNull();
// Each TemplateRef instance should be unique
expect(otherDirective.isSameInstance).toBe(false);
});
it('should throw if injected on an element', () => {
@Component({
template: '<div dir></div>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({declarations: [MyDir, MyComp]});
expect(() => TestBed.createComponent(MyComp)).toThrowError(/No provider for TemplateRef/);
});
it('should throw if injected on an ng-container', () => {
@Component({
template: '<ng-container dir></ng-container>',
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({declarations: [MyDir, MyComp]});
expect(() => TestBed.createComponent(MyComp)).toThrowError(/No provider for TemplateRef/);
});
it('should NOT throw if optional and injected on an element', () => {
@Directive({
selector: '[optionalDir]',
exportAs: 'optionalDir',
standalone: false,
})
class OptionalDir {
constructor(@Optional() public templateRef: TemplateRef<any>) {}
}
@Component({
template: '<div optionalDir></div>',
standalone: false,
})
class MyComp {
@ViewChild(OptionalDir) directive!: OptionalDir;
}
TestBed.configureTestingModule({declarations: [OptionalDir, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.componentInstance.directive.templateRef).toBeNull();
});
});
describe('ViewContainerRef', () => {
it('should create directive with ViewContainerRef dependencies', () => {
@Directive({
selector: '[dir]',
exportAs: 'dir',
standalone: false,
})
class MyDir {
value: string;
constructor(public viewContainerRef: ViewContainerRef) {
this.value = (viewContainerRef.constructor as any).name;
}
}
@Directive({
selector: '[otherDir]',
exportAs: 'otherDir',
standalone: false,
})
class MyOtherDir {
isSameInstance: boolean;
constructor(
public viewContainerRef: ViewContainerRef,
public directive: MyDir,
) {
this.isSameInstance = viewContainerRef === directive.viewContainerRef;
}
}
@Component({
template: '<div dir otherDir #dir="dir" #otherDir="otherDir"></div>',
standalone: false,
})
class MyComp {
@ViewChild(MyDir) directive!: MyDir;
@ViewChild(MyOtherDir) otherDirective!: MyOtherDir;
}
TestBed.configureTestingModule({declarations: [MyDir, MyOtherDir, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const directive = fixture.componentInstance.directive;
const otherDirective = fixture.componentInstance.otherDirective;
expect(directive.value).toContain('ViewContainerRef');
expect(directive.viewContainerRef).not.toBeNull();
expect(otherDirective.viewContainerRef).not.toBeNull();
// Each ViewContainerRef instance should be unique
expect(otherDirective.isSameInstance).toBe(false);
});
it('should sync ViewContainerRef state between all injected instances', () => {
@Component({
selector: 'root',
template: `<ng-template #tmpl>Test</ng-template>`,
standalone: false,
})
class Root {
@ViewChild(TemplateRef, {static: true}) tmpl!: TemplateRef<any>;
constructor(
public vcr: ViewContainerRef,
public vcr2: ViewContainerRef,
) {}
ngOnInit(): void {
this.vcr.createEmbeddedView(this.tmpl);
}
}
TestBed.configureTestingModule({
declarations: [Root],
});
const fixture = TestBed.createComponent(Root);
fixture.detectChanges();
const cmp = fixture.componentInstance;
expect(cmp.vcr.length).toBe(1);
expect(cmp.vcr2.length).toBe(1);
expect(cmp.vcr2.get(0)).toEqual(cmp.vcr.get(0));
cmp.vcr2.remove(0);
expect(cmp.vcr.length).toBe(0);
expect(cmp.vcr.get(0)).toBeNull();
});
});
de | {
"end_byte": 115656,
"start_byte": 109569,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_115662_125097 | ('ChangeDetectorRef', () => {
@Directive({
selector: '[dir]',
exportAs: 'dir',
standalone: false,
})
class MyDir {
value: string;
constructor(public cdr: ChangeDetectorRef) {
this.value = (cdr.constructor as any).name;
}
}
@Directive({
selector: '[otherDir]',
exportAs: 'otherDir',
standalone: false,
})
class MyOtherDir {
constructor(public cdr: ChangeDetectorRef) {}
}
@Component({
selector: 'my-comp',
template: '<ng-content></ng-content>',
standalone: false,
})
class MyComp {
constructor(public cdr: ChangeDetectorRef) {}
}
it('should inject host component ChangeDetectorRef into directives on templates', () => {
let pipeInstance: MyPipe;
@Pipe({
name: 'pipe',
standalone: false,
})
class MyPipe implements PipeTransform {
constructor(public cdr: ChangeDetectorRef) {
pipeInstance = this;
}
transform(value: any): any {
return value;
}
}
@Component({
selector: 'my-app',
template: `<div *ngIf="showing | pipe">Visible</div>`,
standalone: false,
})
class MyApp {
showing = true;
constructor(public cdr: ChangeDetectorRef) {}
}
TestBed.configureTestingModule({declarations: [MyApp, MyPipe], imports: [CommonModule]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
expect((pipeInstance!.cdr as ViewRefInternal<MyApp>).context).toBe(
fixture.componentInstance,
);
});
it('should inject current component ChangeDetectorRef into directives on the same node as components', () => {
@Component({
selector: 'my-app',
template: '<my-comp dir otherDir #dir="dir"></my-comp>',
standalone: false,
})
class MyApp {
@ViewChild(MyComp) component!: MyComp;
@ViewChild(MyDir) directive!: MyDir;
@ViewChild(MyOtherDir) otherDirective!: MyOtherDir;
}
TestBed.configureTestingModule({declarations: [MyApp, MyComp, MyDir, MyOtherDir]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
const app = fixture.componentInstance;
const comp = fixture.componentInstance.component;
expect((comp!.cdr as ViewRefInternal<MyComp>).context).toBe(comp);
// ChangeDetectorRef is the token, ViewRef has historically been the constructor
expect(app.directive.value).toContain('ViewRef');
// Each ChangeDetectorRef instance should be unique
expect(app.directive!.cdr).not.toBe(comp!.cdr);
expect(app.directive!.cdr).not.toBe(app.otherDirective!.cdr);
});
it('should inject host component ChangeDetectorRef into directives on normal elements', () => {
@Component({
selector: 'my-comp',
template: '<div dir otherDir #dir="dir"></div>',
standalone: false,
})
class MyComp {
constructor(public cdr: ChangeDetectorRef) {}
@ViewChild(MyDir) directive!: MyDir;
@ViewChild(MyOtherDir) otherDirective!: MyOtherDir;
}
TestBed.configureTestingModule({declarations: [MyComp, MyDir, MyOtherDir]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const comp = fixture.componentInstance;
expect((comp!.cdr as ViewRefInternal<MyComp>).context).toBe(comp);
// ChangeDetectorRef is the token, ViewRef has historically been the constructor
expect(comp.directive.value).toContain('ViewRef');
// Each ChangeDetectorRef instance should be unique
expect(comp.directive!.cdr).not.toBe(comp.cdr);
expect(comp.directive!.cdr).not.toBe(comp.otherDirective!.cdr);
});
it("should inject host component ChangeDetectorRef into directives in a component's ContentChildren", () => {
@Component({
selector: 'my-app',
template: `<my-comp>
<div dir otherDir #dir="dir"></div>
</my-comp>
`,
standalone: false,
})
class MyApp {
constructor(public cdr: ChangeDetectorRef) {}
@ViewChild(MyComp) component!: MyComp;
@ViewChild(MyDir) directive!: MyDir;
@ViewChild(MyOtherDir) otherDirective!: MyOtherDir;
}
TestBed.configureTestingModule({declarations: [MyApp, MyComp, MyDir, MyOtherDir]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
const app = fixture.componentInstance;
expect((app!.cdr as ViewRefInternal<MyApp>).context).toBe(app);
const comp = fixture.componentInstance.component;
// ChangeDetectorRef is the token, ViewRef has historically been the constructor
expect(app.directive.value).toContain('ViewRef');
// Each ChangeDetectorRef instance should be unique
expect(app.directive!.cdr).not.toBe(comp.cdr);
expect(app.directive!.cdr).not.toBe(app.otherDirective!.cdr);
});
it('should inject host component ChangeDetectorRef into directives in embedded views', () => {
@Component({
selector: 'my-comp',
template: `<ng-container *ngIf="showing">
<div dir otherDir #dir="dir" *ngIf="showing"></div>
</ng-container>`,
standalone: false,
})
class MyComp {
showing = true;
constructor(public cdr: ChangeDetectorRef) {}
@ViewChild(MyDir) directive!: MyDir;
@ViewChild(MyOtherDir) otherDirective!: MyOtherDir;
}
TestBed.configureTestingModule({declarations: [MyComp, MyDir, MyOtherDir]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const comp = fixture.componentInstance;
expect((comp!.cdr as ViewRefInternal<MyComp>).context).toBe(comp);
// ChangeDetectorRef is the token, ViewRef has historically been the constructor
expect(comp.directive.value).toContain('ViewRef');
// Each ChangeDetectorRef instance should be unique
expect(comp.directive!.cdr).not.toBe(comp.cdr);
expect(comp.directive!.cdr).not.toBe(comp.otherDirective!.cdr);
});
it('should inject host component ChangeDetectorRef into directives on containers', () => {
@Component({
selector: 'my-comp',
template: '<div dir otherDir #dir="dir" *ngIf="showing"></div>',
standalone: false,
})
class MyComp {
showing = true;
constructor(public cdr: ChangeDetectorRef) {}
@ViewChild(MyDir) directive!: MyDir;
@ViewChild(MyOtherDir) otherDirective!: MyOtherDir;
}
TestBed.configureTestingModule({declarations: [MyComp, MyDir, MyOtherDir]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const comp = fixture.componentInstance;
expect((comp!.cdr as ViewRefInternal<MyComp>).context).toBe(comp);
// ChangeDetectorRef is the token, ViewRef has historically been the constructor
expect(comp.directive.value).toContain('ViewRef');
// Each ChangeDetectorRef instance should be unique
expect(comp.directive!.cdr).not.toBe(comp.cdr);
expect(comp.directive!.cdr).not.toBe(comp.otherDirective!.cdr);
});
it('should inject host component ChangeDetectorRef into directives on ng-container', () => {
let dirInstance: MyDirective;
@Directive({
selector: '[getCDR]',
standalone: false,
})
class MyDirective {
constructor(public cdr: ChangeDetectorRef) {
dirInstance = this;
}
}
@Component({
selector: 'my-app',
template: `<ng-container getCDR>Visible</ng-container>`,
standalone: false,
})
class MyApp {
constructor(public cdr: ChangeDetectorRef) {}
}
TestBed.configureTestingModule({declarations: [MyApp, MyDirective]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
expect((dirInstance!.cdr as ViewRefInternal<MyApp>).context).toBe(
fixture.componentInstance,
);
});
});
});
describe('string tokens', () => {
it('should be able to provide a string token', () => {
@Directive({
selector: '[injectorDir]',
providers: [{provide: 'test', useValue: 'provided'}],
standalone: false,
})
class InjectorDir {
constructor(@Inject('test') public value: string) {}
}
@Component({
template: '<div injectorDir></div>',
standalone: false,
})
class MyComp {
@ViewChild(InjectorDir) injectorDirInstance!: InjectorDir;
}
TestBed.configureTestingModule({declarations: [InjectorDir, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const injectorDir = fixture.componentInstance.injectorDirInstance;
expect(injectorDir.value).toBe('provided');
});
});
desc | {
"end_byte": 125097,
"start_byte": 115662,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_125101_133634 | ('attribute tokens', () => {
it('should be able to provide an attribute token', () => {
const TOKEN = new InjectionToken<string>('Some token');
function factory(token: string): string {
return token + ' with factory';
}
@Component({
selector: 'my-comp',
template: '...',
providers: [
{
provide: TOKEN,
deps: [[new Attribute('token')]],
useFactory: factory,
},
],
standalone: false,
})
class MyComp {
constructor(@Inject(TOKEN) readonly token: string) {}
}
@Component({
template: `<my-comp token='token'></my-comp>`,
standalone: false,
})
class WrapperComp {
@ViewChild(MyComp) myComp!: MyComp;
}
TestBed.configureTestingModule({declarations: [MyComp, WrapperComp]});
const fixture = TestBed.createComponent(WrapperComp);
fixture.detectChanges();
expect(fixture.componentInstance.myComp.token).toBe('token with factory');
});
});
describe('inject()', () => {
it('should work in a directive constructor', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
@Component({
standalone: true,
selector: 'test-cmp',
template: '{{value}}',
providers: [{provide: TOKEN, useValue: 'injected value'}],
})
class TestCmp {
value: string;
constructor() {
this.value = inject(TOKEN);
}
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('injected value');
});
it('should work in a service constructor when the service is provided on a directive', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
@Injectable()
class Service {
value: string;
constructor() {
this.value = inject(TOKEN);
}
}
@Component({
standalone: true,
selector: 'test-cmp',
template: '{{service.value}}',
providers: [Service, {provide: TOKEN, useValue: 'injected value'}],
})
class TestCmp {
constructor(readonly service: Service) {}
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('injected value');
});
it('should be able to inject special tokens like ChangeDetectorRef', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
@Component({
standalone: true,
selector: 'test-cmp',
template: '{{value}}',
})
class TestCmp {
cdr = inject(ChangeDetectorRef);
value = 'before';
}
const fixture = TestBed.createComponent(TestCmp);
fixture.componentInstance.value = 'after';
fixture.componentInstance.cdr.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('after');
});
it('should work in a service constructor', () => {
const TOKEN = new InjectionToken<string>('TOKEN', {
providedIn: 'root',
factory: () => 'injected value',
});
@Injectable({providedIn: 'root'})
class Service {
value: string;
constructor() {
this.value = inject(TOKEN);
}
}
const service = TestBed.inject(Service);
expect(service.value).toEqual('injected value');
});
it('should work in a useFactory definition for a service', () => {
const TOKEN = new InjectionToken<string>('TOKEN', {
providedIn: 'root',
factory: () => 'injected value',
});
@Injectable({
providedIn: 'root',
useFactory: () => new Service(inject(TOKEN)),
})
class Service {
constructor(readonly value: string) {}
}
expect(TestBed.inject(Service).value).toEqual('injected value');
});
it('should work for field injection', () => {
const TOKEN = new InjectionToken<string>('TOKEN', {
providedIn: 'root',
factory: () => 'injected value',
});
@Injectable({providedIn: 'root'})
class Service {
value = inject(TOKEN);
}
const service = TestBed.inject(Service);
expect(service.value).toEqual('injected value');
});
it('should not give non-node services access to the node context', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
@Injectable({providedIn: 'root'})
class Service {
value: string;
constructor() {
this.value = inject(TOKEN, InjectFlags.Optional) ?? 'default value';
}
}
@Component({
standalone: true,
selector: 'test-cmp',
template: '{{service.value}}',
providers: [{provide: TOKEN, useValue: 'injected value'}],
})
class TestCmp {
service: Service;
constructor() {
// `Service` is injected starting from the component context, where `inject` is
// `ɵɵdirectiveInject` under the hood. However, this should reach the root injector which
// should _not_ use `ɵɵdirectiveInject` to inject dependencies of `Service`, so `TOKEN`
// should not be visible to `Service`.
this.service = inject(Service);
}
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('default value');
});
describe('with an options object argument', () => {
it('should be able to optionally inject a service', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
@Component({
standalone: true,
template: '',
})
class TestCmp {
value = inject(TOKEN, {optional: true});
}
expect(TestBed.createComponent(TestCmp).componentInstance.value).toBeNull();
});
it('should be able to use skipSelf injection', () => {
const TOKEN = new InjectionToken<string>('TOKEN', {
providedIn: 'root',
factory: () => 'from root',
});
@Component({
standalone: true,
template: '',
providers: [{provide: TOKEN, useValue: 'from component'}],
})
class TestCmp {
value = inject(TOKEN, {skipSelf: true});
}
expect(TestBed.createComponent(TestCmp).componentInstance.value).toEqual('from root');
});
it('should be able to use self injection', () => {
const TOKEN = new InjectionToken<string>('TOKEN', {
providedIn: 'root',
factory: () => 'from root',
});
@Component({
standalone: true,
template: '',
})
class TestCmp {
value = inject(TOKEN, {self: true, optional: true});
}
expect(TestBed.createComponent(TestCmp).componentInstance.value).toBeNull();
});
it('should be able to use host injection', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
@Component({
standalone: true,
selector: 'child',
template: '{{value}}',
})
class ChildCmp {
value = inject(TOKEN, {host: true, optional: true}) ?? 'not found';
}
@Component({
standalone: true,
imports: [ChildCmp],
template: '<child></child>',
providers: [{provide: TOKEN, useValue: 'from parent'}],
encapsulation: ViewEncapsulation.None,
})
class ParentCmp {}
const fixture = TestBed.createComponent(ParentCmp);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('<child>not found</child>');
});
it('should not indicate it returns null when optional is explicitly false', () => {
const TOKEN = new InjectionToken<string>('TOKEN', {
providedIn: 'root',
factory: () => 'from root',
});
@Component({
standalone: true,
template: '',
})
class TestCmp {
// TypeScript will check if this assignment is legal, which won't be the case if
// inject() erroneously returns a `string|null` type here.
value: string = inject(TOKEN, {optional: false});
}
expect(TestBed.createComponent(TestCmp).componentInstance.value).toEqual('from root');
});
});
});
describe | {
"end_byte": 133634,
"start_byte": 125101,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_133638_139130 | jection flags', () => {
describe('represented as an options object argument', () => {
it('should be able to optionally inject a service', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
@Component({
standalone: true,
template: '',
})
class TestCmp {
nodeInjector = inject(Injector);
envInjector = inject(EnvironmentInjector);
}
const {nodeInjector, envInjector} = TestBed.createComponent(TestCmp).componentInstance;
expect(nodeInjector.get(TOKEN, undefined, {optional: true})).toBeNull();
expect(nodeInjector.get(TOKEN, undefined, InjectFlags.Optional)).toBeNull();
expect(envInjector.get(TOKEN, undefined, {optional: true})).toBeNull();
expect(envInjector.get(TOKEN, undefined, InjectFlags.Optional)).toBeNull();
});
it('should include `null` into the result type when the optional flag is used', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
@Component({
standalone: true,
template: '',
})
class TestCmp {
nodeInjector = inject(Injector);
envInjector = inject(EnvironmentInjector);
}
const {nodeInjector, envInjector} = TestBed.createComponent(TestCmp).componentInstance;
const flags: InjectOptions = {optional: true};
let nodeInjectorResult = nodeInjector.get(TOKEN, undefined, flags);
expect(nodeInjectorResult).toBe(null);
// Verify that `null` can be a valid value (from typing standpoint),
// the line below would fail a type check in case the result doesn't
// have `null` in the type.
nodeInjectorResult = null;
let envInjectorResult = envInjector.get(TOKEN, undefined, flags);
expect(envInjectorResult).toBe(null);
// Verify that `null` can be a valid value (from typing standpoint),
// the line below would fail a type check in case the result doesn't
// have `null` in the type.
envInjectorResult = null;
});
it('should be able to use skipSelf injection in NodeInjector', () => {
const TOKEN = new InjectionToken<string>('TOKEN', {
providedIn: 'root',
factory: () => 'from root',
});
@Component({
standalone: true,
template: '',
providers: [{provide: TOKEN, useValue: 'from component'}],
})
class TestCmp {
nodeInjector = inject(Injector);
}
const {nodeInjector} = TestBed.createComponent(TestCmp).componentInstance;
expect(nodeInjector.get(TOKEN, undefined, {skipSelf: true})).toEqual('from root');
});
it('should be able to use skipSelf injection in EnvironmentInjector', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
const parent = TestBed.inject(EnvironmentInjector);
const root = createEnvironmentInjector([{provide: TOKEN, useValue: 'from root'}], parent);
const child = createEnvironmentInjector([{provide: TOKEN, useValue: 'from child'}], root);
expect(child.get(TOKEN)).toEqual('from child');
expect(child.get(TOKEN, undefined, {skipSelf: true})).toEqual('from root');
expect(child.get(TOKEN, undefined, InjectFlags.SkipSelf)).toEqual('from root');
});
it('should be able to use self injection in NodeInjector', () => {
const TOKEN = new InjectionToken<string>('TOKEN', {
providedIn: 'root',
factory: () => 'from root',
});
@Component({
standalone: true,
template: '',
})
class TestCmp {
nodeInjector = inject(Injector);
}
const {nodeInjector} = TestBed.createComponent(TestCmp).componentInstance;
expect(nodeInjector.get(TOKEN, undefined, {self: true, optional: true})).toBeNull();
});
it('should be able to use self injection in EnvironmentInjector', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
const parent = TestBed.inject(EnvironmentInjector);
const root = createEnvironmentInjector([{provide: TOKEN, useValue: 'from root'}], parent);
const child = createEnvironmentInjector([], root);
expect(child.get(TOKEN, undefined, {self: true, optional: true})).toBeNull();
expect(child.get(TOKEN, undefined, InjectFlags.Self | InjectFlags.Optional)).toBeNull();
});
it('should be able to use host injection', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
@Component({
standalone: true,
selector: 'child',
template: '{{ a }}|{{ b }}',
})
class ChildCmp {
nodeInjector = inject(Injector);
a = this.nodeInjector.get(TOKEN, 'not found', {host: true, optional: true});
b = this.nodeInjector.get(TOKEN, 'not found', InjectFlags.Host | InjectFlags.Optional);
}
@Component({
standalone: true,
imports: [ChildCmp],
template: '<child></child>',
providers: [{provide: TOKEN, useValue: 'from parent'}],
encapsulation: ViewEncapsulation.None,
})
class ParentCmp {}
const fixture = TestBed.createComponent(ParentCmp);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('<child>not found|not found</child>');
});
});
});
describe | {
"end_byte": 139130,
"start_byte": 133638,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_139134_147664 | nInInjectionContext', () => {
it("should return the function's return value", () => {
const injector = TestBed.inject(EnvironmentInjector);
const returnValue = runInInjectionContext(injector, () => 3);
expect(returnValue).toBe(3);
});
it('should work with an NgModuleRef injector', () => {
const ref = TestBed.inject(NgModuleRef);
const returnValue = runInInjectionContext(ref.injector, () => 3);
expect(returnValue).toBe(3);
});
it('should return correct injector reference', () => {
const ngModuleRef = TestBed.inject(NgModuleRef);
const ref1 = runInInjectionContext(ngModuleRef.injector, () => inject(Injector));
const ref2 = ngModuleRef.injector.get(Injector);
expect(ref1).toBe(ref2);
});
it('should make inject() available', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
const injector = createEnvironmentInjector(
[{provide: TOKEN, useValue: 'from injector'}],
TestBed.inject(EnvironmentInjector),
);
const result = runInInjectionContext(injector, () => inject(TOKEN));
expect(result).toEqual('from injector');
});
it('should properly clean up after the function returns', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
const injector = TestBed.inject(EnvironmentInjector);
runInInjectionContext(injector, () => {});
expect(() => inject(TOKEN, InjectFlags.Optional)).toThrow();
});
it('should properly clean up after the function throws', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
const injector = TestBed.inject(EnvironmentInjector);
expect(() =>
runInInjectionContext(injector, () => {
throw new Error('crashes!');
}),
).toThrow();
expect(() => inject(TOKEN, InjectFlags.Optional)).toThrow();
});
it('should set the correct inject implementation', () => {
const TOKEN = new InjectionToken<string>('TOKEN', {
providedIn: 'root',
factory: () => 'from root',
});
@Component({
standalone: true,
template: '',
providers: [{provide: TOKEN, useValue: 'from component'}],
})
class TestCmp {
envInjector = inject(EnvironmentInjector);
tokenFromComponent = inject(TOKEN);
tokenFromEnvContext = runInInjectionContext(this.envInjector, () => inject(TOKEN));
// Attempt to inject ViewContainerRef within the environment injector's context. This should
// not be available, so the result should be `null`.
vcrFromEnvContext = runInInjectionContext(this.envInjector, () =>
inject(ViewContainerRef, InjectFlags.Optional),
);
}
const instance = TestBed.createComponent(TestCmp).componentInstance;
expect(instance.tokenFromComponent).toEqual('from component');
expect(instance.tokenFromEnvContext).toEqual('from root');
expect(instance.vcrFromEnvContext).toBeNull();
});
it('should support node injectors', () => {
@Component({
standalone: true,
template: '',
})
class TestCmp {
injector = inject(Injector);
vcrFromEnvContext = runInInjectionContext(this.injector, () =>
inject(ViewContainerRef, {optional: true}),
);
}
const instance = TestBed.createComponent(TestCmp).componentInstance;
expect(instance.vcrFromEnvContext).not.toBeNull();
});
it('should be reentrant', () => {
const TOKEN = new InjectionToken<string>('TOKEN', {
providedIn: 'root',
factory: () => 'from root',
});
const parentInjector = TestBed.inject(EnvironmentInjector);
const childInjector = createEnvironmentInjector(
[{provide: TOKEN, useValue: 'from child'}],
parentInjector,
);
const results = runInInjectionContext(parentInjector, () => {
const fromParentBefore = inject(TOKEN);
const fromChild = runInInjectionContext(childInjector, () => inject(TOKEN));
const fromParentAfter = inject(TOKEN);
return {fromParentBefore, fromChild, fromParentAfter};
});
expect(results.fromParentBefore).toEqual('from root');
expect(results.fromChild).toEqual('from child');
expect(results.fromParentAfter).toEqual('from root');
});
it('should not function on a destroyed injector', () => {
const injector = createEnvironmentInjector([], TestBed.inject(EnvironmentInjector));
injector.destroy();
expect(() => runInInjectionContext(injector, () => {})).toThrow();
});
});
describe('assertInInjectionContext', () => {
function placeholder() {}
it('should throw if not in an injection context', () => {
expect(() => assertInInjectionContext(placeholder)).toThrowMatching(
(e: Error) =>
e instanceof RuntimeError && e.code === RuntimeErrorCode.MISSING_INJECTION_CONTEXT,
);
});
it('should not throw if in an EnvironmentInjector context', () => {
expect(() => {
TestBed.runInInjectionContext(() => {
assertInInjectionContext(placeholder);
});
}).not.toThrow();
});
it('should not throw if in an element injector context', () => {
expect(() => {
@Component({
template: '',
standalone: false,
})
class EmptyCmp {}
const fixture = TestBed.createComponent(EmptyCmp);
runInInjectionContext(fixture.componentRef.injector, () => {
assertInInjectionContext(placeholder);
});
}).not.toThrow();
});
});
it('should be able to use Host in `useFactory` dependency config', () => {
// Scenario:
// ---------
// <root (provides token A)>
// <comp (provides token B via useFactory(@Host() @Inject(A))></comp>
// </root>
@Component({
selector: 'root',
template: '<comp></comp>',
viewProviders: [
{
provide: 'A',
useValue: 'A from Root',
},
],
standalone: false,
})
class Root {}
@Component({
selector: 'comp',
template: '{{ token }}',
viewProviders: [
{
provide: 'B',
deps: [[new Inject('A'), new Host()]],
useFactory: (token: string) => `${token} (processed by useFactory)`,
},
],
standalone: false,
})
class Comp {
constructor(@Inject('B') readonly token: string) {}
}
@Component({
template: `<root></root>`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({declarations: [Root, Comp, App]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('A from Root (processed by useFactory)');
});
it('should not lookup outside of the host element when Host is used in `useFactory`', () => {
// Scenario:
// ---------
// <root (provides token A)>
// <intermediate>
// <comp (provides token B via useFactory(@Host() @Inject(A))></comp>
// </intermediate>
// </root>
@Component({
selector: 'root',
template: '<intermediate></intermediate>',
viewProviders: [
{
provide: 'A',
useValue: 'A from Root',
},
],
standalone: false,
})
class Root {}
@Component({
selector: 'intermediate',
template: '<comp></comp>',
standalone: false,
})
class Intermediate {}
@Component({
selector: 'comp',
template: '{{ token }}',
viewProviders: [
{
provide: 'B',
deps: [[new Inject('A'), new Host(), new Optional()]],
useFactory: (token: string) =>
token ? `${token} (processed by useFactory)` : 'No token A found',
},
],
standalone: false,
})
class Comp {
constructor(@Inject('B') readonly token: string) {}
}
@Component({
template: `<root></root>`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({declarations: [Root, Comp, App, Intermediate]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
// Making sure that the `@Host` takes effect and token `A` becomes unavailable in DI since it's
// defined one level up from the Comp's host view.
expect(fixture.nativeElement.textContent).toBe('No token A found');
});
it('shou | {
"end_byte": 147664,
"start_byte": 139134,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_147668_151039 | ot cause cyclic dependency if same token is requested in deps with @SkipSelf', () => {
@Component({
selector: 'my-comp',
template: '...',
providers: [
{
provide: LOCALE_ID,
useFactory: () => 'ja-JP',
// Note: `LOCALE_ID` is also provided within APPLICATION_MODULE_PROVIDERS, so we use it
// here as a dep and making sure it doesn't cause cyclic dependency (since @SkipSelf is
// present)
deps: [[new Inject(LOCALE_ID), new Optional(), new SkipSelf()]],
},
],
standalone: false,
})
class MyComp {
constructor(@Inject(LOCALE_ID) public localeId: string) {}
}
TestBed.configureTestingModule({declarations: [MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.componentInstance.localeId).toBe('ja-JP');
});
it('module-level deps should not access Component/Directive providers', () => {
@Component({
selector: 'my-comp',
template: '...',
providers: [
{
provide: 'LOCALE_ID_DEP', //
useValue: 'LOCALE_ID_DEP_VALUE',
},
],
standalone: false,
})
class MyComp {
constructor(@Inject(LOCALE_ID) public localeId: string) {}
}
TestBed.configureTestingModule({
declarations: [MyComp],
providers: [
{
provide: LOCALE_ID,
// we expect `localeDepValue` to be undefined, since it's not provided at a module level
useFactory: (localeDepValue: any) => localeDepValue || 'en-GB',
deps: [[new Inject('LOCALE_ID_DEP'), new Optional()]],
},
],
});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.componentInstance.localeId).toBe('en-GB');
});
it('should skip current level while retrieving tokens if @SkipSelf is defined', () => {
@Component({
selector: 'my-comp',
template: '...',
providers: [{provide: LOCALE_ID, useFactory: () => 'en-GB'}],
standalone: false,
})
class MyComp {
constructor(@SkipSelf() @Inject(LOCALE_ID) public localeId: string) {}
}
TestBed.configureTestingModule({declarations: [MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
// takes `LOCALE_ID` from module injector, since we skip Component level with @SkipSelf
expect(fixture.componentInstance.localeId).toBe(DEFAULT_LOCALE_ID);
});
it('should work when injecting dependency in Directives', () => {
@Directive({
selector: '[dir]', //
providers: [{provide: LOCALE_ID, useValue: 'ja-JP'}],
standalone: false,
})
class MyDir {
constructor(@SkipSelf() @Inject(LOCALE_ID) public localeId: string) {}
}
@Component({
selector: 'my-comp',
template: '<div dir></div>',
providers: [{provide: LOCALE_ID, useValue: 'en-GB'}],
standalone: false,
})
class MyComp {
@ViewChild(MyDir) myDir!: MyDir;
constructor(@Inject(LOCALE_ID) public localeId: string) {}
}
TestBed.configureTestingModule({declarations: [MyDir, MyComp, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.componentInstance.myDir.localeId).toBe('en-GB');
});
describe | {
"end_byte": 151039,
"start_byte": 147668,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_151043_157945 | ttribute', () => {
it('should inject attributes', () => {
@Directive({
selector: '[dir]',
standalone: false,
})
class MyDir {
constructor(
@Attribute('exist') public exist: string,
@Attribute('nonExist') public nonExist: string,
) {}
}
@Component({
template: '<div dir exist="existValue" other="ignore"></div>',
standalone: false,
})
class MyComp {
@ViewChild(MyDir) directiveInstance!: MyDir;
}
TestBed.configureTestingModule({declarations: [MyDir, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const directive = fixture.componentInstance.directiveInstance;
expect(directive.exist).toBe('existValue');
expect(directive.nonExist).toBeNull();
});
it('should inject attributes on <ng-template>', () => {
@Directive({
selector: '[dir]',
standalone: false,
})
class MyDir {
constructor(
@Attribute('exist') public exist: string,
@Attribute('dir') public myDirectiveAttrValue: string,
) {}
}
@Component({
template: '<ng-template dir="initial" exist="existValue" other="ignore"></ng-template>',
standalone: false,
})
class MyComp {
@ViewChild(MyDir) directiveInstance!: MyDir;
}
TestBed.configureTestingModule({declarations: [MyDir, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const directive = fixture.componentInstance.directiveInstance;
expect(directive.exist).toBe('existValue');
expect(directive.myDirectiveAttrValue).toBe('initial');
});
it('should inject attributes on <ng-container>', () => {
@Directive({
selector: '[dir]',
standalone: false,
})
class MyDir {
constructor(
@Attribute('exist') public exist: string,
@Attribute('dir') public myDirectiveAttrValue: string,
) {}
}
@Component({
template: '<ng-container dir="initial" exist="existValue" other="ignore"></ng-container>',
standalone: false,
})
class MyComp {
@ViewChild(MyDir) directiveInstance!: MyDir;
}
TestBed.configureTestingModule({declarations: [MyDir, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const directive = fixture.componentInstance.directiveInstance;
expect(directive.exist).toBe('existValue');
expect(directive.myDirectiveAttrValue).toBe('initial');
});
it('should be able to inject different kinds of attributes', () => {
@Directive({
selector: '[dir]',
standalone: false,
})
class MyDir {
constructor(
@Attribute('class') public className: string,
@Attribute('style') public inlineStyles: string,
@Attribute('other-attr') public otherAttr: string,
) {}
}
@Component({
template:
'<div dir style="margin: 1px; color: red;" class="hello there" other-attr="value"></div>',
standalone: false,
})
class MyComp {
@ViewChild(MyDir) directiveInstance!: MyDir;
}
TestBed.configureTestingModule({declarations: [MyDir, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const directive = fixture.componentInstance.directiveInstance;
expect(directive.otherAttr).toBe('value');
expect(directive.className).toBe('hello there');
expect(directive.inlineStyles).toMatch(/color:\s*red/);
expect(directive.inlineStyles).toMatch(/margin:\s*1px/);
});
it('should not inject attributes with namespace', () => {
@Directive({
selector: '[dir]',
standalone: false,
})
class MyDir {
constructor(
@Attribute('exist') public exist: string,
@Attribute('svg:exist') public namespacedExist: string,
@Attribute('other') public other: string,
) {}
}
@Component({
template:
'<div dir exist="existValue" svg:exist="testExistValue" other="otherValue"></div>',
standalone: false,
})
class MyComp {
@ViewChild(MyDir) directiveInstance!: MyDir;
}
TestBed.configureTestingModule({declarations: [MyDir, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const directive = fixture.componentInstance.directiveInstance;
expect(directive.exist).toBe('existValue');
expect(directive.namespacedExist).toBeNull();
expect(directive.other).toBe('otherValue');
});
it('should not inject attributes representing bindings and outputs', () => {
@Directive({
selector: '[dir]',
standalone: false,
})
class MyDir {
@Input() binding!: string;
@Output() output = new EventEmitter();
constructor(
@Attribute('exist') public exist: string,
@Attribute('binding') public bindingAttr: string,
@Attribute('output') public outputAttr: string,
@Attribute('other') public other: string,
) {}
}
@Component({
template:
'<div dir exist="existValue" [binding]="bindingValue" (output)="outputValue" other="otherValue" ignore="ignoreValue"></div>',
standalone: false,
})
class MyComp {
@ViewChild(MyDir) directiveInstance!: MyDir;
}
TestBed.configureTestingModule({declarations: [MyDir, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const directive = fixture.componentInstance.directiveInstance;
expect(directive.exist).toBe('existValue');
expect(directive.bindingAttr).toBeNull();
expect(directive.outputAttr).toBeNull();
expect(directive.other).toBe('otherValue');
});
it('should inject `null` for attributes with data bindings', () => {
@Directive({
selector: '[dir]',
standalone: false,
})
class MyDir {
constructor(@Attribute('title') public attrValue: string) {}
}
@Component({
template: '<div dir title="title {{ value }}"></div>',
standalone: false,
})
class MyComp {
@ViewChild(MyDir) directiveInstance!: MyDir;
value = 'value';
}
TestBed.configureTestingModule({declarations: [MyDir, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.componentInstance.directiveInstance.attrValue).toBeNull();
expect(fixture.nativeElement.querySelector('div').getAttribute('title')).toBe('title value');
});
});
describe | {
"end_byte": 157945,
"start_byte": 151043,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_157949_166907 | stAttributeToken', () => {
it('should inject an attribute on an element node', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = inject(new HostAttributeToken('some-attr'));
}
@Component({
standalone: true,
template: '<div dir some-attr="foo" other="ignore"></div>',
imports: [Dir],
})
class TestCmp {
@ViewChild(Dir) dir!: Dir;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.componentInstance.dir.value).toBe('foo');
});
it('should inject an attribute on <ng-template>', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = inject(new HostAttributeToken('some-attr'));
}
@Component({
standalone: true,
template: '<ng-template dir some-attr="foo" other="ignore"></ng-template>',
imports: [Dir],
})
class TestCmp {
@ViewChild(Dir) dir!: Dir;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.componentInstance.dir.value).toBe('foo');
});
it('should inject an attribute on <ng-container>', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = inject(new HostAttributeToken('some-attr'));
}
@Component({
standalone: true,
template: '<ng-container dir some-attr="foo" other="ignore"></ng-container>',
imports: [Dir],
})
class TestCmp {
@ViewChild(Dir) dir!: Dir;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.componentInstance.dir.value).toBe('foo');
});
it('should be able to inject different kinds of attributes', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
className = inject(new HostAttributeToken('class'));
inlineStyles = inject(new HostAttributeToken('style'));
value = inject(new HostAttributeToken('some-attr'));
}
@Component({
standalone: true,
template: `
<div
dir
style="margin: 1px; color: red;"
class="hello there"
some-attr="foo"
other="ignore"></div>
`,
imports: [Dir],
})
class TestCmp {
@ViewChild(Dir) dir!: Dir;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const directive = fixture.componentInstance.dir;
expect(directive.className).toBe('hello there');
expect(directive.inlineStyles).toMatch(/color:\s*red/);
expect(directive.inlineStyles).toMatch(/margin:\s*1px/);
expect(directive.value).toBe('foo');
});
it('should throw a DI error when injecting a non-existent attribute', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = inject(new HostAttributeToken('some-attr'));
}
@Component({
standalone: true,
template: '<div dir other="ignore"></div>',
imports: [Dir],
})
class TestCmp {
@ViewChild(Dir) dir!: Dir;
}
expect(() => TestBed.createComponent(TestCmp)).toThrowError(
/No provider for HostAttributeToken some-attr found/,
);
});
it('should not throw a DI error when injecting a non-existent attribute with optional: true', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = inject(new HostAttributeToken('some-attr'), {optional: true});
}
@Component({
standalone: true,
template: '<div dir other="ignore"></div>',
imports: [Dir],
})
class TestCmp {
@ViewChild(Dir) dir!: Dir;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.componentInstance.dir.value).toBe(null);
});
it('should not inject attributes with namespace', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = inject(new HostAttributeToken('some-attr'), {optional: true});
namespaceExists = inject(new HostAttributeToken('svg:exist'), {optional: true});
other = inject(new HostAttributeToken('other'), {optional: true});
}
@Component({
standalone: true,
template: `
<div dir some-attr="foo" svg:exists="testExistValue" other="otherValue"></div>
`,
imports: [Dir],
})
class TestCmp {
@ViewChild(Dir) dir!: Dir;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const directive = fixture.componentInstance.dir;
expect(directive.value).toBe('foo');
expect(directive.namespaceExists).toBe(null);
expect(directive.other).toBe('otherValue');
});
it('should not inject attributes representing bindings and outputs', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
@Input() binding!: string;
@Output() output = new EventEmitter();
exists = inject(new HostAttributeToken('exists'));
bindingAttr = inject(new HostAttributeToken('binding'), {optional: true});
outputAttr = inject(new HostAttributeToken('output'), {optional: true});
other = inject(new HostAttributeToken('other'));
}
@Component({
standalone: true,
imports: [Dir],
template: `
<div
dir
exists="existsValue"
[binding]="bindingValue"
(output)="noop()"
other="otherValue"
ignore="ignoreValue"></div>`,
})
class TestCmp {
@ViewChild(Dir) dir!: Dir;
bindingValue = 'hello';
noop() {}
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
const directive = fixture.componentInstance.dir;
expect(directive.exists).toBe('existsValue');
expect(directive.bindingAttr).toBe(null);
expect(directive.outputAttr).toBe(null);
expect(directive.other).toBe('otherValue');
});
it('should not inject data-bound attributes', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = inject(new HostAttributeToken('title'), {optional: true});
}
@Component({
standalone: true,
template: '<div dir title="foo {{value}}" other="ignore"></div>',
imports: [Dir],
})
class TestCmp {
@ViewChild(Dir) dir!: Dir;
value = 123;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.componentInstance.dir.value).toBe(null);
expect(fixture.nativeElement.querySelector('[dir]').getAttribute('title')).toBe('foo 123');
});
it('should inject an attribute using @Inject', () => {
const TOKEN = new HostAttributeToken('some-attr');
@Directive({selector: '[dir]', standalone: true})
class Dir {
constructor(@Inject(TOKEN) readonly value: string) {}
}
@Component({
standalone: true,
template: '<div dir some-attr="foo" other="ignore"></div>',
imports: [Dir],
})
class TestCmp {
@ViewChild(Dir) dir!: Dir;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.componentInstance.dir.value).toBe('foo');
});
it('should throw when injecting a non-existent attribute using @Inject', () => {
const TOKEN = new HostAttributeToken('some-attr');
@Directive({selector: '[dir]', standalone: true})
class Dir {
constructor(@Inject(TOKEN) readonly value: string) {}
}
@Component({
standalone: true,
template: '<div dir other="ignore"></div>',
imports: [Dir],
})
class TestCmp {
@ViewChild(Dir) dir!: Dir;
}
expect(() => TestBed.createComponent(TestCmp)).toThrowError(
/No provider for HostAttributeToken some-attr found/,
);
});
it('should not throw when injecting a non-existent attribute using @Inject @Optional', () => {
const TOKEN = new HostAttributeToken('some-attr');
@Directive({selector: '[dir]', standalone: true})
class Dir {
constructor(@Inject(TOKEN) @Optional() readonly value: string | null) {}
}
@Component({
standalone: true,
template: '<div dir other="ignore"></div>',
imports: [Dir],
})
class TestCmp {
@ViewChild(Dir) dir!: Dir;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.componentInstance.dir.value).toBe(null);
});
});
describe | {
"end_byte": 166907,
"start_byte": 157949,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_166911_173265 | ST_TAG_NAME', () => {
it('should inject the tag name on an element node', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = inject(HOST_TAG_NAME);
}
@Component({
standalone: true,
template: `
<div dir #v1></div>
<span dir #v2></span>
<svg dir #v3></svg>
<custom-component dir #v4></custom-component>
<video dir #v5></video>
`,
imports: [Dir],
})
class TestCmp {
@ViewChild('v1', {read: Dir}) value1!: Dir;
@ViewChild('v2', {read: Dir}) value2!: Dir;
@ViewChild('v3', {read: Dir}) value3!: Dir;
@ViewChild('v4', {read: Dir}) value4!: Dir;
@ViewChild('v5', {read: Dir}) value5!: Dir;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.componentInstance.value1.value).toBe('div');
expect(fixture.componentInstance.value2.value).toBe('span');
expect(fixture.componentInstance.value3.value).toBe('svg');
expect(fixture.componentInstance.value4.value).toBe('custom-component');
expect(fixture.componentInstance.value5.value).toBe('video');
});
it('should throw a DI error when injecting into non-DOM nodes', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = inject(HOST_TAG_NAME);
}
@Component({
standalone: true,
template: '<ng-container dir></ng-container>',
imports: [Dir],
})
class TestNgContainer {
@ViewChild(Dir) dir!: Dir;
}
@Component({
standalone: true,
template: '<ng-template dir></ng-template>',
imports: [Dir],
})
class TestNgTemplate {
@ViewChild(Dir) dir!: Dir;
}
expect(() => TestBed.createComponent(TestNgContainer)).toThrowError(
/HOST_TAG_NAME was used on an <ng-container> which doesn't have an underlying element in the DOM/,
);
expect(() => TestBed.createComponent(TestNgTemplate)).toThrowError(
/HOST_TAG_NAME was used on an <ng-template> which doesn't have an underlying element in the DOM/,
);
});
it('should not throw a DI error when injecting into non-DOM nodes with optional: true', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = inject(HOST_TAG_NAME, {optional: true});
}
@Component({
standalone: true,
template: '<ng-container dir></ng-container>',
imports: [Dir],
})
class TestCmp {
@ViewChild(Dir) dir!: Dir;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.componentInstance.dir.value).toBe(null);
});
});
it('should support dependencies in Pipes used inside ICUs', () => {
@Injectable()
class MyService {
transform(value: string): string {
return `${value} (transformed)`;
}
}
@Pipe({
name: 'somePipe',
standalone: false,
})
class MyPipe {
constructor(private service: MyService) {}
transform(value: any): any {
return this.service.transform(value);
}
}
@Component({
template: `
<div i18n>{
count, select,
=1 {One}
other {Other value is: {{count | somePipe}}}
}</div>
`,
standalone: false,
})
class MyComp {
count = '2';
}
TestBed.configureTestingModule({
declarations: [MyPipe, MyComp],
providers: [MyService],
});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toContain('Other value is: 2 (transformed)');
});
it('should support dependencies in Pipes used inside i18n blocks', () => {
@Injectable()
class MyService {
transform(value: string): string {
return `${value} (transformed)`;
}
}
@Pipe({
name: 'somePipe',
standalone: false,
})
class MyPipe {
constructor(private service: MyService) {}
transform(value: any): any {
return this.service.transform(value);
}
}
@Component({
template: `
<ng-template #source i18n>
{{count | somePipe}} <span>items</span>
</ng-template>
<ng-container #target></ng-container>
`,
standalone: false,
})
class MyComp {
count = '2';
@ViewChild('target', {read: ViewContainerRef}) target!: ViewContainerRef;
@ViewChild('source', {read: TemplateRef}) source!: TemplateRef<any>;
create() {
this.target.createEmbeddedView(this.source);
}
}
TestBed.configureTestingModule({
declarations: [MyPipe, MyComp],
providers: [MyService],
});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
fixture.componentInstance.create();
fixture.detectChanges();
expect(fixture.nativeElement.textContent.trim()).toBe('2 (transformed) items');
});
// TODO: https://angular-team.atlassian.net/browse/FW-1779
it('should prioritize useFactory over useExisting', () => {
abstract class Base {}
@Directive({
selector: '[dirA]',
standalone: false,
})
class DirA implements Base {}
@Directive({
selector: '[dirB]',
standalone: false,
})
class DirB implements Base {}
const PROVIDER = {provide: Base, useExisting: DirA, useFactory: () => new DirB()};
@Component({
selector: 'child',
template: '',
providers: [PROVIDER],
standalone: false,
})
class Child {
constructor(readonly base: Base) {}
}
@Component({
template: `<div dirA> <child></child> </div>`,
standalone: false,
})
class App {
@ViewChild(DirA) dirA!: DirA;
@ViewChild(Child) child!: Child;
}
const fixture = TestBed.configureTestingModule({
declarations: [DirA, DirB, App, Child],
}).createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.dirA).not.toEqual(
fixture.componentInstance.child.base,
'should not get dirA from parent, but create new dirB from the useFactory provider',
);
});
describe | {
"end_byte": 173265,
"start_byte": 166911,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_173269_177615 | ovider access on the same node', () => {
const token = new InjectionToken<number>('token');
it('pipes should access providers from the component they are on', () => {
@Pipe({
name: 'token',
standalone: false,
})
class TokenPipe {
constructor(@Inject(token) private _token: string) {}
transform(value: string): string {
return value + this._token;
}
}
@Component({
selector: 'child-comp',
template: '{{value}}',
providers: [{provide: token, useValue: 'child'}],
standalone: false,
})
class ChildComp {
@Input() value: any;
}
@Component({
template: `<child-comp [value]="'' | token"></child-comp>`,
providers: [{provide: token, useValue: 'parent'}],
standalone: false,
})
class App {}
TestBed.configureTestingModule({declarations: [App, ChildComp, TokenPipe]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.nativeElement.textContent.trim()).toBe('child');
});
it('pipes should not access viewProviders from the component they are on', () => {
@Pipe({
name: 'token',
standalone: false,
})
class TokenPipe {
constructor(@Inject(token) private _token: string) {}
transform(value: string): string {
return value + this._token;
}
}
@Component({
selector: 'child-comp',
template: '{{value}}',
viewProviders: [{provide: token, useValue: 'child'}],
standalone: false,
})
class ChildComp {
@Input() value: any;
}
@Component({
template: `<child-comp [value]="'' | token"></child-comp>`,
viewProviders: [{provide: token, useValue: 'parent'}],
standalone: false,
})
class App {}
TestBed.configureTestingModule({declarations: [App, ChildComp, TokenPipe]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.nativeElement.textContent.trim()).toBe('parent');
});
it('directives should access providers from the component they are on', () => {
@Directive({
selector: '[dir]',
standalone: false,
})
class Dir {
constructor(@Inject(token) public token: string) {}
}
@Component({
selector: 'child-comp',
template: '',
providers: [{provide: token, useValue: 'child'}],
standalone: false,
})
class ChildComp {}
@Component({
template: '<child-comp dir></child-comp>',
providers: [{provide: token, useValue: 'parent'}],
standalone: false,
})
class App {
@ViewChild(Dir) dir!: Dir;
}
TestBed.configureTestingModule({declarations: [App, ChildComp, Dir]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.dir.token).toBe('child');
});
it('directives should not access viewProviders from the component they are on', () => {
@Directive({
selector: '[dir]',
standalone: false,
})
class Dir {
constructor(@Inject(token) public token: string) {}
}
@Component({
selector: 'child-comp',
template: '',
viewProviders: [{provide: token, useValue: 'child'}],
standalone: false,
})
class ChildComp {}
@Component({
template: '<child-comp dir></child-comp>',
viewProviders: [{provide: token, useValue: 'parent'}],
standalone: false,
})
class App {
@ViewChild(Dir) dir!: Dir;
}
TestBed.configureTestingModule({declarations: [App, ChildComp, Dir]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.dir.token).toBe('parent');
});
});
it('should not be able to inject ViewRef', () => {
@Component({
template: '',
standalone: false,
})
class App {
constructor(_viewRef: ViewRef) {}
}
TestBed.configureTestingModule({declarations: [App]});
expect(() => TestBed.createComponent(App)).toThrowError(/NullInjectorError/);
});
describe | {
"end_byte": 177615,
"start_byte": 173269,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_177619_186682 | jector when creating embedded view', () => {
const token = new InjectionToken<string>('greeting');
@Directive({
selector: 'menu-trigger',
standalone: false,
})
class MenuTrigger {
@Input('triggerFor') menu!: TemplateRef<unknown>;
constructor(private viewContainerRef: ViewContainerRef) {}
open(injector: Injector | undefined) {
this.viewContainerRef.createEmbeddedView(this.menu, undefined, {injector});
}
}
it('should be able to provide an injection token through a custom injector', () => {
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(@Inject(token) public tokenValue: string) {}
}
@Component({
template: `
<menu-trigger [triggerFor]="menuTemplate"></menu-trigger>
<ng-template #menuTemplate>
<menu></menu>
</ng-template>
`,
standalone: false,
})
class App {
@ViewChild(MenuTrigger) trigger!: MenuTrigger;
@ViewChild(Menu) menu!: Menu;
}
TestBed.configureTestingModule({declarations: [App, MenuTrigger, Menu]});
const injector = Injector.create({providers: [{provide: token, useValue: 'hello'}]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.componentInstance.trigger.open(injector);
fixture.detectChanges();
expect(fixture.componentInstance.menu.tokenValue).toBe('hello');
});
it('should check only the current node with @Self when providing an injection token through an embedded view injector', () => {
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(@Inject(token) @Self() @Optional() public tokenValue: string) {}
}
@Component({
template: `
<menu-trigger [triggerFor]="menuTemplate"></menu-trigger>
<ng-template #menuTemplate>
<menu></menu>
</ng-template>
`,
providers: [{provide: token, useValue: 'root'}],
standalone: false,
})
class App {
@ViewChild(MenuTrigger) trigger!: MenuTrigger;
@ViewChild(Menu) menu!: Menu;
}
TestBed.configureTestingModule({declarations: [App, MenuTrigger, Menu]});
const injector = Injector.create({providers: [{provide: token, useValue: 'hello'}]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.componentInstance.trigger.open(injector);
fixture.detectChanges();
expect(fixture.componentInstance.menu.tokenValue).toBeNull();
});
it('should be able to provide an injection token to a nested template through a custom injector', () => {
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(@Inject(token) public tokenValue: string) {}
}
@Component({
template: `
<menu-trigger #outerTrigger [triggerFor]="outerTemplate"></menu-trigger>
<ng-template #outerTemplate>
<menu></menu>
<menu-trigger #innerTrigger [triggerFor]="innerTemplate"></menu-trigger>
<ng-template #innerTemplate>
<menu #innerMenu></menu>
</ng-template>
</ng-template>
`,
standalone: false,
})
class App {
@ViewChild('outerTrigger', {read: MenuTrigger}) outerTrigger!: MenuTrigger;
@ViewChild('innerTrigger', {read: MenuTrigger}) innerTrigger!: MenuTrigger;
@ViewChild('innerMenu', {read: Menu}) innerMenu!: Menu;
}
TestBed.configureTestingModule({declarations: [App, MenuTrigger, Menu]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.componentInstance.outerTrigger.open(
Injector.create({providers: [{provide: token, useValue: 'hello'}]}),
);
fixture.detectChanges();
fixture.componentInstance.innerTrigger.open(undefined);
fixture.detectChanges();
expect(fixture.componentInstance.innerMenu.tokenValue).toBe('hello');
});
it('should be able to resolve a token from a custom grandparent injector if the token is not provided in the parent', () => {
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(@Inject(token) public tokenValue: string) {}
}
@Component({
template: `
<menu-trigger #grandparentTrigger [triggerFor]="grandparentTemplate"></menu-trigger>
<ng-template #grandparentTemplate>
<menu></menu>
<menu-trigger #parentTrigger [triggerFor]="parentTemplate"></menu-trigger>
<ng-template #parentTemplate>
<menu></menu>
<menu-trigger #childTrigger [triggerFor]="childTemplate"></menu-trigger>
<ng-template #childTemplate>
<menu #childMenu></menu>
</ng-template>
</ng-template>
</ng-template>
`,
standalone: false,
})
class App {
@ViewChild('grandparentTrigger', {read: MenuTrigger}) grandparentTrigger!: MenuTrigger;
@ViewChild('parentTrigger', {read: MenuTrigger}) parentTrigger!: MenuTrigger;
@ViewChild('childTrigger', {read: MenuTrigger}) childTrigger!: MenuTrigger;
@ViewChild('childMenu', {read: Menu}) childMenu!: Menu;
}
TestBed.configureTestingModule({declarations: [App, MenuTrigger, Menu]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.componentInstance.grandparentTrigger.open(
Injector.create({providers: [{provide: token, useValue: 'hello'}]}),
);
fixture.detectChanges();
fixture.componentInstance.parentTrigger.open(Injector.create({providers: []}));
fixture.detectChanges();
fixture.componentInstance.childTrigger.open(undefined);
fixture.detectChanges();
expect(fixture.componentInstance.childMenu.tokenValue).toBe('hello');
});
it('should resolve value from node injector if it is lower than embedded view injector', () => {
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(@Inject(token) public tokenValue: string) {}
}
@Component({
selector: 'wrapper',
providers: [{provide: token, useValue: 'hello from wrapper'}],
template: `
<menu-trigger [triggerFor]="menuTemplate"></menu-trigger>
<ng-template #menuTemplate>
<menu></menu>
</ng-template>
`,
standalone: false,
})
class Wrapper {
@ViewChild(MenuTrigger) trigger!: MenuTrigger;
@ViewChild(Menu) menu!: Menu;
}
@Component({
template: `
<menu-trigger [triggerFor]="menuTemplate"></menu-trigger>
<ng-template #menuTemplate>
<wrapper></wrapper>
</ng-template>
`,
standalone: false,
})
class App {
@ViewChild(MenuTrigger) trigger!: MenuTrigger;
@ViewChild(Wrapper) wrapper!: Wrapper;
}
TestBed.configureTestingModule({declarations: [App, MenuTrigger, Menu, Wrapper]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.componentInstance.trigger.open(
Injector.create({providers: [{provide: token, useValue: 'hello from injector'}]}),
);
fixture.detectChanges();
fixture.componentInstance.wrapper.trigger.open(undefined);
fixture.detectChanges();
expect(fixture.componentInstance.wrapper.menu.tokenValue).toBe('hello from wrapper');
});
it('should be able to inject a value provided at the module level', () => {
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(@Inject(token) public tokenValue: string) {}
}
@Component({
template: `
<menu-trigger [triggerFor]="menuTemplate"></menu-trigger>
<ng-template #menuTemplate>
<menu></menu>
</ng-template>
`,
standalone: false,
})
class App {
@ViewChild(MenuTrigger) trigger!: MenuTrigger;
@ViewChild(Menu) menu!: Menu;
}
@NgModule({
declarations: [App, MenuTrigger, Menu],
exports: [App, MenuTrigger, Menu],
providers: [{provide: token, useValue: 'hello'}],
})
class Module {}
TestBed.configureTestingModule({imports: [Module]});
const injector = Injector.create({providers: []});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.componentInstance.trigger.open(injector);
fixture.detectChanges();
expect(fixture.componentInstance.menu.tokenValue).toBe('hello');
});
it('sh | {
"end_byte": 186682,
"start_byte": 177619,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_186688_195912 | ave value from custom injector take precedence over module injector', () => {
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(@Inject(token) public tokenValue: string) {}
}
@Component({
template: `
<menu-trigger [triggerFor]="menuTemplate"></menu-trigger>
<ng-template #menuTemplate>
<menu></menu>
</ng-template>
`,
standalone: false,
})
class App {
@ViewChild(MenuTrigger) trigger!: MenuTrigger;
@ViewChild(Menu) menu!: Menu;
}
@NgModule({
declarations: [App, MenuTrigger, Menu],
exports: [App, MenuTrigger, Menu],
providers: [{provide: token, useValue: 'hello from module'}],
})
class Module {}
TestBed.configureTestingModule({imports: [Module]});
const injector = Injector.create({
providers: [{provide: token, useValue: 'hello from injector'}],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.componentInstance.trigger.open(injector);
fixture.detectChanges();
expect(fixture.componentInstance.menu.tokenValue).toBe('hello from injector');
});
it('should have value from custom injector take precedence over parent injector', () => {
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(@Inject(token) public tokenValue: string) {}
}
@Component({
template: `
<menu-trigger [triggerFor]="menuTemplate"></menu-trigger>
<ng-template #menuTemplate>
<menu></menu>
</ng-template>
`,
providers: [{provide: token, useValue: 'hello from parent'}],
standalone: false,
})
class App {
@ViewChild(MenuTrigger) trigger!: MenuTrigger;
@ViewChild(Menu) menu!: Menu;
}
@NgModule({
declarations: [App, MenuTrigger, Menu],
exports: [App, MenuTrigger, Menu],
})
class Module {}
TestBed.configureTestingModule({imports: [Module]});
const injector = Injector.create({
providers: [{provide: token, useValue: 'hello from injector'}],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.componentInstance.trigger.open(injector);
fixture.detectChanges();
expect(fixture.componentInstance.menu.tokenValue).toBe('hello from injector');
});
it('should be able to inject built-in tokens when a custom injector is provided', () => {
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(
public elementRef: ElementRef,
public changeDetectorRef: ChangeDetectorRef,
) {}
}
@Component({
template: `
<menu-trigger [triggerFor]="menuTemplate"></menu-trigger>
<ng-template #menuTemplate>
<menu></menu>
</ng-template>
`,
standalone: false,
})
class App {
@ViewChild(MenuTrigger) trigger!: MenuTrigger;
@ViewChild(Menu) menu!: Menu;
}
TestBed.configureTestingModule({declarations: [App, MenuTrigger, Menu]});
const injector = Injector.create({providers: []});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.componentInstance.trigger.open(injector);
fixture.detectChanges();
expect(fixture.componentInstance.menu.elementRef.nativeElement).toBe(
fixture.nativeElement.querySelector('menu'),
);
expect(fixture.componentInstance.menu.changeDetectorRef).toBeTruthy();
});
it('should have value from parent component injector take precedence over module injector', () => {
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(@Inject(token) public tokenValue: string) {}
}
@Component({
template: `
<menu-trigger [triggerFor]="menuTemplate"></menu-trigger>
<ng-template #menuTemplate>
<menu></menu>
</ng-template>
`,
providers: [{provide: token, useValue: 'hello from parent'}],
standalone: false,
})
class App {
@ViewChild(MenuTrigger) trigger!: MenuTrigger;
@ViewChild(Menu) menu!: Menu;
}
@NgModule({
declarations: [App, MenuTrigger, Menu],
exports: [App, MenuTrigger, Menu],
providers: [{provide: token, useValue: 'hello from module'}],
})
class Module {}
TestBed.configureTestingModule({imports: [Module]});
const injector = Injector.create({providers: []});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.componentInstance.trigger.open(injector);
fixture.detectChanges();
expect(fixture.componentInstance.menu.tokenValue).toBe('hello from parent');
});
it('should be able to inject an injectable with dependencies', () => {
@Injectable()
class Greeter {
constructor(@Inject(token) private tokenValue: string) {}
greet() {
return `hello from ${this.tokenValue}`;
}
}
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(public greeter: Greeter) {}
}
@Component({
template: `
<menu-trigger [triggerFor]="menuTemplate"></menu-trigger>
<ng-template #menuTemplate>
<menu></menu>
</ng-template>
`,
standalone: false,
})
class App {
@ViewChild(MenuTrigger) trigger!: MenuTrigger;
@ViewChild(Menu) menu!: Menu;
}
@NgModule({
declarations: [App, MenuTrigger, Menu],
exports: [App, MenuTrigger, Menu],
providers: [{provide: token, useValue: 'module'}],
})
class Module {}
TestBed.configureTestingModule({imports: [Module]});
const injector = Injector.create({
providers: [
{provide: Greeter, useClass: Greeter},
{provide: token, useValue: 'injector'},
],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.componentInstance.trigger.open(injector);
fixture.detectChanges();
expect(fixture.componentInstance.menu.greeter.greet()).toBe('hello from injector');
});
it('should be able to inject a value from a grandparent component when a custom injector is provided', () => {
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(@Inject(token) public tokenValue: string) {}
}
@Component({
selector: 'parent',
template: `
<menu-trigger [triggerFor]="menuTemplate"></menu-trigger>
<ng-template #menuTemplate>
<menu></menu>
</ng-template>
`,
standalone: false,
})
class Parent {
@ViewChild(MenuTrigger) trigger!: MenuTrigger;
@ViewChild(Menu) menu!: Menu;
}
@Component({
template: '<parent></parent>',
providers: [{provide: token, useValue: 'hello from grandparent'}],
standalone: false,
})
class GrandParent {
@ViewChild(Parent) parent!: Parent;
}
TestBed.configureTestingModule({declarations: [GrandParent, Parent, MenuTrigger, Menu]});
const injector = Injector.create({providers: []});
const fixture = TestBed.createComponent(GrandParent);
fixture.detectChanges();
fixture.componentInstance.parent.trigger.open(injector);
fixture.detectChanges();
expect(fixture.componentInstance.parent.menu.tokenValue).toBe('hello from grandparent');
});
it('should be able to use a custom injector when created through TemplateRef', () => {
let injectedValue: string | undefined;
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(@Inject(token) tokenValue: string) {
injectedValue = tokenValue;
}
}
@Component({
template: `
<ng-template>
<menu></menu>
</ng-template>
`,
standalone: false,
})
class App {
@ViewChild(TemplateRef) template!: TemplateRef<unknown>;
}
@NgModule({
declarations: [App, Menu],
exports: [App, Menu],
providers: [{provide: token, useValue: 'hello from module'}],
})
class Module {}
TestBed.configureTestingModule({imports: [Module]});
const injector = Injector.create({
providers: [{provide: token, useValue: 'hello from injector'}],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.componentInstance.template.createEmbeddedView({}, injector);
fixture.detectChanges();
expect(injectedValue).toBe('hello from injector');
});
it('sh | {
"end_byte": 195912,
"start_byte": 186688,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_195918_205081 | se a custom injector when the view is created outside of the declaration view', () => {
const declarerToken = new InjectionToken<string>('declarerToken');
const creatorToken = new InjectionToken<string>('creatorToken');
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(
@Inject(token) public tokenValue: string,
@Optional() @Inject(declarerToken) public declarerTokenValue: string,
@Optional() @Inject(creatorToken) public creatorTokenValue: string,
) {}
}
@Component({
selector: 'declarer',
template: '<ng-template><menu></menu></ng-template>',
providers: [{provide: declarerToken, useValue: 'hello from declarer'}],
standalone: false,
})
class Declarer {
@ViewChild(Menu) menu!: Menu;
@ViewChild(TemplateRef) template!: TemplateRef<unknown>;
}
@Component({
selector: 'creator',
template: '<menu-trigger></menu-trigger>',
providers: [{provide: creatorToken, useValue: 'hello from creator'}],
standalone: false,
})
class Creator {
@ViewChild(MenuTrigger) trigger!: MenuTrigger;
}
@Component({
template: `
<declarer></declarer>
<creator></creator>
`,
standalone: false,
})
class App {
@ViewChild(Declarer) declarer!: Declarer;
@ViewChild(Creator) creator!: Creator;
}
TestBed.configureTestingModule({declarations: [App, MenuTrigger, Menu, Declarer, Creator]});
const injector = Injector.create({providers: [{provide: token, useValue: 'hello'}]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const {declarer, creator} = fixture.componentInstance;
creator.trigger.menu = declarer.template;
creator.trigger.open(injector);
fixture.detectChanges();
expect(declarer.menu.tokenValue).toBe('hello');
expect(declarer.menu.declarerTokenValue).toBe('hello from declarer');
expect(declarer.menu.creatorTokenValue).toBeNull();
});
it('should give precedence to value provided lower in the tree over custom injector', () => {
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(@Inject(token) public tokenValue: string) {}
}
@Directive({
selector: '[provide-token]',
providers: [{provide: token, useValue: 'hello from directive'}],
standalone: false,
})
class ProvideToken {}
@Component({
template: `
<menu-trigger [triggerFor]="menuTemplate"></menu-trigger>
<ng-template #menuTemplate>
<section>
<div provide-token>
<menu></menu>
</div>
</section>
</ng-template>
`,
providers: [{provide: token, useValue: 'hello from parent'}],
standalone: false,
})
class App {
@ViewChild(MenuTrigger) trigger!: MenuTrigger;
@ViewChild(Menu) menu!: Menu;
}
@NgModule({
declarations: [App, MenuTrigger, Menu, ProvideToken],
exports: [App, MenuTrigger, Menu, ProvideToken],
})
class Module {}
TestBed.configureTestingModule({imports: [Module]});
const injector = Injector.create({
providers: [{provide: token, useValue: 'hello from injector'}],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.componentInstance.trigger.open(injector);
fixture.detectChanges();
expect(fixture.componentInstance.menu.tokenValue).toBe('hello from directive');
});
it('should give precedence to value provided in custom injector over one provided higher', () => {
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(@Inject(token) public tokenValue: string) {}
}
@Directive({
selector: '[provide-token]',
providers: [{provide: token, useValue: 'hello from directive'}],
standalone: false,
})
class ProvideToken {}
@Component({
template: `
<menu-trigger [triggerFor]="menuTemplate"></menu-trigger>
<div provide-token>
<ng-template #menuTemplate>
<menu></menu>
</ng-template>
</div>
`,
providers: [{provide: token, useValue: 'hello from parent'}],
standalone: false,
})
class App {
@ViewChild(MenuTrigger) trigger!: MenuTrigger;
@ViewChild(Menu) menu!: Menu;
}
@NgModule({
declarations: [App, MenuTrigger, Menu, ProvideToken],
exports: [App, MenuTrigger, Menu, ProvideToken],
})
class Module {}
TestBed.configureTestingModule({imports: [Module]});
const injector = Injector.create({
providers: [{provide: token, useValue: 'hello from injector'}],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.componentInstance.trigger.open(injector);
fixture.detectChanges();
expect(fixture.componentInstance.menu.tokenValue).toBe('hello from injector');
});
it('should give precedence to value provided lower in the tree over custom injector when crossing view boundaries', () => {
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(@Inject(token) public tokenValue: string) {}
}
@Directive({
selector: '[provide-token]',
providers: [{provide: token, useValue: 'hello from directive'}],
standalone: false,
})
class ProvideToken {}
@Component({
selector: 'wrapper',
template: `<div><menu></menu></div>`,
standalone: false,
})
class Wrapper {
@ViewChild(Menu) menu!: Menu;
}
@Component({
template: `
<menu-trigger [triggerFor]="menuTemplate"></menu-trigger>
<ng-template #menuTemplate>
<section provide-token>
<wrapper></wrapper>
</section>
</ng-template>
`,
providers: [{provide: token, useValue: 'hello from parent'}],
standalone: false,
})
class App {
@ViewChild(MenuTrigger) trigger!: MenuTrigger;
@ViewChild(Wrapper) wrapper!: Wrapper;
}
@NgModule({
declarations: [App, MenuTrigger, Menu, ProvideToken, Wrapper],
exports: [App, MenuTrigger, Menu, ProvideToken, Wrapper],
})
class Module {}
TestBed.configureTestingModule({imports: [Module]});
const injector = Injector.create({
providers: [{provide: token, useValue: 'hello from injector'}],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.componentInstance.trigger.open(injector);
fixture.detectChanges();
expect(fixture.componentInstance.wrapper.menu.tokenValue).toBe('hello from directive');
});
it('should give precedence to value provided in custom injector over one provided higher when crossing view boundaries', () => {
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(@Inject(token) public tokenValue: string) {}
}
@Directive({
selector: '[provide-token]',
providers: [{provide: token, useValue: 'hello from directive'}],
standalone: false,
})
class ProvideToken {}
@Component({
selector: 'wrapper',
template: `<div><menu></menu></div>`,
standalone: false,
})
class Wrapper {
@ViewChild(Menu) menu!: Menu;
}
@Component({
template: `
<menu-trigger [triggerFor]="menuTemplate"></menu-trigger>
<div provide-token>
<ng-template #menuTemplate>
<wrapper></wrapper>
</ng-template>
</div>
`,
providers: [{provide: token, useValue: 'hello from parent'}],
standalone: false,
})
class App {
@ViewChild(MenuTrigger) trigger!: MenuTrigger;
@ViewChild(Wrapper) wrapper!: Wrapper;
}
@NgModule({
declarations: [App, MenuTrigger, Menu, ProvideToken, Wrapper],
exports: [App, MenuTrigger, Menu, ProvideToken, Wrapper],
})
class Module {}
TestBed.configureTestingModule({imports: [Module]});
const injector = Injector.create({
providers: [{provide: token, useValue: 'hello from injector'}],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.componentInstance.trigger.open(injector);
fixture.detectChanges();
expect(fixture.componentInstance.wrapper.menu.tokenValue).toBe('hello from injector');
});
it('sh | {
"end_byte": 205081,
"start_byte": 195918,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/di_spec.ts_205087_207021 | ot resolve value at insertion location', () => {
@Directive({
selector: 'menu',
standalone: false,
})
class Menu {
constructor(@Inject(token) public tokenValue: string) {}
}
@Directive({
selector: '[provide-token]',
providers: [{provide: token, useValue: 'hello from directive'}],
standalone: false,
})
class ProvideToken {}
@Component({
template: `
<div provide-token>
<menu-trigger [triggerFor]="menuTemplate"></menu-trigger>
</div>
<ng-template #menuTemplate>
<menu></menu>
</ng-template>
`,
providers: [{provide: token, useValue: 'hello from parent'}],
standalone: false,
})
class App {
@ViewChild(MenuTrigger) trigger!: MenuTrigger;
@ViewChild(Menu) menu!: Menu;
}
@NgModule({
declarations: [App, MenuTrigger, Menu, ProvideToken],
exports: [App, MenuTrigger, Menu, ProvideToken],
})
class Module {}
TestBed.configureTestingModule({imports: [Module]});
// Provide an empty injector so we hit the new code path.
const injector = Injector.create({providers: []});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
fixture.componentInstance.trigger.open(injector);
fixture.detectChanges();
expect(fixture.componentInstance.menu.tokenValue).toBe('hello from parent');
});
});
it('should prioritize module providers over additional providers', () => {
const token = new InjectionToken('token');
@NgModule({providers: [{provide: token, useValue: 'module'}]})
class ModuleWithProvider {}
const injector = createInjector(ModuleWithProvider, null, [
{provide: token, useValue: 'additional'},
]);
expect(injector.get(token)).toBe('module');
});
});
| {
"end_byte": 207021,
"start_byte": 205087,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/di_spec.ts"
} |
angular/packages/core/test/acceptance/csp_spec.ts_0_4118 | /*!
* @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,
CSP_NONCE,
destroyPlatform,
ElementRef,
inject,
ViewEncapsulation,
} from '@angular/core';
import {bootstrapApplication} from '@angular/platform-browser';
import {withBody} from '@angular/private/testing';
describe('CSP integration', () => {
beforeEach(destroyPlatform);
afterEach(destroyPlatform);
const testStyles = '.a { color: var(--csp-test-var, hotpink); }';
function findTestNonces(rootNode: ParentNode): string[] {
const styles = rootNode.querySelectorAll('style');
const nonces: string[] = [];
for (let i = 0; i < styles.length; i++) {
const style = styles[i];
const nonce = style.getAttribute('nonce');
if (nonce && style.textContent?.includes('--csp-test-var')) {
nonces.push(nonce);
}
}
return nonces;
}
it(
'should use the predefined ngCspNonce when inserting styles with emulated encapsulation',
withBody('<app ngCspNonce="emulated-nonce"></app>', async () => {
@Component({
selector: 'uses-styles',
template: '',
styles: [testStyles],
standalone: true,
encapsulation: ViewEncapsulation.Emulated,
})
class UsesStyles {}
@Component({
selector: 'app',
standalone: true,
template: '<uses-styles></uses-styles>',
imports: [UsesStyles],
})
class App {}
const appRef = await bootstrapApplication(App);
expect(findTestNonces(document)).toEqual(['emulated-nonce']);
appRef.destroy();
}),
);
it(
'should use the predefined ngCspNonce when inserting styles with no encapsulation',
withBody('<app ngCspNonce="disabled-nonce"></app>', async () => {
@Component({
selector: 'uses-styles',
template: '',
styles: [testStyles],
standalone: true,
encapsulation: ViewEncapsulation.None,
})
class UsesStyles {}
@Component({
selector: 'app',
standalone: true,
template: '<uses-styles></uses-styles>',
imports: [UsesStyles],
})
class App {}
const appRef = await bootstrapApplication(App);
expect(findTestNonces(document)).toEqual(['disabled-nonce']);
appRef.destroy();
}),
);
it(
'should use the predefined ngCspNonce when inserting styles with shadow DOM encapsulation',
withBody('<app ngCspNonce="shadow-nonce"></app>', async () => {
if (!document.body.attachShadow) {
return;
}
let usesStylesRootNode!: HTMLElement;
@Component({
selector: 'uses-styles',
template: '',
styles: [testStyles],
standalone: true,
encapsulation: ViewEncapsulation.ShadowDom,
})
class UsesStyles {
constructor() {
usesStylesRootNode = inject(ElementRef).nativeElement;
}
}
@Component({
selector: 'app',
standalone: true,
template: '<uses-styles></uses-styles>',
imports: [UsesStyles],
})
class App {}
const appRef = await bootstrapApplication(App);
expect(findTestNonces(usesStylesRootNode.shadowRoot!)).toEqual(['shadow-nonce']);
appRef.destroy();
}),
);
it(
'should prefer nonce provided through DI over one provided in the DOM',
withBody('<app ngCspNonce="dom-nonce"></app>', async () => {
@Component({selector: 'uses-styles', template: '', styles: [testStyles], standalone: true})
class UsesStyles {}
@Component({
selector: 'app',
standalone: true,
template: '<uses-styles></uses-styles>',
imports: [UsesStyles],
})
class App {}
const appRef = await bootstrapApplication(App, {
providers: [{provide: CSP_NONCE, useValue: 'di-nonce'}],
});
expect(findTestNonces(document)).toEqual(['di-nonce']);
appRef.destroy();
}),
);
});
| {
"end_byte": 4118,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/csp_spec.ts"
} |
angular/packages/core/test/acceptance/copy_definition_feature_spec.ts_0_2742 | /**
* @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,
NgModule,
ɵɵCopyDefinitionFeature as CopyDefinitionFeature,
ɵɵdefineComponent as defineComponent,
ɵɵInheritDefinitionFeature as InheritDefinitionFeature,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
describe('CopyDefinitionFeature', () => {
it('should copy the template function of a component definition from parent to child', () => {
// It would be nice if the base component could be JIT compiled. However, this creates
// a getter for ɵcmp which precludes adding a static definition of that field for the
// child class.
// TODO(alxhub): see if there's a cleaner way to do this.
class BaseComponent {
name!: string;
static ɵcmp = defineComponent({
type: BaseComponent,
selectors: [['some-cmp']],
decls: 0,
vars: 0,
inputs: {name: 'name'},
template: function BaseComponent_Template(rf, ctx) {
ctx.rendered = true;
},
encapsulation: 2,
});
static ɵfac = function BaseComponent_Factory(t: any) {
return new (t || BaseComponent)();
};
rendered = false;
}
class ChildComponent extends BaseComponent {
static override ɵcmp = defineComponent({
type: ChildComponent,
selectors: [['some-cmp']],
standalone: false,
features: [InheritDefinitionFeature, CopyDefinitionFeature],
decls: 0,
vars: 0,
template: function ChildComponent_Template(rf, ctx) {},
encapsulation: 2,
});
static override ɵfac = function ChildComponent_Factory(t: any) {
return new (t || ChildComponent)();
};
}
@NgModule({
declarations: [ChildComponent],
exports: [ChildComponent],
})
class Module {}
@Component({
selector: 'test-cmp',
template: '<some-cmp name="Success!"></some-cmp>',
standalone: false,
})
class TestCmp {}
TestBed.configureTestingModule({
declarations: [TestCmp],
imports: [Module],
});
const fixture = TestBed.createComponent(TestCmp);
// The child component should have matched and been instantiated.
const child = fixture.debugElement.children[0].componentInstance as ChildComponent;
expect(child instanceof ChildComponent).toBe(true);
// And the base class template function should've been called.
expect(child.rendered).toBe(true);
// The input binding should have worked.
expect(child.name).toBe('Success!');
});
});
| {
"end_byte": 2742,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/copy_definition_feature_spec.ts"
} |
angular/packages/core/test/acceptance/authoring/signal_queries_spec.ts_0_9534 | /**
* @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,
contentChild,
contentChildren,
createComponent,
Directive,
ElementRef,
EnvironmentInjector,
QueryList,
viewChild,
ViewChildren,
viewChildren,
} from '@angular/core';
import {SIGNAL} from '@angular/core/primitives/signals';
import {TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
describe('queries as signals', () => {
describe('view', () => {
it('should query for an optional element in a template', () => {
@Component({
standalone: true,
template: `<div #el></div>`,
})
class AppComponent {
divEl = viewChild<ElementRef<HTMLDivElement>>('el');
foundEl = computed(() => this.divEl() != null);
}
const fixture = TestBed.createComponent(AppComponent);
// with signal based queries we _do_ have query results after the creation mode
// execution
// (before the change detection runs) so we can return those early on! In this sense all
// queries behave as "static" (?)
expect(fixture.componentInstance.foundEl()).toBeTrue();
fixture.detectChanges();
expect(fixture.componentInstance.foundEl()).toBeTrue();
});
it('should return undefined if optional query is read in the constructor', () => {
let result: {} | undefined = {};
@Component({
standalone: true,
template: `<div #el></div>`,
})
class AppComponent {
divEl = viewChild<ElementRef<HTMLDivElement>>('el');
constructor() {
result = this.divEl();
}
}
TestBed.createComponent(AppComponent);
expect(result).toBeUndefined();
});
it('should query for a required element in a template', () => {
@Component({
standalone: true,
template: `<div #el></div>`,
})
class AppComponent {
divEl = viewChild.required<ElementRef<HTMLDivElement>>('el');
foundEl = computed(() => this.divEl() != null);
}
const fixture = TestBed.createComponent(AppComponent);
// with signal based queries we _do_ have query results after the creation mode execution
// (before the change detection runs) so we can return those early on! In this sense all
// queries behave as "static" (?)
expect(fixture.componentInstance.foundEl()).toBeTrue();
fixture.detectChanges();
expect(fixture.componentInstance.foundEl()).toBeTrue();
});
it('should throw if required query is read in the constructor', () => {
@Component({
standalone: true,
template: `<div #el></div>`,
})
class AppComponent {
divEl = viewChild.required<ElementRef<HTMLDivElement>>('el');
constructor() {
this.divEl();
}
}
// non-required query results are undefined before we run creation mode on the view queries
expect(() => {
TestBed.createComponent(AppComponent);
}).toThrowError(/NG0951: Child query result is required but no value is available/);
});
it('should query for multiple elements in a template', () => {
@Component({
standalone: true,
template: `
<div #el></div>
@if (show) {
<div #el></div>
}
`,
})
class AppComponent {
show = false;
divEls = viewChildren<ElementRef<HTMLDivElement>>('el');
foundEl = computed(() => this.divEls().length);
}
const fixture = TestBed.createComponent(AppComponent);
// with signal based queries we _do_ have query results after the creation mode execution
// (before the change detection runs) so we can return those early on! In this sense all
// queries behave as "static" (?)
expect(fixture.componentInstance.foundEl()).toBe(1);
fixture.detectChanges();
expect(fixture.componentInstance.foundEl()).toBe(1);
fixture.componentInstance.show = true;
fixture.detectChanges();
expect(fixture.componentInstance.foundEl()).toBe(2);
fixture.componentInstance.show = false;
fixture.detectChanges();
expect(fixture.componentInstance.foundEl()).toBe(1);
});
it('should return an empty array when reading children query in the constructor', () => {
let result: readonly ElementRef[] | undefined;
@Component({
standalone: true,
template: `<div #el></div>`,
})
class AppComponent {
divEls = viewChildren<ElementRef<HTMLDivElement>>('el');
constructor() {
result = this.divEls();
}
}
TestBed.createComponent(AppComponent);
expect(result).toEqual([]);
});
it('should return the same array instance when there were no changes in results', () => {
@Component({
standalone: true,
template: `<div #el></div>`,
})
class AppComponent {
divEls = viewChildren<ElementRef<HTMLDivElement>>('el');
}
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const result1 = fixture.componentInstance.divEls();
expect(result1.length).toBe(1);
// subsequent reads should return the same result instance
const result2 = fixture.componentInstance.divEls();
expect(result2.length).toBe(1);
expect(result2).toBe(result1);
});
it('should not mark signal as dirty when a child query result does not change', () => {
let computeCount = 0;
@Component({
standalone: true,
template: `
<div #el></div>
@if (show) {
<div #el></div>
}
`,
})
class AppComponent {
divEl = viewChild.required<ElementRef<HTMLDivElement>>('el');
isThere = computed(() => ++computeCount);
show = false;
}
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(fixture.componentInstance.isThere()).toBe(1);
const divEl = fixture.componentInstance.divEl();
// subsequent reads should return the same result instance and _not_ trigger downstream
// computed re-evaluation
fixture.componentInstance.show = true;
fixture.detectChanges();
expect(fixture.componentInstance.divEl()).toBe(divEl);
expect(fixture.componentInstance.isThere()).toBe(1);
});
it('should return the same array instance when there were no changes in results after view manipulation', () => {
@Component({
standalone: true,
template: `
<div #el></div>
@if (show) {
<div></div>
}
`,
})
class AppComponent {
divEls = viewChildren<ElementRef<HTMLDivElement>>('el');
show = false;
}
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const result1 = fixture.componentInstance.divEls();
expect(result1.length).toBe(1);
fixture.componentInstance.show = true;
fixture.detectChanges();
// subsequent reads should return the same result instance since the query results didn't
// change
const result2 = fixture.componentInstance.divEls();
expect(result2.length).toBe(1);
expect(result2).toBe(result1);
});
it('should be empty when no query matches exist', () => {
@Component({
standalone: true,
template: ``,
})
class AppComponent {
result = viewChild('unknown');
results = viewChildren('unknown');
}
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(fixture.componentInstance.result()).toBeUndefined();
expect(fixture.componentInstance.results().length).toBe(0);
});
it('should assign a debugName to the underlying signal node when a debugName is provided', () => {
@Component({
standalone: true,
template: `<div #el></div>`,
})
class AppComponent {
viewChildQuery = viewChild<ElementRef<HTMLDivElement>>('el', {debugName: 'viewChildQuery'});
viewChildrenQuery = viewChildren<ElementRef<HTMLDivElement>>('el', {
debugName: 'viewChildrenQuery',
});
}
const fixture = TestBed.createComponent(AppComponent);
const viewChildNode = fixture.componentInstance.viewChildQuery![SIGNAL] as {
debugName: string;
};
expect(viewChildNode.debugName).toBe('viewChildQuery');
const viewChildrenNode = fixture.componentInstance.viewChildrenQuery![SIGNAL] as {
debugName: string;
};
expect(viewChildrenNode.debugName).toBe('viewChildrenQuery');
});
it('should assign a debugName to the underlying signal node when a debugName is provided to a required viewChild query', () => {
@Component({
standalone: true,
template: `<div #el></div>`,
})
class AppComponent {
viewChildQuery = viewChild<ElementRef<HTMLDivElement>>('el', {debugName: 'viewChildQuery'});
}
const fixture = TestBed.createComponent(AppComponent);
const node = fixture.componentInstance.viewChildQuery![SIGNAL] as {debugName: string};
expect(node.debugName).toBe('viewChildQuery');
});
}); | {
"end_byte": 9534,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/authoring/signal_queries_spec.ts"
} |
angular/packages/core/test/acceptance/authoring/signal_queries_spec.ts_9538_19064 | describe('content queries', () => {
it('should run content queries defined on components', () => {
@Component({
selector: 'query-cmp',
standalone: true,
template: `{{noOfEls()}}`,
})
class QueryComponent {
elements = contentChildren('el');
element = contentChild('el');
elementReq = contentChild.required('el');
noOfEls = computed(
() =>
this.elements().length +
(this.element() !== undefined ? 1 : 0) +
(this.elementReq() !== undefined ? 1 : 0),
);
}
@Component({
standalone: true,
imports: [QueryComponent],
template: `
<query-cmp>
<div #el></div >
@if (show) {
<div #el></div>
}
</query-cmp>
`,
})
class AppComponent {
show = false;
}
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('3');
fixture.componentInstance.show = true;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('4');
fixture.componentInstance.show = false;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('3');
});
it('should run content queries defined on directives', () => {
@Directive({
selector: '[query]',
standalone: true,
host: {'[textContent]': `noOfEls()`},
})
class QueryDir {
elements = contentChildren('el');
element = contentChild('el');
elementReq = contentChild.required('el');
noOfEls = computed(
() =>
this.elements().length +
(this.element() !== undefined ? 1 : 0) +
(this.elementReq() !== undefined ? 1 : 0),
);
}
@Component({
standalone: true,
imports: [QueryDir],
template: `
<div query>
<div #el></div>
@if (show) {
<div #el></div>
}
</div>
`,
})
class AppComponent {
show = false;
}
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('3');
fixture.componentInstance.show = true;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('4');
fixture.componentInstance.show = false;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('3');
});
it('should not return partial results during the first-time view rendering', () => {
@Directive({selector: '[marker]', standalone: true})
class MarkerForResults {}
@Directive({
selector: '[declare]',
standalone: true,
})
class DeclareQuery {
results = contentChildren(MarkerForResults);
}
@Directive({selector: '[inspect]', standalone: true})
class InspectsQueryResults {
constructor(declaration: DeclareQuery) {
// we should _not_ get partial query results while the view is still creating
expect(declaration.results().length).toBe(0);
}
}
@Component({
standalone: true,
imports: [MarkerForResults, InspectsQueryResults, DeclareQuery],
template: `
<div declare>
<div marker></div>
<div inspect></div>
<div marker></div>
</div>
`,
})
class AppComponent {}
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const queryDir = fixture.debugElement
.query(By.directive(DeclareQuery))
.injector.get(DeclareQuery);
expect(queryDir.results().length).toBe(2);
});
it('should be empty when no query matches exist', () => {
@Directive({
selector: '[declare]',
standalone: true,
})
class DeclareQuery {
result = contentChild('unknown');
results = contentChildren('unknown');
}
@Component({
standalone: true,
imports: [DeclareQuery],
template: `<div declare></div>`,
})
class AppComponent {}
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const queryDir = fixture.debugElement
.query(By.directive(DeclareQuery))
.injector.get(DeclareQuery);
expect(queryDir.result()).toBeUndefined();
expect(queryDir.results().length).toBe(0);
});
it('should assign a debugName to the underlying signal node when a debugName is provided', () => {
@Component({
selector: 'query-cmp',
standalone: true,
template: ``,
})
class QueryComponent {
contentChildrenQuery = contentChildren('el', {debugName: 'contentChildrenQuery'});
contentChildQuery = contentChild('el', {debugName: 'contentChildQuery'});
contentChildRequiredQuery = contentChild.required('el', {
debugName: 'contentChildRequiredQuery',
});
}
@Component({
standalone: true,
imports: [QueryComponent],
template: `
<query-cmp>
<div #el></div>
<div #el></div>
</query-cmp>
`,
})
class AppComponent {}
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const queryComponent = fixture.debugElement.query(By.directive(QueryComponent))
.componentInstance as QueryComponent;
expect((queryComponent.contentChildrenQuery[SIGNAL] as {debugName: string}).debugName).toBe(
'contentChildrenQuery',
);
expect((queryComponent.contentChildQuery[SIGNAL] as {debugName: string}).debugName).toBe(
'contentChildQuery',
);
expect(
(queryComponent.contentChildRequiredQuery[SIGNAL] as {debugName: string}).debugName,
).toBe('contentChildRequiredQuery');
});
});
describe('reactivity and performance', () => {
it('should not dirty a children query when a list of matches does not change - a view with matches', () => {
let recomputeCount = 0;
@Component({
standalone: true,
template: `
<div #el></div>
@if (show) {
<div #el></div>
}
`,
})
class AppComponent {
divEls = viewChildren<ElementRef<HTMLDivElement>>('el');
foundElCount = computed(() => {
recomputeCount++;
return this.divEls().length;
});
show = false;
}
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(fixture.componentInstance.foundElCount()).toBe(1);
expect(recomputeCount).toBe(1);
// trigger view manipulation that should dirty queries but not change the results
fixture.componentInstance.show = true;
fixture.detectChanges();
fixture.componentInstance.show = false;
fixture.detectChanges();
expect(fixture.componentInstance.foundElCount()).toBe(1);
expect(recomputeCount).toBe(1);
});
it('should not dirty a children query when a list of matches does not change - a view with another container', () => {
let recomputeCount = 0;
@Component({
standalone: true,
template: `
<div #el></div>
@if (show) {
<!-- an empty if to create a container -->
@if (true) {}
}
`,
})
class AppComponent {
divEls = viewChildren<ElementRef<HTMLDivElement>>('el');
foundElCount = computed(() => {
recomputeCount++;
return this.divEls().length;
});
show = false;
}
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(fixture.componentInstance.foundElCount()).toBe(1);
expect(recomputeCount).toBe(1);
// trigger view manipulation that should dirty queries but not change the results
fixture.componentInstance.show = true;
fixture.detectChanges();
fixture.componentInstance.show = false;
fixture.detectChanges();
expect(fixture.componentInstance.foundElCount()).toBe(1);
expect(recomputeCount).toBe(1);
});
});
describe('dynamic component creation', () => {
it('should return empty results for content queries of dynamically created components', () => {
// https://github.com/angular/angular/issues/54450
@Component({
selector: 'query-cmp',
standalone: true,
template: ``,
})
class QueryComponent {
elements = contentChildren('el');
element = contentChild('el');
}
@Component({
standalone: true,
template: ``,
})
class TestComponent {
constructor(private _envInjector: EnvironmentInjector) {}
createDynamic() {
return createComponent(QueryComponent, {environmentInjector: this._envInjector});
}
}
const fixture = TestBed.createComponent(TestComponent);
const cmpRef = fixture.componentInstance.createDynamic();
cmpRef.changeDetectorRef.detectChanges();
expect(cmpRef.instance.elements()).toEqual([]);
expect(cmpRef.instance.element()).toBeUndefined();
});
}); | {
"end_byte": 19064,
"start_byte": 9538,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/authoring/signal_queries_spec.ts"
} |
angular/packages/core/test/acceptance/authoring/signal_queries_spec.ts_19068_21715 | describe('mix of signal and decorator queries', () => {
it('should allow specifying both types of queries in one component', () => {
@Component({
standalone: true,
template: `
<div #el></div>
@if (show) {
<div #el></div>
}
`,
})
class AppComponent {
show = false;
divElsSignal = viewChildren<ElementRef<HTMLDivElement>>('el');
@ViewChildren('el') divElsDecorator!: QueryList<ElementRef<HTMLDivElement>>;
}
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(fixture.componentInstance.divElsSignal().length).toBe(1);
expect(fixture.componentInstance.divElsDecorator.length).toBe(1);
fixture.componentInstance.show = true;
fixture.detectChanges();
expect(fixture.componentInstance.divElsSignal().length).toBe(2);
expect(fixture.componentInstance.divElsDecorator.length).toBe(2);
fixture.componentInstance.show = false;
fixture.detectChanges();
expect(fixture.componentInstance.divElsSignal().length).toBe(1);
expect(fixture.componentInstance.divElsDecorator.length).toBe(1);
});
it('should allow combination via inheritance of both types of queries in one component', () => {
@Component({
standalone: true,
template: `
<div #el></div>
@if (show) {
<div #el></div>
}
`,
})
class BaseComponent {
show = false;
divElsSignal = viewChildren<ElementRef<HTMLDivElement>>('el');
}
@Component({
standalone: true,
template: `
<div #el></div>
@if (show) {
<div #el></div>
}
`,
})
class AppComponent extends BaseComponent {
@ViewChildren('el') divElsDecorator!: QueryList<ElementRef<HTMLDivElement>>;
}
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(fixture.componentInstance.divElsSignal().length).toBe(1);
expect(fixture.componentInstance.divElsDecorator.length).toBe(1);
fixture.componentInstance.show = true;
fixture.detectChanges();
expect(fixture.componentInstance.divElsSignal().length).toBe(2);
expect(fixture.componentInstance.divElsDecorator.length).toBe(2);
fixture.componentInstance.show = false;
fixture.detectChanges();
expect(fixture.componentInstance.divElsSignal().length).toBe(1);
expect(fixture.componentInstance.divElsDecorator.length).toBe(1);
});
});
}); | {
"end_byte": 21715,
"start_byte": 19068,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/authoring/signal_queries_spec.ts"
} |
angular/packages/core/test/acceptance/authoring/signal_inputs_spec.ts_0_8160 | /**
* @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,
Directive,
effect,
EventEmitter,
input,
Output,
ViewChild,
} from '@angular/core';
import {setUseMicrotaskEffectsByDefault} from '@angular/core/src/render3/reactivity/effect';
import {SIGNAL} from '@angular/core/primitives/signals';
import {TestBed} from '@angular/core/testing';
describe('signal inputs', () => {
let prev: boolean;
beforeEach(() => {
prev = setUseMicrotaskEffectsByDefault(false);
});
afterEach(() => setUseMicrotaskEffectsByDefault(prev));
beforeEach(() =>
TestBed.configureTestingModule({
errorOnUnknownProperties: true,
}),
);
it('should be possible to bind to an input', () => {
@Component({
selector: 'input-comp',
standalone: true,
template: 'input:{{input()}}',
})
class InputComp {
input = input<number>();
}
@Component({
standalone: true,
template: `<input-comp [input]="value" />`,
imports: [InputComp],
})
class TestCmp {
value = 1;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('input:1');
fixture.componentInstance.value = 2;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('input:2');
});
it('should be possible to use an input in a computed expression', () => {
@Component({
selector: 'input-comp',
standalone: true,
template: 'changed:{{changed()}}',
})
class InputComp {
input = input<number>();
changed = computed(() => `computed-${this.input()}`);
}
@Component({
standalone: true,
template: `<input-comp [input]="value" />`,
imports: [InputComp],
})
class TestCmp {
value = 1;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('changed:computed-1');
fixture.componentInstance.value = 2;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('changed:computed-2');
});
it('should be possible to use an input in an effect', () => {
let effectLog: unknown[] = [];
@Component({
selector: 'input-comp',
standalone: true,
template: '',
})
class InputComp {
input = input<number>();
constructor() {
effect(() => {
effectLog.push(this.input());
});
}
}
@Component({
standalone: true,
template: `<input-comp [input]="value" />`,
imports: [InputComp],
})
class TestCmp {
value = 1;
}
const fixture = TestBed.createComponent(TestCmp);
expect(effectLog).toEqual([]);
fixture.detectChanges();
expect(effectLog).toEqual([1]);
fixture.componentInstance.value = 2;
fixture.detectChanges();
expect(effectLog).toEqual([1, 2]);
});
it('should support transforms', () => {
@Component({
selector: 'input-comp',
standalone: true,
template: 'input:{{input()}}',
})
class InputComp {
input = input(0, {transform: (v: number) => v + 1000});
}
@Component({
standalone: true,
template: `<input-comp [input]="value" />`,
imports: [InputComp],
})
class TestCmp {
value = 1;
}
const fixture = TestBed.createComponent(TestCmp);
const inputComp = fixture.debugElement.children[0].componentInstance as InputComp;
expect(inputComp.input()).withContext('should not run transform on initial value').toBe(0);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('input:1001');
});
it('should not run transforms lazily', () => {
let transformRunCount = 0;
@Component({
selector: 'input-comp',
standalone: true,
template: '',
})
class InputComp {
input = input(0, {
transform: (v: number) => (transformRunCount++, v + 1000),
});
}
@Component({
standalone: true,
template: `<input-comp [input]="value" />`,
imports: [InputComp],
})
class TestCmp {
value = 1;
}
const fixture = TestBed.createComponent(TestCmp);
expect(transformRunCount).toBe(0);
fixture.detectChanges();
expect(transformRunCount).toBe(1);
});
it('should throw error if a required input is accessed too early', () => {
@Component({
selector: 'input-comp',
standalone: true,
template: 'input:{{input()}}',
})
class InputComp {
input = input.required<string>();
constructor() {
this.input();
}
}
@Component({
standalone: true,
template: `<input-comp [input]="value" />`,
imports: [InputComp],
})
class TestCmp {
value = 1;
}
expect(() => TestBed.createComponent(TestCmp)).toThrowError(
/Input is required but no value is available yet/,
);
});
it('should be possible to bind to an inherited input', () => {
@Directive()
class BaseDir {
input = input<number>();
}
@Component({
selector: 'input-comp',
standalone: true,
template: 'input:{{input()}}',
})
class InputComp extends BaseDir {}
@Component({
standalone: true,
template: `<input-comp [input]="value" />`,
imports: [InputComp],
})
class TestCmp {
value = 1;
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('input:1');
fixture.componentInstance.value = 2;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('input:2');
});
it('should support two-way binding to signal input and @Output decorated member', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = input(0);
@Output() valueChange = new EventEmitter<number>();
}
@Component({
template: '<div [(value)]="value" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
value = 1;
}
const fixture = TestBed.createComponent(App);
const host = fixture.componentInstance;
fixture.detectChanges();
// Initial value.
expect(host.value).toBe(1);
expect(host.dir.value()).toBe(1);
// Changing the value from within the directive.
host.dir.valueChange.emit(2);
fixture.detectChanges();
expect(host.value).toBe(2);
expect(host.dir.value()).toBe(2);
// Changing the value from the outside.
host.value = 3;
fixture.detectChanges();
expect(host.value).toBe(3);
expect(host.dir.value()).toBe(3);
});
it('should assign a debugName to the input signal node when a debugName is provided', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = input(0, {debugName: 'TEST_DEBUG_NAME'});
}
@Component({
template: '<div [value]="1" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
}
const fixture = TestBed.createComponent(App);
const host = fixture.componentInstance;
fixture.detectChanges();
expect(host.dir.value[SIGNAL].debugName).toBe('TEST_DEBUG_NAME');
});
it('should assign a debugName to the input signal node when a debugName is provided to a required input', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = input.required({debugName: 'TEST_DEBUG_NAME'});
}
@Component({
template: '<div [value]="1" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
}
const fixture = TestBed.createComponent(App);
const host = fixture.componentInstance;
fixture.detectChanges();
expect(host.dir.value[SIGNAL].debugName).toBe('TEST_DEBUG_NAME');
});
});
| {
"end_byte": 8160,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/authoring/signal_inputs_spec.ts"
} |
angular/packages/core/test/acceptance/authoring/authoring_test_compiler.ts_0_1510 | /**
* @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 {ImportedSymbolsTracker} from '@angular/compiler-cli/src/ngtsc/imports';
import {TypeScriptReflectionHost} from '@angular/compiler-cli/src/ngtsc/reflection';
import {getInitializerApiJitTransform} from '@angular/compiler-cli/src/ngtsc/transform/jit';
import fs from 'fs';
import path from 'path';
import ts from 'typescript';
main().catch((e) => {
console.error(e);
process.exitCode = 1;
});
async function main() {
const [outputDirExecPath, ...inputFileExecpaths] = process.argv.slice(2);
const program = ts.createProgram(inputFileExecpaths, {
skipLibCheck: true,
module: ts.ModuleKind.ESNext,
target: ts.ScriptTarget.ESNext,
moduleResolution: ts.ModuleResolutionKind.Node10,
});
const host = new TypeScriptReflectionHost(program.getTypeChecker());
const importTracker = new ImportedSymbolsTracker();
for (const inputFileExecpath of inputFileExecpaths) {
const outputFile = ts.transform(
program.getSourceFile(inputFileExecpath)!,
[getInitializerApiJitTransform(host, importTracker, /* isCore */ false)],
program.getCompilerOptions(),
);
await fs.promises.writeFile(
path.join(outputDirExecPath, `transformed_${path.basename(inputFileExecpath)}`),
ts.createPrinter().printFile(outputFile.transformed[0]),
);
}
}
| {
"end_byte": 1510,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/authoring/authoring_test_compiler.ts"
} |
angular/packages/core/test/acceptance/authoring/BUILD.bazel_0_2008 | load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ng_module", "nodejs_binary", "npm_package_bin", "ts_library")
package(default_visibility = ["//visibility:private"])
TEST_FILES = glob(
["*.ts"],
exclude = ["authoring_test_compiler.ts"],
)
TEST_DEPS = [
"//packages/core",
"//packages/core/rxjs-interop",
"//packages/core/testing",
"//packages/platform-browser",
"//packages/core/primitives/signals",
"@npm//rxjs",
]
ts_library(
name = "test_compiler_lib",
testonly = True,
srcs = ["authoring_test_compiler.ts"],
deps = [
"//packages/compiler-cli",
"//packages/compiler-cli/src/ngtsc/imports",
"//packages/compiler-cli/src/ngtsc/partial_evaluator",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/transform/jit",
"@npm//typescript",
],
)
nodejs_binary(
name = "test_compiler",
testonly = True,
data = [":test_compiler_lib"],
entry_point = ":authoring_test_compiler.ts",
)
npm_package_bin(
name = "processed_test_sources",
testonly = True,
outs = ["transformed_%s" % file for file in TEST_FILES],
args = ["$(@D)"] + ["$(execpath %s)" % file for file in TEST_FILES],
data = TEST_FILES,
tool = ":test_compiler",
)
ts_library(
name = "test_jit_lib",
testonly = True,
srcs = ["transformed_%s" % file for file in TEST_FILES],
deps = TEST_DEPS,
)
ng_module(
name = "test_lib",
testonly = True,
srcs = TEST_FILES,
deps = TEST_DEPS,
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node"],
deps = [
":test_lib",
],
)
jasmine_node_test(
name = "test_jit",
bootstrap = ["//tools/testing:node"],
deps = [
":test_jit_lib",
],
)
karma_web_test_suite(
name = "test_web",
deps = [
":test_lib",
],
)
karma_web_test_suite(
name = "test_jit_web",
deps = [
":test_jit_lib",
],
)
| {
"end_byte": 2008,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/authoring/BUILD.bazel"
} |
angular/packages/core/test/acceptance/authoring/model_inputs_spec.ts_0_8197 | /*!
* @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,
EventEmitter,
Input,
model,
OnChanges,
Output,
signal,
SimpleChange,
SimpleChanges,
ViewChild,
} from '@angular/core';
import {SIGNAL} from '@angular/core/primitives/signals';
import {TestBed} from '@angular/core/testing';
describe('model inputs', () => {
it('should support two-way binding to a signal', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = model(0);
}
@Component({
template: '<div [(value)]="value" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
value = signal(1);
}
const fixture = TestBed.createComponent(App);
const host = fixture.componentInstance;
fixture.detectChanges();
// Initial value.
expect(host.value()).toBe(1);
expect(host.dir.value()).toBe(1);
// Changing the value from within the directive.
host.dir.value.set(2);
expect(host.value()).toBe(2);
expect(host.dir.value()).toBe(2);
// Changing the value from the outside.
host.value.set(3);
fixture.detectChanges();
expect(host.value()).toBe(3);
expect(host.dir.value()).toBe(3);
});
it('should support two-way binding to a non-signal value', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = model(0);
}
@Component({
template: '<div [(value)]="value" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
value = 1;
}
const fixture = TestBed.createComponent(App);
const host = fixture.componentInstance;
fixture.detectChanges();
// Initial value.
expect(host.value).toBe(1);
expect(host.dir.value()).toBe(1);
// Changing the value from within the directive.
host.dir.value.set(2);
expect(host.value).toBe(2);
expect(host.dir.value()).toBe(2);
// Changing the value from the outside.
host.value = 3;
fixture.detectChanges();
expect(host.value).toBe(3);
expect(host.dir.value()).toBe(3);
});
it('should support two-way binding a signal to a non-model input/output pair', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
@Input() value = 0;
@Output() valueChange = new EventEmitter<number>();
}
@Component({
template: '<div [(value)]="value" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
value = signal(1);
}
const fixture = TestBed.createComponent(App);
const host = fixture.componentInstance;
fixture.detectChanges();
// Initial value.
expect(host.value()).toBe(1);
expect(host.dir.value).toBe(1);
// Changing the value from within the directive.
host.dir.value = 2;
host.dir.valueChange.emit(2);
fixture.detectChanges();
expect(host.value()).toBe(2);
expect(host.dir.value).toBe(2);
// Changing the value from the outside.
host.value.set(3);
fixture.detectChanges();
expect(host.value()).toBe(3);
expect(host.dir.value).toBe(3);
});
it('should support a one-way property binding to a model', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = model(0);
}
@Component({
template: '<div [value]="value" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
value = 1;
}
const fixture = TestBed.createComponent(App);
const host = fixture.componentInstance;
fixture.detectChanges();
// Initial value.
expect(host.value).toBe(1);
expect(host.dir.value()).toBe(1);
// Changing the value from within the directive.
host.dir.value.set(2);
fixture.detectChanges();
expect(host.value).toBe(1);
expect(host.dir.value()).toBe(2);
// Changing the value from the outside.
host.value = 3;
fixture.detectChanges();
expect(host.value).toBe(3);
expect(host.dir.value()).toBe(3);
});
it('should emit to the change output when the model changes', () => {
const emittedValues: number[] = [];
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = model(0);
}
@Component({
template: '<div (valueChange)="changed($event)" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
changed(value: number) {
emittedValues.push(value);
}
}
const fixture = TestBed.createComponent(App);
const host = fixture.componentInstance;
fixture.detectChanges();
expect(emittedValues).toEqual([]);
host.dir.value.set(1);
fixture.detectChanges();
expect(emittedValues).toEqual([1]);
// Same value should not emit.
host.dir.value.set(1);
fixture.detectChanges();
expect(emittedValues).toEqual([1]);
host.dir.value.update((value) => value * 5);
fixture.detectChanges();
expect(emittedValues).toEqual([1, 5]);
});
it('should not emit to the change event when then property binding changes', () => {
const emittedValues: number[] = [];
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = model(0);
}
@Component({
template: '<div [value]="value()" (valueChange)="changed($event)" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
value = signal(1);
changed(value: number) {
emittedValues.push(value);
}
}
const fixture = TestBed.createComponent(App);
const host = fixture.componentInstance;
fixture.detectChanges();
expect(emittedValues).toEqual([]);
host.value.set(2);
fixture.detectChanges();
expect(emittedValues).toEqual([]);
});
it('should support binding to the model input and output separately', () => {
const emittedValues: number[] = [];
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = model(0);
}
@Component({
template: '<div [value]="value()" (valueChange)="changed($event)" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
value = signal(1);
changed(value: number) {
emittedValues.push(value);
}
}
const fixture = TestBed.createComponent(App);
const host = fixture.componentInstance;
fixture.detectChanges();
expect(host.value()).toBe(1);
expect(host.dir.value()).toBe(1);
expect(emittedValues).toEqual([]);
host.dir.value.set(2);
fixture.detectChanges();
expect(host.value()).toBe(1);
expect(host.dir.value()).toBe(2);
expect(emittedValues).toEqual([2]);
host.value.set(3);
fixture.detectChanges();
expect(host.value()).toBe(3);
expect(host.dir.value()).toBe(3);
expect(emittedValues).toEqual([2]);
});
it('should support two-way binding to a model with an alias', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = model(0, {alias: 'alias'});
}
@Component({
template: '<div [(alias)]="value" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
value = signal(1);
}
const fixture = TestBed.createComponent(App);
const host = fixture.componentInstance;
fixture.detectChanges();
// Initial value.
expect(host.value()).toBe(1);
expect(host.dir.value()).toBe(1);
// Changing the value from within the directive.
host.dir.value.set(2);
fixture.detectChanges();
expect(host.value()).toBe(2);
expect(host.dir.value()).toBe(2);
// Changing the value from the outside.
host.value.set(3);
fixture.detectChanges();
expect(host.value()).toBe(3);
expect(host.dir.value()).toBe(3);
}); | {
"end_byte": 8197,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/authoring/model_inputs_spec.ts"
} |
angular/packages/core/test/acceptance/authoring/model_inputs_spec.ts_8201_16213 | it('should support binding to an aliased model input and output separately', () => {
const emittedValues: number[] = [];
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = model(0, {alias: 'alias'});
}
@Component({
template: '<div [alias]="value()" (aliasChange)="changed($event)" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
value = signal(1);
changed(value: number) {
emittedValues.push(value);
}
}
const fixture = TestBed.createComponent(App);
const host = fixture.componentInstance;
fixture.detectChanges();
expect(host.value()).toBe(1);
expect(host.dir.value()).toBe(1);
expect(emittedValues).toEqual([]);
host.dir.value.set(2);
fixture.detectChanges();
expect(host.value()).toBe(1);
expect(host.dir.value()).toBe(2);
expect(emittedValues).toEqual([2]);
host.value.set(3);
fixture.detectChanges();
expect(host.value()).toBe(3);
expect(host.dir.value()).toBe(3);
expect(emittedValues).toEqual([2]);
});
it('should throw if a required model input is accessed too early', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = model.required<number>();
constructor() {
this.value();
}
}
@Component({
template: '<div [(value)]="value" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
value = 1;
}
expect(() => TestBed.createComponent(App)).toThrowError(
/Model is required but no value is available yet/,
);
});
it('should throw if a required model input is updated too early', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = model.required<number>();
constructor() {
this.value.update((prev) => prev * 2);
}
}
@Component({
template: '<div [(value)]="value" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
value = 1;
}
expect(() => TestBed.createComponent(App)).toThrowError(
/Model is required but no value is available yet/,
);
});
it('should stop emitting to the output on destroy', () => {
let emittedEvents = 0;
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = model(0);
}
@Component({
template: '<div (valueChange)="changed()" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
changed() {
emittedEvents++;
}
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const modelRef = fixture.componentInstance.dir.value;
expect(emittedEvents).toBe(0);
modelRef.set(1);
fixture.detectChanges();
expect(emittedEvents).toBe(1);
fixture.destroy();
expect(() => modelRef.set(2)).toThrowError(/Unexpected emit for destroyed `OutputRef`/);
expect(emittedEvents).toBe(1);
});
it('should support inherited model inputs', () => {
@Directive()
abstract class BaseDir {
value = model(0);
}
@Directive({selector: '[dir]', standalone: true})
class Dir extends BaseDir {}
@Component({
template: '<div [(value)]="value" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
value = signal(1);
}
const fixture = TestBed.createComponent(App);
const host = fixture.componentInstance;
fixture.detectChanges();
// Initial value.
expect(host.value()).toBe(1);
expect(host.dir.value()).toBe(1);
// Changing the value from within the directive.
host.dir.value.set(2);
fixture.detectChanges();
expect(host.value()).toBe(2);
expect(host.dir.value()).toBe(2);
// Changing the value from the outside.
host.value.set(3);
fixture.detectChanges();
expect(host.value()).toBe(3);
expect(host.dir.value()).toBe(3);
});
it('should reflect changes to a two-way-bound signal in the DOM', () => {
@Directive({
selector: '[dir]',
standalone: true,
host: {
'(click)': 'increment()',
},
})
class Dir {
value = model(0);
increment() {
this.value.update((previous) => previous + 1);
}
}
@Component({
template: '<button [(value)]="value" dir></button> Current value: {{value()}}',
standalone: true,
imports: [Dir],
})
class App {
value = signal(1);
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Current value: 1');
fixture.nativeElement.querySelector('button').click();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Current value: 2');
fixture.nativeElement.querySelector('button').click();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Current value: 3');
});
it('should support ngOnChanges for two-way model bindings', () => {
const changes: SimpleChange[] = [];
@Directive({selector: '[dir]', standalone: true})
class Dir implements OnChanges {
value = model(0);
ngOnChanges(allChanges: SimpleChanges): void {
if (allChanges['value']) {
changes.push(allChanges['value']);
}
}
}
@Component({
template: '<div [(value)]="value" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
value = signal(1);
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(changes).toEqual([
jasmine.objectContaining({
previousValue: undefined,
currentValue: 1,
firstChange: true,
}),
]);
fixture.componentInstance.value.set(2);
fixture.detectChanges();
expect(changes).toEqual([
jasmine.objectContaining({
previousValue: undefined,
currentValue: 1,
firstChange: true,
}),
jasmine.objectContaining({
previousValue: 1,
currentValue: 2,
firstChange: false,
}),
]);
});
it('should not throw for mixed model and output subscriptions', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
model = model(0);
@Output() output = new EventEmitter();
model2 = model(0);
@Output() output2 = new EventEmitter();
}
@Component({
template: `
<div dir (model)="noop()" (output)="noop()" (model2)="noop()" (output2)="noop()"></div>
`,
standalone: true,
imports: [Dir],
})
class App {
noop() {}
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(() => fixture.destroy()).not.toThrow();
});
it('should support two-way binding to a signal @for loop variable', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = model(0);
}
@Component({
template: `
@for (value of values; track $index) {
<div [(value)]="value" dir></div>
}
`,
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
values = [signal(1)];
}
const fixture = TestBed.createComponent(App);
const host = fixture.componentInstance;
fixture.detectChanges();
// Initial value.
expect(host.values[0]()).toBe(1);
expect(host.dir.value()).toBe(1);
// Changing the value from within the directive.
host.dir.value.set(2);
expect(host.values[0]()).toBe(2);
expect(host.dir.value()).toBe(2);
// Changing the value from the outside.
host.values[0].set(3);
fixture.detectChanges();
expect(host.values[0]()).toBe(3);
expect(host.dir.value()).toBe(3);
}); | {
"end_byte": 16213,
"start_byte": 8201,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/authoring/model_inputs_spec.ts"
} |
angular/packages/core/test/acceptance/authoring/model_inputs_spec.ts_16217_17523 | it('should assign a debugName to the underlying watcher node when a debugName is provided', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = model(0, {debugName: 'TEST_DEBUG_NAME'});
}
@Component({
template: '<div [(value)]="value" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
value = signal(1);
}
const fixture = TestBed.createComponent(App);
const host = fixture.componentInstance;
fixture.detectChanges();
expect(host.dir.value[SIGNAL].debugName).toBe('TEST_DEBUG_NAME');
});
it('should assign a debugName to the underlying watcher node when a debugName is provided to a required model', () => {
@Directive({selector: '[dir]', standalone: true})
class Dir {
value = model.required({debugName: 'TEST_DEBUG_NAME'});
}
@Component({
template: '<div [(value)]="value" dir></div>',
standalone: true,
imports: [Dir],
})
class App {
@ViewChild(Dir) dir!: Dir;
value = signal(1);
}
const fixture = TestBed.createComponent(App);
const host = fixture.componentInstance;
fixture.detectChanges();
expect(host.dir.value[SIGNAL].debugName).toBe('TEST_DEBUG_NAME');
});
}); | {
"end_byte": 17523,
"start_byte": 16217,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/authoring/model_inputs_spec.ts"
} |
angular/packages/core/test/acceptance/authoring/output_function_spec.ts_0_5045 | /*!
* @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,
effect,
ErrorHandler,
EventEmitter,
output,
signal,
} from '@angular/core';
import {outputFromObservable} from '@angular/core/rxjs-interop';
import {setUseMicrotaskEffectsByDefault} from '@angular/core/src/render3/reactivity/effect';
import {TestBed} from '@angular/core/testing';
import {BehaviorSubject, Observable, share, Subject} from 'rxjs';
describe('output() function', () => {
let prev: boolean;
beforeEach(() => {
prev = setUseMicrotaskEffectsByDefault(false);
});
afterEach(() => setUseMicrotaskEffectsByDefault(prev));
it('should support emitting values', () => {
@Directive({
selector: '[dir]',
standalone: true,
})
class Dir {
onBla = output<number>();
}
@Component({
template: '<div dir (onBla)="values.push($event)"></div>',
standalone: true,
imports: [Dir],
})
class App {
values: number[] = [];
}
const fixture = TestBed.createComponent(App);
const dir = fixture.debugElement.children[0].injector.get(Dir);
fixture.detectChanges();
expect(fixture.componentInstance.values).toEqual([]);
dir.onBla.emit(1);
dir.onBla.emit(2);
expect(fixture.componentInstance.values).toEqual([1, 2]);
});
it('should support emitting void values', () => {
@Directive({
selector: '[dir]',
standalone: true,
})
class Dir {
onBla = output();
}
@Component({
template: '<div dir (onBla)="count = count + 1"></div>',
standalone: true,
imports: [Dir],
})
class App {
count = 0;
}
const fixture = TestBed.createComponent(App);
const dir = fixture.debugElement.children[0].injector.get(Dir);
fixture.detectChanges();
expect(fixture.componentInstance.count).toEqual(0);
dir.onBla.emit();
dir.onBla.emit();
expect(fixture.componentInstance.count).toEqual(2);
});
it('should error when emitting to a destroyed output', () => {
@Directive({
selector: '[dir]',
standalone: true,
})
class Dir {
onBla = output<number>();
}
@Component({
template: `
@if (show) {
<div dir (onBla)="values.push($event)"></div>
}
`,
standalone: true,
imports: [Dir],
})
class App {
show = true;
values: number[] = [];
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const dir = fixture.debugElement.children[0].injector.get(Dir);
expect(fixture.componentInstance.values).toEqual([]);
dir.onBla.emit(1);
dir.onBla.emit(2);
expect(fixture.componentInstance.values).toEqual([1, 2]);
fixture.componentInstance.show = false;
fixture.detectChanges();
expect(() => dir.onBla.emit(3)).toThrowError(/Unexpected emit for destroyed `OutputRef`/);
});
it('should error when subscribing to a destroyed output', () => {
@Directive({
selector: '[dir]',
standalone: true,
})
class Dir {
onBla = output<number>();
}
@Component({
template: `
@if (show) {
<div dir (onBla)="values.push($event)"></div>
}
`,
standalone: true,
imports: [Dir],
})
class App {
show = true;
values: number[] = [];
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const dir = fixture.debugElement.children[0].injector.get(Dir);
expect(fixture.componentInstance.values).toEqual([]);
dir.onBla.emit(1);
dir.onBla.emit(2);
expect(fixture.componentInstance.values).toEqual([1, 2]);
fixture.componentInstance.show = false;
fixture.detectChanges();
expect(() => dir.onBla.subscribe(() => {})).toThrowError(
/Unexpected subscription to destroyed `OutputRef`/,
);
});
it('should run listeners outside of `emit` reactive context', () => {
@Directive({
selector: '[dir]',
standalone: true,
})
class Dir {
onBla = output();
effectCount = 0;
constructor() {
effect(() => {
this.onBla.emit();
this.effectCount++;
});
}
}
@Component({
template: '<div dir (onBla)="fnUsingSomeSignal()"></div>',
standalone: true,
imports: [Dir],
})
class App {
signalUnrelatedToDir = signal(0);
fnUsingSomeSignal() {
// track this signal in this function.
this.signalUnrelatedToDir();
}
}
const fixture = TestBed.createComponent(App);
const dir = fixture.debugElement.children[0].injector.get(Dir);
fixture.detectChanges();
expect(dir.effectCount).toEqual(1);
fixture.componentInstance.signalUnrelatedToDir.update((v) => v + 1);
fixture.detectChanges();
expect(dir.effectCount).toEqual(1);
}); | {
"end_byte": 5045,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/authoring/output_function_spec.ts"
} |
angular/packages/core/test/acceptance/authoring/output_function_spec.ts_5049_9794 | describe('outputFromObservable()', () => {
it('should support using a `Subject` as source', () => {
@Directive({
selector: '[dir]',
standalone: true,
})
class Dir {
onBla$ = new Subject<number>();
onBla = outputFromObservable(this.onBla$);
}
@Component({
template: '<div dir (onBla)="values.push($event)"></div>',
standalone: true,
imports: [Dir],
})
class App {
values: number[] = [];
}
const fixture = TestBed.createComponent(App);
const dir = fixture.debugElement.children[0].injector.get(Dir);
fixture.detectChanges();
expect(fixture.componentInstance.values).toEqual([]);
dir.onBla$.next(1);
dir.onBla$.next(2);
expect(fixture.componentInstance.values).toEqual([1, 2]);
});
it('should support using a `BehaviorSubject` as source', () => {
@Directive({
selector: '[dir]',
standalone: true,
})
class Dir {
onBla$ = new BehaviorSubject<number>(1);
onBla = outputFromObservable(this.onBla$);
}
@Component({
template: '<div dir (onBla)="values.push($event)"></div>',
standalone: true,
imports: [Dir],
})
class App {
values: number[] = [];
}
const fixture = TestBed.createComponent(App);
const dir = fixture.debugElement.children[0].injector.get(Dir);
fixture.detectChanges();
expect(fixture.componentInstance.values).toEqual([1]);
dir.onBla$.next(2);
dir.onBla$.next(3);
expect(fixture.componentInstance.values).toEqual([1, 2, 3]);
});
it('should support using an `EventEmitter` as source', () => {
@Directive({
selector: '[dir]',
standalone: true,
})
class Dir {
onBla$ = new EventEmitter<number>();
onBla = outputFromObservable(this.onBla$);
}
@Component({
template: '<div dir (onBla)="values.push($event)"></div>',
standalone: true,
imports: [Dir],
})
class App {
values: number[] = [];
}
const fixture = TestBed.createComponent(App);
const dir = fixture.debugElement.children[0].injector.get(Dir);
fixture.detectChanges();
expect(fixture.componentInstance.values).toEqual([]);
dir.onBla$.next(1);
dir.onBla$.next(2);
expect(fixture.componentInstance.values).toEqual([1, 2]);
});
it('should support lazily creating an observer upon subscription', () => {
@Directive({
selector: '[dir]',
standalone: true,
})
class Dir {
streamStarted = false;
onBla$ = new Observable((obs) => {
this.streamStarted = true;
obs.next(1);
}).pipe(share());
onBla = outputFromObservable(this.onBla$);
}
@Component({
template: `
<div dir></div>
<div dir (onBla)="true"></div>
`,
standalone: true,
imports: [Dir],
})
class App {}
const fixture = TestBed.createComponent(App);
const dir = fixture.debugElement.children[0].injector.get(Dir);
const dir2 = fixture.debugElement.children[1].injector.get(Dir);
fixture.detectChanges();
expect(dir.streamStarted).toBe(false);
expect(dir2.streamStarted).toBe(true);
});
it('should report subscription listener errors to `ErrorHandler` and continue', () => {
@Directive({
selector: '[dir]',
standalone: true,
})
class Dir {
onBla = output();
}
@Component({
template: `
<div dir (onBla)="true"></div>
`,
standalone: true,
imports: [Dir],
})
class App {}
let handledErrors: unknown[] = [];
TestBed.configureTestingModule({
providers: [
{
provide: ErrorHandler,
useClass: class Handler extends ErrorHandler {
override handleError(error: unknown): void {
handledErrors.push(error);
}
},
},
],
});
const fixture = TestBed.createComponent(App);
const dir = fixture.debugElement.children[0].injector.get(Dir);
fixture.detectChanges();
let triggered = 0;
dir.onBla.subscribe(() => {
throw new Error('first programmatic listener failure');
});
dir.onBla.subscribe(() => {
triggered++;
});
dir.onBla.emit();
expect(handledErrors.length).toBe(1);
expect((handledErrors[0] as Error).message).toBe('first programmatic listener failure');
expect(triggered).toBe(1);
});
});
}); | {
"end_byte": 9794,
"start_byte": 5049,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/acceptance/authoring/output_function_spec.ts"
} |
angular/packages/core/test/render3/integration_spec.ts_0_643 | /**
* @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, HostBinding} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {getLContext, readPatchedData} from '../../src/render3/context_discovery';
import {CONTEXT, HEADER_OFFSET} from '../../src/render3/interfaces/view';
import {Sanitizer} from '../../src/sanitization/sanitizer';
import {SecurityContext} from '../../src/sanitization/security'; | {
"end_byte": 643,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/integration_spec.ts"
} |
angular/packages/core/test/render3/integration_spec.ts_645_9661 | describe('element discovery', () => {
it('should only monkey-patch immediate child nodes in a component', () => {
@Component({
standalone: true,
template: '<div><p></p></div>',
})
class StructuredComp {}
const fixture = TestBed.createComponent(StructuredComp);
fixture.detectChanges();
const host = fixture.nativeElement;
const parent = host.querySelector('div') as any;
const child = host.querySelector('p') as any;
expect(readPatchedData(parent)).toBeTruthy();
expect(readPatchedData(child)).toBeFalsy();
});
it('should only monkey-patch immediate child nodes in a sub component', () => {
@Component({
selector: 'child-comp',
standalone: true,
template: `
<div></div>
<div></div>
<div></div>
`,
})
class ChildComp {}
@Component({
selector: 'parent-comp',
standalone: true,
imports: [ChildComp],
template: `
<section>
<child-comp></child-comp>
</section>
`,
})
class ParentComp {}
const fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
const host = fixture.nativeElement;
const child = host.querySelector('child-comp') as any;
expect(readPatchedData(child)).toBeTruthy();
const [kid1, kid2, kid3] = Array.from(host.querySelectorAll('child-comp > *'));
expect(readPatchedData(kid1)).toBeTruthy();
expect(readPatchedData(kid2)).toBeTruthy();
expect(readPatchedData(kid3)).toBeTruthy();
});
it('should only monkey-patch immediate child nodes in an embedded template container', () => {
@Component({
selector: 'structured-comp',
imports: [CommonModule],
standalone: true,
template: `
<section>
<ng-container *ngIf="true">
<div><p></p></div>
<div></div>
</ng-container>
</section>
`,
})
class StructuredComp {}
const fixture = TestBed.createComponent(StructuredComp);
fixture.detectChanges();
const host = fixture.nativeElement;
const [section, div1, p, div2] = Array.from<HTMLElement>(
host.querySelectorAll('section, div, p'),
);
expect(section.nodeName.toLowerCase()).toBe('section');
expect(readPatchedData(section)).toBeTruthy();
expect(div1.nodeName.toLowerCase()).toBe('div');
expect(readPatchedData(div1)).toBeTruthy();
expect(p.nodeName.toLowerCase()).toBe('p');
expect(readPatchedData(p)).toBeFalsy();
expect(div2.nodeName.toLowerCase()).toBe('div');
expect(readPatchedData(div2)).toBeTruthy();
});
it('should return a context object from a given dom node', () => {
@Component({
selector: 'structured-comp',
standalone: true,
template: `
<section></section>
<div></div>
`,
})
class StructuredComp {}
const fixture = TestBed.createComponent(StructuredComp);
fixture.detectChanges();
const section = fixture.nativeElement.querySelector('section')!;
const sectionContext = getLContext(section)!;
expect(sectionContext.nodeIndex).toEqual(HEADER_OFFSET);
expect(sectionContext.lView!.length).toBeGreaterThan(HEADER_OFFSET);
expect(sectionContext.native).toBe(section);
const div = fixture.nativeElement.querySelector('div')!;
const divContext = getLContext(div)!;
expect(divContext.nodeIndex).toEqual(HEADER_OFFSET + 1);
expect(divContext.lView!.length).toBeGreaterThan(HEADER_OFFSET);
expect(divContext.native).toBe(div);
expect(divContext.lView).toBe(sectionContext.lView);
});
it('should cache the element context on a element was preemptively monkey-patched', () => {
@Component({
selector: 'structured-comp',
standalone: true,
template: `
<section></section>
`,
})
class StructuredComp {}
const fixture = TestBed.createComponent(StructuredComp);
fixture.detectChanges();
const section = fixture.nativeElement.querySelector('section')! as any;
const result1 = readPatchedData(section);
expect(Array.isArray(result1)).toBeTruthy();
const context = getLContext(section)!;
const result2 = readPatchedData(section) as any;
expect(Array.isArray(result2)).toBeFalsy();
expect(result2).toBe(context);
expect(result2.lView).toBe(result1);
});
it("should cache the element context on an intermediate element that isn't preemptively monkey-patched", () => {
@Component({
selector: 'structured-comp',
standalone: true,
template: `
<section>
<p></p>
</section>
`,
})
class StructuredComp {}
const fixture = TestBed.createComponent(StructuredComp);
fixture.detectChanges();
const section = fixture.nativeElement.querySelector('section')! as any;
expect(readPatchedData(section)).toBeTruthy();
const p = fixture.nativeElement.querySelector('p')! as any;
expect(readPatchedData(p)).toBeFalsy();
const pContext = getLContext(p)!;
expect(pContext.native).toBe(p);
expect(readPatchedData(p)).toBe(pContext);
});
it('should be able to pull in element context data even if the element is decorated using styling', () => {
@Component({
selector: 'structured-comp',
standalone: true,
template: `
<section></section>
`,
})
class StructuredComp {}
const fixture = TestBed.createComponent(StructuredComp);
fixture.detectChanges();
const section = fixture.nativeElement.querySelector('section')! as any;
const result1 = readPatchedData(section) as any;
expect(Array.isArray(result1)).toBeTruthy();
const elementResult = result1[HEADER_OFFSET]; // first element
expect(elementResult).toBe(section);
const context = getLContext(section)!;
const result2 = readPatchedData(section);
expect(Array.isArray(result2)).toBeFalsy();
expect(context.native).toBe(section);
});
it('should monkey-patch immediate child nodes in a content-projected region with a reference to the parent component', () => {
/*
<!-- DOM view -->
<section>
<projection-comp>
welcome
<header>
<h1>
<p>this content is projected</p>
this content is projected also
</h1>
</header>
</projection-comp>
</section>
*/
@Component({
selector: 'projector-comp',
standalone: true,
template: `
welcome
<header>
<h1>
<ng-content></ng-content>
</h1>
</header>
`,
})
class ProjectorComp {}
@Component({
selector: 'parent-comp',
standalone: true,
imports: [ProjectorComp],
template: `
<section>
<projector-comp>
<p>this content is projected</p>
this content is projected also
</projector-comp>
</section>
`,
})
class ParentComp {}
const fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
const host = fixture.nativeElement;
const textNode = host.firstChild as any;
const section = host.querySelector('section')! as any;
const projectorComp = host.querySelector('projector-comp')! as any;
const header = host.querySelector('header')! as any;
const h1 = host.querySelector('h1')! as any;
const p = host.querySelector('p')! as any;
const pText = p.firstChild as any;
const projectedTextNode = p.nextSibling;
expect(projectorComp.children).toContain(header);
expect(h1.children).toContain(p);
expect(readPatchedData(textNode)).toBeTruthy();
expect(readPatchedData(section)).toBeTruthy();
expect(readPatchedData(projectorComp)).toBeTruthy();
expect(readPatchedData(header)).toBeTruthy();
expect(readPatchedData(h1)).toBeFalsy();
expect(readPatchedData(p)).toBeTruthy();
expect(readPatchedData(pText)).toBeFalsy();
expect(readPatchedData(projectedTextNode)).toBeTruthy();
const parentContext = getLContext(section)!;
const shadowContext = getLContext(header)!;
const projectedContext = getLContext(p)!;
const parentComponentData = parentContext.lView;
const shadowComponentData = shadowContext.lView;
const projectedComponentData = projectedContext.lView;
expect(projectedComponentData).toBe(parentComponentData);
expect(shadowComponentData).not.toBe(parentComponentData);
});
it("should return `null` when an element context is retrieved that isn't situated in Angular", () => {
const elm1 = document.createElement('div');
const context1 = getLContext(elm1);
expect(context1).toBeFalsy();
const elm2 = document.createElement('div');
document.body.appendChild(elm2);
const context2 = getLContext(elm2);
expect(context2).toBeFalsy();
}); | {
"end_byte": 9661,
"start_byte": 645,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/integration_spec.ts"
} |
angular/packages/core/test/render3/integration_spec.ts_9665_17159 | it('should return `null` when an element context is retrieved that is a DOM node that was not created by Angular', () => {
@Component({
selector: 'structured-comp',
standalone: true,
template: `
<section></section>
`,
})
class StructuredComp {}
const fixture = TestBed.createComponent(StructuredComp);
fixture.detectChanges();
const section = fixture.nativeElement.querySelector('section')! as any;
const manuallyCreatedElement = document.createElement('div');
section.appendChild(manuallyCreatedElement);
const context = getLContext(manuallyCreatedElement);
expect(context).toBeFalsy();
});
it('should by default monkey-patch the bootstrap component with context details', () => {
@Component({
selector: 'structured-comp',
standalone: true,
template: ``,
})
class StructuredComp {}
const fixture = TestBed.createComponent(StructuredComp);
fixture.detectChanges();
const hostElm = fixture.nativeElement;
const component = fixture.componentInstance;
const componentLView = readPatchedData(component);
expect(Array.isArray(componentLView)).toBeTruthy();
const hostLView = readPatchedData(hostElm) as any;
expect(hostLView).toBe(componentLView);
const context1 = getLContext(hostElm)!;
expect(context1.lView).toBe(hostLView);
expect(context1.native).toEqual(hostElm);
const context2 = getLContext(component)!;
expect(context2).toBe(context1);
expect(context2.lView).toBe(hostLView);
expect(context2.native).toEqual(hostElm);
});
it('should by default monkey-patch the directives with LView so that they can be examined', () => {
let myDir1Instance: MyDir1 | null = null;
let myDir2Instance: MyDir2 | null = null;
let myDir3Instance: MyDir2 | null = null;
@Directive({
selector: '[my-dir-1]',
standalone: true,
})
class MyDir1 {
constructor() {
myDir1Instance = this;
}
}
@Directive({
selector: '[my-dir-2]',
standalone: true,
})
class MyDir2 {
constructor() {
myDir2Instance = this;
}
}
@Directive({
selector: '[my-dir-3]',
standalone: true,
})
class MyDir3 {
constructor() {
myDir3Instance = this;
}
}
@Component({
selector: 'structured-comp',
standalone: true,
imports: [MyDir1, MyDir2, MyDir3],
template: `
<div my-dir-1 my-dir-2></div>
<div my-dir-3></div>
`,
})
class StructuredComp {}
const fixture = TestBed.createComponent(StructuredComp);
fixture.detectChanges();
const hostElm = fixture.nativeElement;
const div1 = hostElm.querySelector('div:first-child')! as any;
const div2 = hostElm.querySelector('div:last-child')! as any;
const context = getLContext(hostElm)!;
const componentView = context.lView![context.nodeIndex];
expect(componentView).toContain(myDir1Instance);
expect(componentView).toContain(myDir2Instance);
expect(componentView).toContain(myDir3Instance);
expect(Array.isArray(readPatchedData(myDir1Instance))).toBeTruthy();
expect(Array.isArray(readPatchedData(myDir2Instance))).toBeTruthy();
expect(Array.isArray(readPatchedData(myDir3Instance))).toBeTruthy();
const d1Context = getLContext(myDir1Instance)!;
const d2Context = getLContext(myDir2Instance)!;
const d3Context = getLContext(myDir3Instance)!;
expect(d1Context.lView).toEqual(componentView);
expect(d2Context.lView).toEqual(componentView);
expect(d3Context.lView).toEqual(componentView);
expect(readPatchedData(myDir1Instance)).toBe(d1Context);
expect(readPatchedData(myDir2Instance)).toBe(d2Context);
expect(readPatchedData(myDir3Instance)).toBe(d3Context);
expect(d1Context.nodeIndex).toEqual(HEADER_OFFSET);
expect(d1Context.native).toBe(div1);
expect(d1Context.directives as any[]).toEqual([myDir1Instance, myDir2Instance]);
expect(d2Context.nodeIndex).toEqual(HEADER_OFFSET);
expect(d2Context.native).toBe(div1);
expect(d2Context.directives as any[]).toEqual([myDir1Instance, myDir2Instance]);
expect(d3Context.nodeIndex).toEqual(HEADER_OFFSET + 1);
expect(d3Context.native).toBe(div2);
expect(d3Context.directives as any[]).toEqual([myDir3Instance]);
});
it('should monkey-patch the exact same context instance of the DOM node, component and any directives on the same element', () => {
let myDir1Instance: MyDir1 | null = null;
let myDir2Instance: MyDir2 | null = null;
let childComponentInstance: ChildComp | null = null;
@Directive({
selector: '[my-dir-1]',
standalone: true,
})
class MyDir1 {
constructor() {
myDir1Instance = this;
}
}
@Directive({
selector: '[my-dir-2]',
standalone: true,
})
class MyDir2 {
constructor() {
myDir2Instance = this;
}
}
@Component({
selector: 'child-comp',
standalone: true,
template: `
<div></div>
`,
})
class ChildComp {
constructor() {
childComponentInstance = this;
}
}
@Component({
selector: 'parent-comp',
standalone: true,
imports: [ChildComp, MyDir1, MyDir2],
template: `
<child-comp my-dir-1 my-dir-2></child-comp>
`,
})
class ParentComp {}
const fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
const childCompHostElm = fixture.nativeElement.querySelector('child-comp')! as any;
const lView = readPatchedData(childCompHostElm);
expect(Array.isArray(lView)).toBeTruthy();
expect(readPatchedData(myDir1Instance)).toBe(lView);
expect(readPatchedData(myDir2Instance)).toBe(lView);
expect(readPatchedData(childComponentInstance)).toBe(lView);
const childNodeContext = getLContext(childCompHostElm)!;
expect(childNodeContext.component).toBeFalsy();
expect(childNodeContext.directives).toBeFalsy();
assertMonkeyPatchValueIsLView(myDir1Instance);
assertMonkeyPatchValueIsLView(myDir2Instance);
assertMonkeyPatchValueIsLView(childComponentInstance);
expect(getLContext(myDir1Instance)).toBe(childNodeContext);
expect(childNodeContext.component).toBeFalsy();
expect(childNodeContext.directives!.length).toEqual(2);
assertMonkeyPatchValueIsLView(myDir1Instance, false);
assertMonkeyPatchValueIsLView(myDir2Instance, false);
assertMonkeyPatchValueIsLView(childComponentInstance);
expect(getLContext(myDir2Instance)).toBe(childNodeContext);
expect(childNodeContext.component).toBeFalsy();
expect(childNodeContext.directives!.length).toEqual(2);
assertMonkeyPatchValueIsLView(myDir1Instance, false);
assertMonkeyPatchValueIsLView(myDir2Instance, false);
assertMonkeyPatchValueIsLView(childComponentInstance);
expect(getLContext(childComponentInstance)).toBe(childNodeContext);
expect(childNodeContext.component).toBeTruthy();
expect(childNodeContext.directives!.length).toEqual(2);
assertMonkeyPatchValueIsLView(myDir1Instance, false);
assertMonkeyPatchValueIsLView(myDir2Instance, false);
assertMonkeyPatchValueIsLView(childComponentInstance, false);
function assertMonkeyPatchValueIsLView(value: any, yesOrNo = true) {
expect(Array.isArray(readPatchedData(value))).toBe(yesOrNo);
}
}); | {
"end_byte": 17159,
"start_byte": 9665,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/integration_spec.ts"
} |
angular/packages/core/test/render3/integration_spec.ts_17163_21723 | it('should monkey-patch sub components with the view data and then replace them with the context result once a lookup occurs', () => {
@Component({
selector: 'child-comp',
standalone: true,
template: `
<div></div>
<div></div>
<div></div>
`,
})
class ChildComp {}
@Component({
selector: 'parent-comp',
standalone: true,
imports: [ChildComp],
template: `
<section>
<child-comp></child-comp>
</section>
`,
})
class ParentComp {}
const fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
const host = fixture.nativeElement;
const child = host.querySelector('child-comp') as any;
expect(readPatchedData(child)).toBeTruthy();
const context = getLContext(child)!;
expect(readPatchedData(child)).toBeTruthy();
const componentData = context.lView![context.nodeIndex];
const component = componentData[CONTEXT];
expect(component instanceof ChildComp).toBeTruthy();
expect(readPatchedData(component)).toBe(context.lView);
const componentContext = getLContext(component)!;
expect(readPatchedData(component)).toBe(componentContext);
expect(componentContext.nodeIndex).toEqual(context.nodeIndex);
expect(componentContext.native).toEqual(context.native);
expect(componentContext.lView).toEqual(context.lView);
});
});
describe('sanitization', () => {
it('should sanitize data using the provided sanitization interface', () => {
@Component({
selector: 'sanitize-this',
standalone: true,
template: `
<a [href]="href"></a>
`,
})
class SanitizationComp {
href = '';
updateLink(href: any) {
this.href = href;
}
}
const sanitizer = new LocalSanitizer((value) => {
return 'http://bar';
});
TestBed.configureTestingModule({
providers: [
{
provide: Sanitizer,
useValue: sanitizer,
},
],
});
const fixture = TestBed.createComponent(SanitizationComp);
fixture.componentInstance.updateLink('http://foo');
fixture.detectChanges();
const anchor = fixture.nativeElement.querySelector('a')!;
expect(anchor.getAttribute('href')).toEqual('http://bar');
fixture.componentInstance.updateLink(sanitizer.bypassSecurityTrustUrl('http://foo'));
fixture.detectChanges();
expect(anchor.getAttribute('href')).toEqual('http://foo');
});
it('should sanitize HostBindings data using provided sanitization interface', () => {
let hostBindingDir: UnsafeUrlHostBindingDir;
@Directive({
selector: '[unsafeUrlHostBindingDir]',
standalone: true,
})
class UnsafeUrlHostBindingDir {
@HostBinding() cite: any = 'http://cite-dir-value';
constructor() {
hostBindingDir = this;
}
}
@Component({
selector: 'sanitize-this',
standalone: true,
imports: [UnsafeUrlHostBindingDir],
template: `
<blockquote unsafeUrlHostBindingDir></blockquote>
`,
})
class SimpleComp {}
const sanitizer = new LocalSanitizer((value) => 'http://bar');
TestBed.configureTestingModule({
providers: [
{
provide: Sanitizer,
useValue: sanitizer,
},
],
});
const fixture = TestBed.createComponent(SimpleComp);
hostBindingDir!.cite = 'http://foo';
fixture.detectChanges();
const anchor = fixture.nativeElement.querySelector('blockquote')!;
expect(anchor.getAttribute('cite')).toEqual('http://bar');
hostBindingDir!.cite = sanitizer.bypassSecurityTrustUrl('http://foo');
fixture.detectChanges();
expect(anchor.getAttribute('cite')).toEqual('http://foo');
});
});
class LocalSanitizedValue {
constructor(public value: any) {}
toString() {
return this.value;
}
}
class LocalSanitizer implements Sanitizer {
constructor(private _interceptor: (value: string | null | any) => string) {}
sanitize(context: SecurityContext, value: LocalSanitizedValue | string | null): string | null {
if (value instanceof LocalSanitizedValue) {
return value.toString();
}
return this._interceptor(value);
}
bypassSecurityTrustHtml(value: string) {}
bypassSecurityTrustStyle(value: string) {}
bypassSecurityTrustScript(value: string) {}
bypassSecurityTrustResourceUrl(value: string) {}
bypassSecurityTrustUrl(value: string) {
return new LocalSanitizedValue(value);
}
} | {
"end_byte": 21723,
"start_byte": 17163,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/integration_spec.ts"
} |
angular/packages/core/test/render3/metadata_spec.ts_0_2234 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Type} from '../../src/interface/type';
import {setClassMetadata} from '../../src/render3/metadata';
interface Decorator {
type: any;
args?: any[];
}
interface HasMetadata extends Type<any> {
decorators?: Decorator[];
ctorParameters: () => CtorParameter[];
propDecorators: {[field: string]: Decorator[]};
}
interface CtorParameter {
type: any;
decorators?: Decorator[];
}
function metadataOf(value: Type<any>): HasMetadata {
return value as HasMetadata;
}
describe('render3 setClassMetadata()', () => {
it('should set decorator metadata on a type', () => {
const Foo = metadataOf(class Foo {});
setClassMetadata(Foo, [{type: 'test', args: ['arg']}], null, null);
expect(Foo.decorators).toEqual([{type: 'test', args: ['arg']}]);
});
it('should merge decorator metadata on a type', () => {
const Foo = metadataOf(class Foo {});
Foo.decorators = [{type: 'first'}];
setClassMetadata(Foo, [{type: 'test', args: ['arg']}], null, null);
expect(Foo.decorators).toEqual([{type: 'first'}, {type: 'test', args: ['arg']}]);
});
it('should set ctor parameter metadata on a type', () => {
const Foo = metadataOf(class Foo {});
Foo.ctorParameters = () => [{type: 'initial'}];
setClassMetadata(Foo, null, () => [{type: 'test'}], null);
expect(Foo.ctorParameters()).toEqual([{type: 'test'}]);
});
it('should set parameter decorator metadata on a type', () => {
const Foo = metadataOf(class Foo {});
setClassMetadata(Foo, null, null, {field: [{type: 'test', args: ['arg']}]});
expect(Foo.propDecorators).toEqual({field: [{type: 'test', args: ['arg']}]});
});
it('should merge parameter decorator metadata on a type', () => {
const Foo = metadataOf(class Foo {});
Foo.propDecorators = {initial: [{type: 'first'}]};
setClassMetadata(Foo, null, null, {field: [{type: 'test', args: ['arg']}]});
expect(Foo.propDecorators).toEqual({
field: [{type: 'test', args: ['arg']}],
initial: [{type: 'first'}],
});
});
});
| {
"end_byte": 2234,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/metadata_spec.ts"
} |
angular/packages/core/test/render3/jit_environment_spec.ts_0_2908 | /**
* @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 {ExternalReference} from '@angular/compiler';
import {Identifiers} from '@angular/compiler/src/render3/r3_identifiers';
import {angularCoreEnv} from '../../src/render3/jit/environment';
const INTERFACE_EXCEPTIONS = new Set<string>([
'ɵɵComponentDeclaration',
'ɵɵDirectiveDeclaration',
'ɵɵInjectableDeclaration',
'ɵɵInjectorDeclaration',
'ɵɵInjectorDef',
'ɵɵNgModuleDeclaration',
'ɵɵPipeDeclaration',
'ɵɵFactoryDeclaration',
'ModuleWithProviders',
]);
/**
* The following symbols are only referenced from AOT compilation outputs so are allowed to be
* omitted from the JIT environment.
*/
const AOT_ONLY = new Set<string>([
'ɵsetClassMetadata',
'ɵsetClassMetadataAsync',
// used in type-checking.
'ɵINPUT_SIGNAL_BRAND_WRITE_TYPE',
'ɵUnwrapDirectiveSignalInputs',
'ɵunwrapWritableSignal',
]);
/**
* The following symbols are only referenced from partial declaration compilation outputs, which
* will never be emitted by the JIT compiler so are allowed to be omitted from the JIT environment.
*/
const PARTIAL_ONLY = new Set<string>([
'ɵɵngDeclareDirective',
'ɵɵngDeclareClassMetadata',
'ɵɵngDeclareClassMetadataAsync',
'ɵɵngDeclareComponent',
'ɵɵngDeclareFactory',
'ɵɵngDeclareInjectable',
'ɵɵngDeclareInjector',
'ɵɵngDeclareNgModule',
'ɵɵngDeclarePipe',
'ɵɵFactoryTarget',
'ChangeDetectionStrategy',
'ViewEncapsulation',
]);
describe('r3 jit environment', () => {
// This test keeps render3/jit/environment and r3_identifiers in the compiler in sync, ensuring
// that if the compiler writes a reference to a render3 symbol, it will be resolvable at runtime
// in JIT mode.
it('should support all r3 symbols', () => {
Object
// Map over the static properties of Identifiers.
.values(Identifiers)
// A few such properties are string constants. Ignore them, and focus on ExternalReferences.
.filter(isExternalReference)
// Some references are to interface types. Only take properties which have runtime values.
.filter(
(sym) =>
!INTERFACE_EXCEPTIONS.has(sym.name) &&
!AOT_ONLY.has(sym.name) &&
!PARTIAL_ONLY.has(sym.name),
)
.forEach((sym) => {
// Assert that angularCoreEnv has a reference to the runtime symbol.
expect(angularCoreEnv.hasOwnProperty(sym.name)).toBe(
true,
`Missing symbol ${sym.name} in render3/jit/environment`,
);
});
});
});
function isExternalReference(
sym: ExternalReference | string,
): sym is ExternalReference & {name: string} {
return typeof sym === 'object' && sym.name !== null && sym.moduleName !== null;
}
| {
"end_byte": 2908,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/jit_environment_spec.ts"
} |
angular/packages/core/test/render3/is_shape_of.ts_0_4883 | /**
* @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 {TI18n, TIcu} from '@angular/core/src/render3/interfaces/i18n';
import {TNode} from '@angular/core/src/render3/interfaces/node';
import {TView} from '@angular/core/src/render3/interfaces/view';
/**
* A type used to create a runtime representation of a shape of object which matches the declared
* interface at compile time.
*
* The purpose of this type is to ensure that the object must match all of the properties of a type.
* This is later used by `isShapeOf` method to ensure that a particular object has a particular
* shape.
*
* ```
* interface MyShape {
* foo: string,
* bar: number
* }
*
* const myShapeObj: {foo: '', bar: 0};
* const ExpectedPropertiesOfShape = {foo: true, bar: true};
*
* isShapeOf(myShapeObj, ExpectedPropertiesOfShape);
* ```
*
* The above code would verify that `myShapeObj` has `foo` and `bar` properties. However if later
* `MyShape` is refactored to change a set of properties we would like to have a compile time error
* that the `ExpectedPropertiesOfShape` also needs to be changed.
*
* ```
* const ExpectedPropertiesOfShape = <ShapeOf<MyShape>>{foo: true, bar: true};
* ```
* The above code will force through compile time checks that the `ExpectedPropertiesOfShape` match
* that of `MyShape`.
*
* See: `isShapeOf`
*
*/
export type ShapeOf<T> = {
[P in keyof T]: true;
};
/**
* Determines if a particular object is of a given shape (duck-type version of `instanceof`.)
*
* ```
* isShapeOf(someObj, {foo: true, bar: true});
* ```
*
* The above code will be true if the `someObj` has both `foo` and `bar` property
*
* @param obj Object to test for.
* @param shapeOf Desired shape.
*/
export function isShapeOf<T>(obj: any, shapeOf: ShapeOf<T>): obj is T {
if (typeof obj === 'object' && obj) {
return Object.keys(shapeOf).every((key) => obj.hasOwnProperty(key));
}
return false;
}
/**
* Determines if `obj` matches the shape `TI18n`.
* @param obj
*/
export function isTI18n(obj: any): obj is TI18n {
return isShapeOf<TI18n>(obj, ShapeOfTI18n);
}
const ShapeOfTI18n: ShapeOf<TI18n> = {
create: true,
update: true,
ast: true,
parentTNodeIndex: true,
};
/**
* Determines if `obj` matches the shape `TIcu`.
* @param obj
*/
export function isTIcu(obj: any): obj is TIcu {
return isShapeOf<TIcu>(obj, ShapeOfTIcu);
}
const ShapeOfTIcu: ShapeOf<TIcu> = {
type: true,
anchorIdx: true,
currentCaseLViewIndex: true,
cases: true,
create: true,
remove: true,
update: true,
};
/**
* Determines if `obj` matches the shape `TView`.
* @param obj
*/
export function isTView(obj: any): obj is TView {
return isShapeOf<TView>(obj, ShapeOfTView);
}
const ShapeOfTView: ShapeOf<TView> = {
type: true,
blueprint: true,
template: true,
viewQuery: true,
declTNode: true,
firstCreatePass: true,
firstUpdatePass: true,
data: true,
bindingStartIndex: true,
expandoStartIndex: true,
staticViewQueries: true,
staticContentQueries: true,
firstChild: true,
hostBindingOpCodes: true,
directiveRegistry: true,
pipeRegistry: true,
preOrderHooks: true,
preOrderCheckHooks: true,
contentHooks: true,
contentCheckHooks: true,
viewHooks: true,
viewCheckHooks: true,
destroyHooks: true,
cleanup: true,
components: true,
queries: true,
contentQueries: true,
schemas: true,
consts: true,
incompleteFirstPass: true,
ssrId: true,
};
/**
* Determines if `obj` matches the shape `TI18n`.
* @param obj
*/
export function isTNode(obj: any): obj is TNode {
return isShapeOf<TNode>(obj, ShapeOfTNode);
}
const ShapeOfTNode: ShapeOf<TNode> = {
type: true,
index: true,
insertBeforeIndex: true,
injectorIndex: true,
directiveStart: true,
directiveEnd: true,
directiveStylingLast: true,
componentOffset: true,
propertyBindings: true,
flags: true,
providerIndexes: true,
value: true,
attrs: true,
mergedAttrs: true,
localNames: true,
initialInputs: true,
inputs: true,
outputs: true,
tView: true,
next: true,
prev: true,
projectionNext: true,
child: true,
parent: true,
projection: true,
styles: true,
stylesWithoutHost: true,
residualStyles: true,
classes: true,
classesWithoutHost: true,
residualClasses: true,
classBindings: true,
styleBindings: true,
};
/**
* Determines if `obj` is DOM `Node`.
*/
export function isDOMNode(obj: any): obj is Node {
return obj instanceof Node;
}
/**
* Determines if `obj` is DOM `Text`.
*/
export function isDOMElement(obj: any): obj is Element {
return obj instanceof Element;
}
/**
* Determines if `obj` is DOM `Text`.
*/
export function isDOMText(obj: any): obj is Text {
return obj instanceof Text;
}
| {
"end_byte": 4883,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/is_shape_of.ts"
} |
angular/packages/core/test/render3/multi_map_spec.ts_0_1628 | /**
* @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 {UniqueValueMultiKeyMap} from '@angular/core/src/render3/list_reconciliation';
describe('MultiMap', () => {
it('should set, get and remove items with duplicated keys', () => {
const map = new UniqueValueMultiKeyMap();
map.set('k', 'v1');
map.set('k', 'v2');
expect(map.has('k')).toBeTrue();
expect(map.get('k')).toBe('v1');
map.delete('k');
expect(map.has('k')).toBeTrue();
expect(map.get('k')).toBe('v2');
map.delete('k');
expect(map.has('k')).toBeFalse();
});
it('should set, get and remove items without duplicated keys', () => {
const map = new UniqueValueMultiKeyMap();
map.set('k', 'v1');
expect(map.has('k')).toBeTrue();
expect(map.get('k')).toBe('v1');
map.delete('k');
expect(map.has('k')).toBeFalse();
});
it('should iterate with forEach', () => {
const map = new UniqueValueMultiKeyMap<string, string>();
map.set('km', 'v1');
map.set('km', 'v2');
map.set('ks', 'v');
const items: string[][] = [];
map.forEach((v, k) => items.push([v, k]));
expect(items).toEqual([
['v1', 'km'],
['v2', 'km'],
['v', 'ks'],
]);
});
it('should throw upon detecting duplicate values', () => {
const map = new UniqueValueMultiKeyMap();
map.set('k', 'v');
expect(() => {
map.set('k', 'v');
}).toThrowError(/Detected a duplicated value v for the key k/);
});
});
| {
"end_byte": 1628,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/multi_map_spec.ts"
} |
angular/packages/core/test/render3/matchers_spec.ts_0_3877 | /**
* @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 {createTNode, createTView} from '@angular/core/src/render3/instructions/shared';
import {TNodeType} from '@angular/core/src/render3/interfaces/node';
import {TViewType} from '@angular/core/src/render3/interfaces/view';
import {isShapeOf, ShapeOf} from './is_shape_of';
import {matchDomElement, matchDomText, matchObjectShape, matchTNode, matchTView} from './matchers';
describe('render3 matchers', () => {
const fakeMatcherUtil = {equals: (a: any, b: any) => a === b} as jasmine.MatchersUtil;
describe('matchObjectShape', () => {
interface MyShape {
propA: any;
propB: any;
}
const myShape: MyShape = {propA: 'value', propB: 3};
function isMyShape(obj: any): obj is MyShape {
return isShapeOf<MyShape>(obj, ShapeOfMyShape);
}
const ShapeOfMyShape: ShapeOf<MyShape> = {propA: true, propB: true};
function matchMyShape(expected?: Partial<MyShape>): jasmine.AsymmetricMatcher<MyShape> {
return matchObjectShape('MyShape', isMyShape, expected);
}
it('should match', () => {
expect(isMyShape(myShape)).toBeTrue();
expect(myShape).toEqual(matchMyShape());
expect(myShape).toEqual(matchMyShape({propA: 'value'}));
expect({node: myShape}).toEqual({node: matchMyShape({propA: 'value'})});
});
it('should produce human readable errors', () => {
const matcher = matchMyShape({propA: 'different'});
expect(matcher.asymmetricMatch(myShape, fakeMatcherUtil)).toEqual(false);
expect(matcher.jasmineToString!((value: any) => value + '')).toEqual(
'\n property obj.propA to equal different but got value',
);
});
});
describe('matchTView', () => {
const tView = createTView(TViewType.Root, null, null, 2, 3, null, null, null, null, null, null);
it('should match', () => {
expect(tView).toEqual(matchTView());
expect(tView).toEqual(matchTView({type: TViewType.Root}));
expect({node: tView}).toEqual({node: matchTView({type: TViewType.Root})});
});
});
describe('matchTNode', () => {
const tView = createTView(TViewType.Root, null, null, 2, 3, null, null, null, null, null, null);
const tNode = createTNode(tView, null, TNodeType.Element, 0, 'tagName', []);
it('should match', () => {
expect(tNode).toEqual(matchTNode());
expect(tNode).toEqual(matchTNode({type: TNodeType.Element, value: 'tagName'}));
expect({node: tNode}).toEqual({node: matchTNode({type: TNodeType.Element})});
});
});
describe('matchDomElement', () => {
const div = document.createElement('div');
div.setAttribute('name', 'Name');
it('should match', () => {
expect(div).toEqual(matchDomElement());
expect(div).toEqual(matchDomElement('div', {name: 'Name'}));
});
it('should produce human readable error', () => {
const matcher = matchDomElement('div', {name: 'other'});
expect(matcher.asymmetricMatch(div, fakeMatcherUtil)).toEqual(false);
expect(matcher.jasmineToString!((value: any) => value + '')).toEqual(
`[<DIV name="Name"> != <div name="other">]`,
);
});
});
describe('matchDomText', () => {
const text = document.createTextNode('myText');
it('should match', () => {
expect(text).toEqual(matchDomText());
expect(text).toEqual(matchDomText('myText'));
});
it('should produce human readable error', () => {
const matcher = matchDomText('other text');
expect(matcher.asymmetricMatch(text, fakeMatcherUtil)).toEqual(false);
expect(matcher.jasmineToString!((value: any) => value + '')).toEqual(
`[#TEXT: "myText" != #TEXT: "other text"]`,
);
});
});
});
| {
"end_byte": 3877,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/matchers_spec.ts"
} |
angular/packages/core/test/render3/matchers.ts_0_7600 | /**
* @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 {I18nDebug, IcuCreateOpCodes, TI18n, TIcu} from '@angular/core/src/render3/interfaces/i18n';
import {TNode} from '@angular/core/src/render3/interfaces/node';
import {TView} from '@angular/core/src/render3/interfaces/view';
import {isDOMElement, isDOMText, isTI18n, isTIcu, isTNode, isTView} from './is_shape_of';
/**
* Generic matcher which asserts that an object is of a given shape (`shapePredicate`) and that it
* contains a subset of properties.
*
* @param name Name of `shapePredicate` to display when assertion fails.
* @param shapePredicate Predicate which verifies that the object is of correct shape.
* @param expected Expected set of properties to be found on the object.
*/
export function matchObjectShape<T>(
name: string,
shapePredicate: (obj: any) => obj is T,
expected: Partial<T> = {},
): jasmine.AsymmetricMatcher<T> {
const matcher = function () {};
let _actual: any = null;
let _matcherUtils: jasmine.MatchersUtil = null!;
matcher.asymmetricMatch = function (actual: any, matcherUtils: jasmine.MatchersUtil) {
_actual = actual;
_matcherUtils = matcherUtils;
if (!shapePredicate(actual)) return false;
for (const key in expected) {
if (expected.hasOwnProperty(key) && !matcherUtils.equals(actual[key], expected[key])) {
return false;
}
}
return true;
};
matcher.jasmineToString = function (pp: (value: any) => string) {
let errors: string[] = [];
if (!_actual || typeof _actual !== 'object') {
return `Expecting ${pp(expect)} got ${pp(_actual)}`;
}
for (const key in expected) {
if (expected.hasOwnProperty(key) && !_matcherUtils.equals(_actual[key], expected[key]))
errors.push(`\n property obj.${key} to equal ${expected[key]} but got ${_actual[key]}`);
}
return errors.join('\n');
};
return matcher;
}
/**
* Asymmetric matcher which matches a `TView` of a given shape.
*
* Expected usage:
* ```
* expect(tNode).toEqual(matchTView({type: TViewType.Root}));
* expect({
* node: tNode
* }).toEqual({
* node: matchTNode({type: TViewType.Root})
* });
* ```
*
* @param expected optional properties which the `TView` must contain.
*/
export function matchTView(expected?: Partial<TView>): jasmine.AsymmetricMatcher<TView> {
return matchObjectShape('TView', isTView, expected);
}
/**
* Asymmetric matcher which matches a `TNode` of a given shape.
*
* Expected usage:
* ```
* expect(tNode).toEqual(matchTNode({type: TNodeType.Element}));
* expect({
* node: tNode
* }).toEqual({
* node: matchTNode({type: TNodeType.Element})
* });
* ```
*
* @param expected optional properties which the `TNode` must contain.
*/
export function matchTNode(expected?: Partial<TNode>): jasmine.AsymmetricMatcher<TNode> {
return matchObjectShape('TNode', isTNode, expected);
}
/**
* Asymmetric matcher which matches a `T18n` of a given shape.
*
* Expected usage:
* ```
* expect(tNode).toEqual(matchT18n({vars: 0}));
* expect({
* node: tNode
* }).toEqual({
* node: matchT18n({vars: 0})
* });
* ```
*
* @param expected optional properties which the `TI18n` must contain.
*/
export function matchTI18n(expected?: Partial<TI18n>): jasmine.AsymmetricMatcher<TI18n> {
return matchObjectShape('TI18n', isTI18n, expected);
}
/**
* Asymmetric matcher which matches a `T1cu` of a given shape.
*
* Expected usage:
* ```
* expect(tNode).toEqual(matchTIcu({type: TIcuType.select}));
* expect({
* type: TIcuType.select
* }).toEqual({
* node: matchT18n({type: TIcuType.select})
* });
* ```
*
* @param expected optional properties which the `TIcu` must contain.
*/
export function matchTIcu(expected?: Partial<TIcu>): jasmine.AsymmetricMatcher<TIcu> {
return matchObjectShape('TIcu', isTIcu, expected);
}
/**
* Asymmetric matcher which matches a DOM Element.
*
* Expected usage:
* ```
* expect(div).toEqual(matchT18n('div', {id: '123'}));
* expect({
* node: div
* }).toEqual({
* node: matchT18n('div', {id: '123'})
* });
* ```
*
* @param expectedTagName optional DOM tag name.
* @param expectedAttributes optional DOM element properties.
*/
export function matchDomElement(
expectedTagName: string | undefined = undefined,
expectedAttrs: {[key: string]: string | null} = {},
): jasmine.AsymmetricMatcher<Element> {
const matcher = function () {};
let _actual: any = null;
matcher.asymmetricMatch = function (actual: any) {
_actual = actual;
if (!isDOMElement(actual)) return false;
if (expectedTagName && expectedTagName.toUpperCase() !== actual.tagName.toUpperCase()) {
return false;
}
if (expectedAttrs) {
for (const attrName in expectedAttrs) {
if (expectedAttrs.hasOwnProperty(attrName)) {
const expectedAttrValue = expectedAttrs[attrName];
const actualAttrValue = actual.getAttribute(attrName);
if (expectedAttrValue !== actualAttrValue) {
return false;
}
}
}
}
return true;
};
matcher.jasmineToString = function () {
let actualStr = isDOMElement(_actual)
? `<${_actual.tagName}${toString(_actual.attributes)}>`
: JSON.stringify(_actual);
let expectedStr = `<${expectedTagName || '*'}${Object.entries(expectedAttrs).map(
([key, value]) => ` ${key}=${JSON.stringify(value)}`,
)}>`;
return `[${actualStr} != ${expectedStr}]`;
};
function toString(attrs: NamedNodeMap) {
let text = '';
for (let i = 0; i < attrs.length; i++) {
const attr = attrs[i];
text += ` ${attr.name}=${JSON.stringify(attr.value)}`;
}
return text;
}
return matcher;
}
/**
* Asymmetric matcher which matches DOM text node.
*
* Expected usage:
* ```
* expect(div).toEqual(matchDomText('text'));
* expect({
* node: div
* }).toEqual({
* node: matchDomText('text')
* });
* ```
*
* @param expectedText optional DOM text.
*/
export function matchDomText(
expectedText: string | undefined = undefined,
): jasmine.AsymmetricMatcher<Text> {
const matcher = function () {};
let _actual: any = null;
matcher.asymmetricMatch = function (actual: any) {
_actual = actual;
if (!isDOMText(actual)) return false;
if (expectedText && expectedText !== actual.textContent) {
return false;
}
return true;
};
matcher.jasmineToString = function () {
let actualStr = isDOMText(_actual)
? `#TEXT: ${JSON.stringify(_actual.textContent)}`
: JSON.stringify(_actual);
let expectedStr = `#TEXT: ${JSON.stringify(expectedText)}`;
return `[${actualStr} != ${expectedStr}]`;
};
return matcher;
}
export function matchI18nMutableOpCodes(
expectedMutableOpCodes: string[],
): jasmine.AsymmetricMatcher<IcuCreateOpCodes> {
const matcher = function () {};
let _actual: any = null;
matcher.asymmetricMatch = function (actual: any, matchersUtil: jasmine.MatchersUtil) {
_actual = actual;
if (!Array.isArray(actual)) return false;
const debug = (actual as I18nDebug).debug as undefined | string[];
if (expectedMutableOpCodes && !matchersUtil.equals(debug, expectedMutableOpCodes)) {
return false;
}
return true;
};
matcher.jasmineToString = function () {
const debug = (_actual as I18nDebug).debug as undefined | string[];
return `[${JSON.stringify(debug)} != ${expectedMutableOpCodes}]`;
};
return matcher;
}
| {
"end_byte": 7600,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/matchers.ts"
} |
angular/packages/core/test/render3/instructions_spec.ts_0_1347 | /**
* @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, Input} from '@angular/core/public_api';
import {ngDevModeResetPerfCounters} from '@angular/core/src/util/ng_dev_mode';
import {TestBed} from '@angular/core/testing';
import {getSortedClassName} from '@angular/core/testing/src/styling';
import {
ɵɵadvance,
ɵɵattribute,
ɵɵclassMap,
ɵɵelement,
ɵɵproperty,
ɵɵstyleMap,
ɵɵstyleProp,
} from '../../src/render3/index';
import {AttributeMarker} from '../../src/render3/interfaces/attribute_marker';
import {
bypassSanitizationTrustHtml,
bypassSanitizationTrustResourceUrl,
bypassSanitizationTrustScript,
bypassSanitizationTrustStyle,
bypassSanitizationTrustUrl,
getSanitizationBypassType,
SafeValue,
unwrapSafeValue,
} from '../../src/sanitization/bypass';
import {
ɵɵsanitizeHtml,
ɵɵsanitizeResourceUrl,
ɵɵsanitizeScript,
ɵɵsanitizeStyle,
ɵɵsanitizeUrl,
} from '../../src/sanitization/sanitization';
import {Sanitizer} from '../../src/sanitization/sanitizer';
import {SecurityContext} from '../../src/sanitization/security';
import {ViewFixture} from './view_fixture';
describe('instructions | {
"end_byte": 1347,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/instructions_spec.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.