_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/core/test/linker/integration_spec.ts_1793_11119 | scribe('integration tests', function () {
describe('react to record changes', function () {
it('should consume text node changes', () => {
TestBed.configureTestingModule({declarations: [MyComp]});
const template = '<div>{{ctxProp}}</div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = 'Hello World!';
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('Hello World!');
});
it('should update text node with a blank string when interpolation evaluates to null', () => {
TestBed.configureTestingModule({declarations: [MyComp]});
const template = '<div>{{null}}{{ctxProp}}</div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = null!;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('');
});
it('should allow both null and undefined in expressions', () => {
const template = '<div>{{null == undefined}}|{{null === undefined}}</div>';
const fixture = TestBed.configureTestingModule({declarations: [MyComp]})
.overrideComponent(MyComp, {set: {template}})
.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('true|false');
});
it('should support an arbitrary number of interpolations in an element', () => {
TestBed.configureTestingModule({declarations: [MyComp]});
const template = `<div>before{{'0'}}a{{'1'}}b{{'2'}}c{{'3'}}d{{'4'}}e{{'5'}}f{{'6'}}g{{'7'}}h{{'8'}}i{{'9'}}j{{'10'}}after</div>`;
const fixture = TestBed.overrideComponent(MyComp, {set: {template}}).createComponent(MyComp);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('before0a1b2c3d4e5f6g7h8i9j10after');
});
it('should use a blank string when interpolation evaluates to null or undefined with an arbitrary number of interpolations', () => {
TestBed.configureTestingModule({declarations: [MyComp]});
const template = `<div>0{{null}}a{{undefined}}b{{null}}c{{undefined}}d{{null}}e{{undefined}}f{{null}}g{{undefined}}h{{null}}i{{undefined}}j{{null}}1</div>`;
const fixture = TestBed.overrideComponent(MyComp, {set: {template}}).createComponent(MyComp);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('0abcdefghij1');
});
it('should consume element binding changes', () => {
TestBed.configureTestingModule({declarations: [MyComp]});
const template = '<div [id]="ctxProp"></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = 'Hello World!';
fixture.detectChanges();
expect(fixture.debugElement.children[0].nativeElement.id).toEqual('Hello World!');
});
it('should consume binding to aria-* attributes', () => {
TestBed.configureTestingModule({declarations: [MyComp]});
const template = '<div [attr.aria-label]="ctxProp"></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = 'Initial aria label';
fixture.detectChanges();
expect(fixture.debugElement.children[0].nativeElement.getAttribute('aria-label')).toEqual(
'Initial aria label',
);
fixture.componentInstance.ctxProp = 'Changed aria label';
fixture.detectChanges();
expect(fixture.debugElement.children[0].nativeElement.getAttribute('aria-label')).toEqual(
'Changed aria label',
);
});
it('should remove an attribute when attribute expression evaluates to null', () => {
TestBed.configureTestingModule({declarations: [MyComp]});
const template = '<div [attr.foo]="ctxProp"></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = 'bar';
fixture.detectChanges();
expect(fixture.debugElement.children[0].nativeElement.getAttribute('foo')).toEqual('bar');
fixture.componentInstance.ctxProp = null!;
fixture.detectChanges();
expect(fixture.debugElement.children[0].nativeElement.hasAttribute('foo')).toBeFalsy();
});
it('should remove style when when style expression evaluates to null', () => {
TestBed.configureTestingModule({declarations: [MyComp]});
const template = '<div [style.height.px]="ctxProp"></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = '10';
fixture.detectChanges();
expect(fixture.debugElement.children[0].nativeElement.style['height']).toEqual('10px');
fixture.componentInstance.ctxProp = null!;
fixture.detectChanges();
expect(fixture.debugElement.children[0].nativeElement.style['height']).toEqual('');
});
it('should consume binding to property names where attr name and property name do not match', () => {
TestBed.configureTestingModule({declarations: [MyComp]});
const template = '<div [tabindex]="ctxNumProp"></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.debugElement.children[0].nativeElement.tabIndex).toEqual(0);
fixture.componentInstance.ctxNumProp = 5;
fixture.detectChanges();
expect(fixture.debugElement.children[0].nativeElement.tabIndex).toEqual(5);
});
it('should consume binding to camel-cased properties', () => {
TestBed.configureTestingModule({declarations: [MyComp]});
const template = '<input [readOnly]="ctxBoolProp">';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.debugElement.children[0].nativeElement.readOnly).toBeFalsy();
fixture.componentInstance.ctxBoolProp = true;
fixture.detectChanges();
expect(fixture.debugElement.children[0].nativeElement.readOnly).toBeTruthy();
});
it('should consume binding to innerHtml', () => {
TestBed.configureTestingModule({declarations: [MyComp]});
const template = '<div innerHtml="{{ctxProp}}"></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = 'Some <span>HTML</span>';
fixture.detectChanges();
expect(fixture.debugElement.children[0].nativeElement.innerHTML).toEqual(
'Some <span>HTML</span>',
);
fixture.componentInstance.ctxProp = 'Some other <div>HTML</div>';
fixture.detectChanges();
expect(fixture.debugElement.children[0].nativeElement.innerHTML).toEqual(
'Some other <div>HTML</div>',
);
});
it('should consume binding to htmlFor using for alias', () => {
const template = '<label [for]="ctxProp"></label>';
const fixture = TestBed.configureTestingModule({declarations: [MyComp]})
.overrideComponent(MyComp, {set: {template}})
.createComponent(MyComp);
const nativeEl = fixture.debugElement.children[0].nativeElement;
fixture.debugElement.componentInstance.ctxProp = 'foo';
fixture.detectChanges();
expect(nativeEl.htmlFor).toBe('foo');
});
it('should consume directive watch expression change.', () => {
TestBed.configureTestingModule({declarations: [MyComp, MyDir]});
const template =
'<span>' +
'<div my-dir [elprop]="ctxProp"></div>' +
'<div my-dir elprop="Hi there!"></div>' +
'<div my-dir elprop="Hi {{\'there!\'}}"></div>' +
'<div my-dir elprop="One more {{ctxProp}}"></div>' +
'</span>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = 'Hello World!';
fixture.detectChanges();
const containerSpan = fixture.debugElement.children[0];
expect(containerSpan.children[0].injector.get(MyDir).dirProp).toEqual('Hello World!');
expect(containerSpan.children[1].injector.get(MyDir).dirProp).toEqual('Hi there!');
expect(containerSpan.children[2].injector.get(MyDir).dirProp).toEqual('Hi there!');
expect(containerSpan.children[3].injector.get(MyDir).dirProp).toEqual(
'One more Hello World!',
);
});
describe('pipes', () => {
it('should support pipes in bindings', () => {
TestBed.configureTestingModule({declarations: [MyComp, MyDir, DoublePipe]});
const template = '<div my-dir #dir="mydir" [elprop]="ctxProp | double"></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = 'a';
fixture.detectChanges();
const dir = fixture.debugElement.children[0].references!['dir'];
expect(dir.dirProp).toEqual('aa');
});
});
| {
"end_byte": 11119,
"start_byte": 1793,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/integration_spec.ts"
} |
angular/packages/core/test/linker/integration_spec.ts_11125_18292 | ('should support nested components.', () => {
TestBed.configureTestingModule({declarations: [MyComp, ChildComp]});
const template = '<child-cmp></child-cmp>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('hello');
});
// GH issue 328 - https://github.com/angular/angular/issues/328
it('should support different directive types on a single node', () => {
TestBed.configureTestingModule({declarations: [MyComp, ChildComp, MyDir]});
const template = '<child-cmp my-dir [elprop]="ctxProp"></child-cmp>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = 'Hello World!';
fixture.detectChanges();
const tc = fixture.debugElement.children[0];
expect(tc.injector.get(MyDir).dirProp).toEqual('Hello World!');
expect(tc.injector.get(ChildComp).dirProp).toEqual(null);
});
it('should support directives where a binding attribute is not given', () => {
TestBed.configureTestingModule({declarations: [MyComp, MyDir]});
const template = '<p my-dir></p>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
});
it('should execute a given directive once, even if specified multiple times', () => {
TestBed.configureTestingModule({
declarations: [MyComp, DuplicateDir, DuplicateDir, [DuplicateDir, [DuplicateDir]]],
});
const template = '<p no-duplicate></p>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
expect(fixture.nativeElement).toHaveText('noduplicate');
});
it('should support directives where a selector matches property binding', () => {
TestBed.configureTestingModule({declarations: [MyComp, IdDir]});
const template = '<p [id]="ctxProp"></p>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const tc = fixture.debugElement.children[0];
const idDir = tc.injector.get(IdDir);
fixture.componentInstance.ctxProp = 'some_id';
fixture.detectChanges();
expect(idDir.id).toEqual('some_id');
fixture.componentInstance.ctxProp = 'other_id';
fixture.detectChanges();
expect(idDir.id).toEqual('other_id');
});
it('should support directives where a selector matches event binding', () => {
TestBed.configureTestingModule({declarations: [MyComp, EventDir]});
const template = '<p (customEvent)="doNothing()"></p>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const tc = fixture.debugElement.children[0];
expect(tc.injector.get(EventDir)).not.toBeNull();
});
it('should display correct error message for uninitialized @Output', () => {
@Component({
selector: 'my-uninitialized-output',
template: '<p>It works!</p>',
standalone: false,
})
class UninitializedOutputComp {
@Output() customEvent!: EventEmitter<any>;
}
const template =
'<my-uninitialized-output (customEvent)="doNothing()"></my-uninitialized-output>';
TestBed.overrideComponent(MyComp, {set: {template}});
TestBed.configureTestingModule({declarations: [MyComp, UninitializedOutputComp]});
expect(() => TestBed.createComponent(MyComp)).toThrowError(
"@Output customEvent not initialized in 'UninitializedOutputComp'.",
);
});
it('should read directives metadata from their binding token', () => {
TestBed.configureTestingModule({declarations: [MyComp, PrivateImpl, NeedsPublicApi]});
const template = '<div public-api><div needs-public-api></div></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
});
it('should not share empty context for template directives - issue #10045', () => {
TestBed.configureTestingModule({declarations: [MyComp, PollutedContext, NoContext]});
const template =
'<ng-template pollutedContext let-foo="bar">{{foo}}</ng-template><ng-template noContext let-foo="bar">{{foo}}</ng-template>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('baz');
});
it('should not detach views in ViewContainers when the parent view is destroyed.', () => {
TestBed.configureTestingModule({declarations: [MyComp, SomeViewport]});
const template =
'<div *ngIf="ctxBoolProp"><ng-template some-viewport let-greeting="someTmpl"><span>{{greeting}}</span></ng-template></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxBoolProp = true;
fixture.detectChanges();
const ngIfEl = fixture.debugElement.children[0];
const someViewport: SomeViewport = ngIfEl.childNodes
.find((debugElement) => debugElement.nativeNode.nodeType === Node.COMMENT_NODE)!
.injector.get(SomeViewport);
expect(someViewport.container.length).toBe(2);
expect(ngIfEl.children.length).toBe(2);
fixture.componentInstance.ctxBoolProp = false;
fixture.detectChanges();
expect(someViewport.container.length).toBe(2);
expect(fixture.debugElement.children.length).toBe(0);
});
it('should use a comment while stamping out `<ng-template>` elements.', () => {
const fixture = TestBed.configureTestingModule({declarations: [MyComp]})
.overrideComponent(MyComp, {set: {template: '<ng-template></ng-template>'}})
.createComponent(MyComp);
const childNodesOfWrapper = fixture.nativeElement.childNodes;
expect(childNodesOfWrapper.length).toBe(1);
expect(isCommentNode(childNodesOfWrapper[0])).toBe(true);
});
it('should allow to transplant TemplateRefs into other ViewContainers', () => {
TestBed.configureTestingModule({
declarations: [
MyComp,
SomeDirective,
CompWithHost,
ToolbarComponent,
ToolbarViewContainer,
ToolbarPart,
],
imports: [CommonModule],
schemas: [NO_ERRORS_SCHEMA],
});
const template =
'<some-directive><toolbar><ng-template toolbarpart let-toolbarProp="toolbarProp">{{ctxProp}},{{toolbarProp}},<cmp-with-host></cmp-with-host></ng-template></toolbar></some-directive>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = 'From myComp';
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText(
'TOOLBAR(From myComp,From toolbar,Component with an injected host)',
);
});
| {
"end_byte": 18292,
"start_byte": 11125,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/integration_spec.ts"
} |
angular/packages/core/test/linker/integration_spec.ts_18298_23156 | scribe('reference bindings', () => {
it('should assign a component to a ref-', () => {
TestBed.configureTestingModule({declarations: [MyComp, ChildComp]});
const template = '<p><child-cmp ref-alice></child-cmp></p>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
expect(fixture.debugElement.children[0].children[0].references!['alice']).toBeInstanceOf(
ChildComp,
);
});
it('should assign a directive to a ref-', () => {
TestBed.configureTestingModule({declarations: [MyComp, ExportDir]});
const template = '<div><div export-dir #localdir="dir"></div></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
expect(fixture.debugElement.children[0].children[0].references!['localdir']).toBeInstanceOf(
ExportDir,
);
});
it('should assign a directive to a ref when it has multiple exportAs names', () => {
TestBed.configureTestingModule({
declarations: [MyComp, DirectiveWithMultipleExportAsNames],
});
const template = '<div multiple-export-as #x="dirX" #y="dirY"></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
expect(fixture.debugElement.children[0].references!['x']).toBeInstanceOf(
DirectiveWithMultipleExportAsNames,
);
expect(fixture.debugElement.children[0].references!['y']).toBeInstanceOf(
DirectiveWithMultipleExportAsNames,
);
});
it('should make the assigned component accessible in property bindings, even if they were declared before the component', () => {
TestBed.configureTestingModule({declarations: [MyComp, ChildComp]});
const template =
'<ng-template [ngIf]="true">{{alice.ctxProp}}</ng-template>|{{alice.ctxProp}}|<child-cmp ref-alice></child-cmp>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('hello|hello|hello');
});
it('should assign two component instances each with a ref-', () => {
TestBed.configureTestingModule({declarations: [MyComp, ChildComp]});
const template = '<p><child-cmp ref-alice></child-cmp><child-cmp ref-bob></child-cmp></p>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const pEl = fixture.debugElement.children[0];
const alice = pEl.children[0].references!['alice'];
const bob = pEl.children[1].references!['bob'];
expect(alice).toBeInstanceOf(ChildComp);
expect(bob).toBeInstanceOf(ChildComp);
expect(alice).not.toBe(bob);
});
it('should assign the component instance to a ref- with shorthand syntax', () => {
TestBed.configureTestingModule({declarations: [MyComp, ChildComp]});
const template = '<child-cmp #alice></child-cmp>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
expect(fixture.debugElement.children[0].references!['alice']).toBeInstanceOf(ChildComp);
});
it('should assign the element instance to a user-defined variable', () => {
TestBed.configureTestingModule({declarations: [MyComp]});
const template = '<div><div ref-alice><i>Hello</i></div></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const value = fixture.debugElement.children[0].children[0].references!['alice'];
expect(value).not.toBe(null);
expect(value.tagName.toLowerCase()).toEqual('div');
});
it('should assign the TemplateRef to a user-defined variable', () => {
const fixture = TestBed.configureTestingModule({declarations: [MyComp]})
.overrideComponent(MyComp, {set: {template: '<ng-template ref-alice></ng-template>'}})
.createComponent(MyComp);
const value = fixture.debugElement.childNodes[0].references!['alice'];
expect(value.createEmbeddedView).toBeTruthy();
});
it('should preserve case', () => {
TestBed.configureTestingModule({declarations: [MyComp, ChildComp]});
const template = '<p><child-cmp ref-superAlice></child-cmp></p>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
expect(
fixture.debugElement.children[0].children[0].references!['superAlice'],
).toBeInstanceOf(ChildComp);
});
});
| {
"end_byte": 23156,
"start_byte": 18298,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/integration_spec.ts"
} |
angular/packages/core/test/linker/integration_spec.ts_23162_32122 | scribe('OnPush components', () => {
it('should use ChangeDetectorRef to manually request a check', () => {
TestBed.configureTestingModule({declarations: [MyComp, [[PushCmpWithRef]]]});
const template = '<push-cmp-with-ref #cmp></push-cmp-with-ref>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const cmp = fixture.debugElement.children[0].references!['cmp'];
fixture.detectChanges();
expect(cmp.numberOfChecks).toEqual(1);
fixture.detectChanges();
expect(cmp.numberOfChecks).toEqual(1);
cmp.propagate();
fixture.detectChanges();
expect(cmp.numberOfChecks).toEqual(2);
});
it('should be checked when its bindings got updated', () => {
TestBed.configureTestingModule({
declarations: [MyComp, PushCmp, EventCmp],
imports: [CommonModule],
});
const template = '<push-cmp [prop]="ctxProp" #cmp></push-cmp>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const cmp = fixture.debugElement.children[0].references!['cmp'];
fixture.componentInstance.ctxProp = 'one';
fixture.detectChanges();
expect(cmp.numberOfChecks).toEqual(1);
fixture.componentInstance.ctxProp = 'two';
fixture.detectChanges();
expect(cmp.numberOfChecks).toEqual(2);
});
if (getDOM().supportsDOMEvents) {
it('should allow to destroy a component from within a host event handler', fakeAsync(() => {
TestBed.configureTestingModule({declarations: [MyComp, [[PushCmpWithHostEvent]]]});
const template = '<push-cmp-with-host-event></push-cmp-with-host-event>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
tick();
fixture.detectChanges();
const cmpEl = fixture.debugElement.children[0];
const cmp: PushCmpWithHostEvent = cmpEl.injector.get(PushCmpWithHostEvent);
cmp.ctxCallback = (_: any) => fixture.destroy();
expect(() => cmpEl.triggerEventHandler('click', <Event>{})).not.toThrow();
}));
}
it('should be checked when an event is fired', () => {
TestBed.configureTestingModule({
declarations: [MyComp, PushCmp, EventCmp],
imports: [CommonModule],
});
const template = '<push-cmp [prop]="ctxProp" #cmp></push-cmp>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const cmpEl = fixture.debugElement.children[0];
const cmp = cmpEl.componentInstance;
fixture.detectChanges();
fixture.detectChanges();
expect(cmp.numberOfChecks).toEqual(1);
// regular element
cmpEl.children[0].triggerEventHandler('click', <Event>{});
fixture.detectChanges();
fixture.detectChanges();
expect(cmp.numberOfChecks).toEqual(2);
// element inside of an *ngIf
cmpEl.children[1].triggerEventHandler('click', <Event>{});
fixture.detectChanges();
fixture.detectChanges();
expect(cmp.numberOfChecks).toEqual(3);
// element inside a nested component
cmpEl.children[2].children[0].triggerEventHandler('click', <Event>{});
fixture.detectChanges();
fixture.detectChanges();
expect(cmp.numberOfChecks).toEqual(4);
// host element
cmpEl.triggerEventHandler('click', <Event>{});
fixture.detectChanges();
fixture.detectChanges();
expect(cmp.numberOfChecks).toEqual(5);
});
it('should not affect updating properties on the component', () => {
TestBed.configureTestingModule({declarations: [MyComp, [[PushCmpWithRef]]]});
const template = '<push-cmp-with-ref [prop]="ctxProp" #cmp></push-cmp-with-ref>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const cmp = fixture.debugElement.children[0].references!['cmp'];
fixture.componentInstance.ctxProp = 'one';
fixture.detectChanges();
expect(cmp.prop).toEqual('one');
fixture.componentInstance.ctxProp = 'two';
fixture.detectChanges();
expect(cmp.prop).toEqual('two');
});
it('should be checked when an async pipe requests a check', fakeAsync(() => {
TestBed.configureTestingModule({
declarations: [MyComp, PushCmpWithAsyncPipe],
imports: [CommonModule],
});
const template = '<push-cmp-with-async #cmp></push-cmp-with-async>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
tick();
const cmp: PushCmpWithAsyncPipe = fixture.debugElement.children[0].references!['cmp'];
fixture.detectChanges();
expect(cmp.numberOfChecks).toEqual(1);
fixture.detectChanges();
fixture.detectChanges();
expect(cmp.numberOfChecks).toEqual(1);
cmp.resolve(2);
tick();
fixture.detectChanges();
expect(cmp.numberOfChecks).toEqual(2);
}));
});
it('should create a component that injects an @Host', () => {
TestBed.configureTestingModule({
declarations: [MyComp, SomeDirective, CompWithHost],
schemas: [NO_ERRORS_SCHEMA],
});
const template = `
<some-directive>
<p>
<cmp-with-host #child></cmp-with-host>
</p>
</some-directive>`;
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const childComponent =
fixture.debugElement.children[0].children[0].children[0].references!['child'];
expect(childComponent.myHost).toBeInstanceOf(SomeDirective);
});
it('should create a component that injects an @Host through viewcontainer directive', () => {
TestBed.configureTestingModule({
declarations: [MyComp, SomeDirective, CompWithHost],
schemas: [NO_ERRORS_SCHEMA],
});
const template = `
<some-directive>
<p *ngIf="true">
<cmp-with-host #child></cmp-with-host>
</p>
</some-directive>`;
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const tc = fixture.debugElement.children[0].children[0].children[0];
const childComponent = tc.references!['child'];
expect(childComponent.myHost).toBeInstanceOf(SomeDirective);
});
it('should support events via EventEmitter on regular elements', waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [MyComp, DirectiveEmittingEvent, DirectiveListeningEvent],
});
const template = '<div emitter listener></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const tc = fixture.debugElement.children[0];
const emitter = tc.injector.get(DirectiveEmittingEvent);
const listener = tc.injector.get(DirectiveListeningEvent);
expect(listener.msg).toEqual('');
let eventCount = 0;
emitter.event.subscribe({
next: () => {
eventCount++;
if (eventCount === 1) {
expect(listener.msg).toEqual('fired !');
fixture.destroy();
emitter.fireEvent('fired again !');
} else {
expect(listener.msg).toEqual('fired !');
}
},
});
emitter.fireEvent('fired !');
}));
it('should support events via EventEmitter on template elements', waitForAsync(() => {
const fixture = TestBed.configureTestingModule({
declarations: [MyComp, DirectiveEmittingEvent, DirectiveListeningEvent],
})
.overrideComponent(MyComp, {
set: {
template: '<ng-template emitter listener (event)="ctxProp=$event"></ng-template>',
},
})
.createComponent(MyComp);
const tc = fixture.debugElement.childNodes.find(
(debugElement) => debugElement.nativeNode.nodeType === Node.COMMENT_NODE,
)!;
const emitter = tc.injector.get(DirectiveEmittingEvent);
const myComp = fixture.debugElement.injector.get(MyComp);
const listener = tc.injector.get(DirectiveListeningEvent);
myComp.ctxProp = '';
expect(listener.msg).toEqual('');
emitter.event.subscribe({
next: () => {
expect(listener.msg).toEqual('fired !');
expect(myComp.ctxProp).toEqual('fired !');
},
});
emitter.fireEvent('fired !');
}));
| {
"end_byte": 32122,
"start_byte": 23162,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/integration_spec.ts"
} |
angular/packages/core/test/linker/integration_spec.ts_32128_40477 | ('should support [()] syntax', waitForAsync(() => {
TestBed.configureTestingModule({declarations: [MyComp, DirectiveWithTwoWayBinding]});
const template = '<div [(control)]="ctxProp" two-way></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const tc = fixture.debugElement.children[0];
const dir = tc.injector.get(DirectiveWithTwoWayBinding);
fixture.componentInstance.ctxProp = 'one';
fixture.detectChanges();
expect(dir.control).toEqual('one');
dir.controlChange.subscribe({
next: () => {
expect(fixture.componentInstance.ctxProp).toEqual('two');
},
});
dir.triggerChange('two');
}));
it('should support render events', () => {
TestBed.configureTestingModule({declarations: [MyComp, DirectiveListeningDomEvent]});
const template = '<div listener></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const tc = fixture.debugElement.children[0];
const listener = tc.injector.get(DirectiveListeningDomEvent);
dispatchEvent(tc.nativeElement, 'domEvent');
expect(listener.eventTypes).toEqual([
'domEvent',
'body_domEvent',
'document_domEvent',
'window_domEvent',
]);
fixture.destroy();
listener.eventTypes = [];
dispatchEvent(tc.nativeElement, 'domEvent');
expect(listener.eventTypes).toEqual([]);
});
it('should support render global events', () => {
TestBed.configureTestingModule({declarations: [MyComp, DirectiveListeningDomEvent]});
const template = '<div listener></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const doc = TestBed.inject(DOCUMENT);
const tc = fixture.debugElement.children[0];
const listener = tc.injector.get(DirectiveListeningDomEvent);
dispatchEvent(getDOM().getGlobalEventTarget(doc, 'window'), 'domEvent');
expect(listener.eventTypes).toEqual(['window_domEvent']);
listener.eventTypes = [];
dispatchEvent(getDOM().getGlobalEventTarget(doc, 'document'), 'domEvent');
expect(listener.eventTypes).toEqual(['document_domEvent', 'window_domEvent']);
fixture.destroy();
listener.eventTypes = [];
dispatchEvent(getDOM().getGlobalEventTarget(doc, 'body'), 'domEvent');
expect(listener.eventTypes).toEqual([]);
});
it('should support updating host element via hostAttributes on root elements', () => {
@Component({
host: {'role': 'button'},
template: '',
standalone: false,
})
class ComponentUpdatingHostAttributes {}
TestBed.configureTestingModule({declarations: [ComponentUpdatingHostAttributes]});
const fixture = TestBed.createComponent(ComponentUpdatingHostAttributes);
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.getAttribute('role')).toEqual('button');
});
it('should support updating host element via hostAttributes on host elements', () => {
TestBed.configureTestingModule({declarations: [MyComp, DirectiveUpdatingHostAttributes]});
const template = '<div update-host-attributes></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.debugElement.children[0].nativeElement.getAttribute('role')).toEqual('button');
});
it('should support updating host element via hostProperties', () => {
TestBed.configureTestingModule({declarations: [MyComp, DirectiveUpdatingHostProperties]});
const template = '<div update-host-properties></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const tc = fixture.debugElement.children[0];
const updateHost = tc.injector.get(DirectiveUpdatingHostProperties);
updateHost.id = 'newId';
fixture.detectChanges();
expect(tc.nativeElement.id).toEqual('newId');
});
it('should not use template variables for expressions in hostProperties', () => {
@Directive({
selector: '[host-properties]',
host: {'[id]': 'id', '[title]': 'unknownProp'},
standalone: false,
})
class DirectiveWithHostProps {
id = 'one';
unknownProp = 'unknownProp';
}
const fixture = TestBed.configureTestingModule({
declarations: [MyComp, DirectiveWithHostProps],
})
.overrideComponent(MyComp, {
set: {template: `<div *ngFor="let id of ['forId']" host-properties></div>`},
})
.createComponent(MyComp);
fixture.detectChanges();
const tc = fixture.debugElement.children[0];
expect(tc.properties['id']).toBe('one');
expect(tc.properties['title']).toBe('unknownProp');
});
it('should not allow pipes in hostProperties', () => {
@Directive({
selector: '[host-properties]',
host: {'[id]': 'id | uppercase'},
standalone: false,
})
class DirectiveWithHostProps {}
TestBed.configureTestingModule({declarations: [MyComp, DirectiveWithHostProps]});
const template = '<div host-properties></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
expect(() => TestBed.createComponent(MyComp)).toThrowError(
/Host binding expression cannot contain pipes/,
);
});
it('should not use template variables for expressions in hostListeners', () => {
@Directive({
selector: '[host-listener]',
host: {'(click)': 'doIt(id, unknownProp)'},
standalone: false,
})
class DirectiveWithHostListener {
id = 'one';
receivedArgs: any[] = [];
doIt(...args: any[]) {
this.receivedArgs = args;
}
}
const fixture = TestBed.configureTestingModule({
declarations: [MyComp, DirectiveWithHostListener],
})
.overrideComponent(MyComp, {
set: {template: `<div *ngFor="let id of ['forId']" host-listener></div>`},
})
.createComponent(MyComp);
fixture.detectChanges();
const tc = fixture.debugElement.children[0];
tc.triggerEventHandler('click', {});
const dir: DirectiveWithHostListener = tc.injector.get(DirectiveWithHostListener);
expect(dir.receivedArgs).toEqual(['one', undefined]);
});
it('should not allow pipes in hostListeners', () => {
@Directive({
selector: '[host-listener]',
host: {'(click)': 'doIt() | somePipe'},
standalone: false,
})
class DirectiveWithHostListener {}
TestBed.configureTestingModule({declarations: [MyComp, DirectiveWithHostListener]});
const template = '<div host-listener></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
expect(() => TestBed.createComponent(MyComp)).toThrowError(
/Cannot have a pipe in an action expression/,
);
});
if (getDOM().supportsDOMEvents) {
it('should support preventing default on render events', () => {
TestBed.configureTestingModule({
declarations: [
MyComp,
DirectiveListeningDomEventPrevent,
DirectiveListeningDomEventNoPrevent,
],
});
const template =
'<input type="checkbox" listenerprevent><input type="checkbox" listenernoprevent>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const dispatchedEvent = createMouseEvent('click');
const dispatchedEvent2 = createMouseEvent('click');
getDOM().dispatchEvent(fixture.debugElement.children[0].nativeElement, dispatchedEvent);
getDOM().dispatchEvent(fixture.debugElement.children[1].nativeElement, dispatchedEvent2);
expect(isPrevented(dispatchedEvent)).toBe(true);
expect(isPrevented(dispatchedEvent2)).toBe(false);
expect(fixture.debugElement.children[0].nativeElement.checked).toBeFalsy();
expect(fixture.debugElement.children[1].nativeElement.checked).toBeTruthy();
});
}
| {
"end_byte": 40477,
"start_byte": 32128,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/integration_spec.ts"
} |
angular/packages/core/test/linker/integration_spec.ts_40483_50389 | ('should support render global events from multiple directives', () => {
TestBed.configureTestingModule({
declarations: [MyComp, DirectiveListeningDomEvent, DirectiveListeningDomEventOther],
});
const template = '<div *ngIf="ctxBoolProp" listener listenerother></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const doc = TestBed.inject(DOCUMENT);
globalCounter = 0;
fixture.componentInstance.ctxBoolProp = true;
fixture.detectChanges();
const tc = fixture.debugElement.children[0];
const listener = tc.injector.get(DirectiveListeningDomEvent);
const listenerother = tc.injector.get(DirectiveListeningDomEventOther);
dispatchEvent(getDOM().getGlobalEventTarget(doc, 'window'), 'domEvent');
expect(listener.eventTypes).toEqual(['window_domEvent']);
expect(listenerother.eventType).toEqual('other_domEvent');
expect(globalCounter).toEqual(1);
fixture.componentInstance.ctxBoolProp = false;
fixture.detectChanges();
dispatchEvent(getDOM().getGlobalEventTarget(doc, 'window'), 'domEvent');
expect(globalCounter).toEqual(1);
fixture.componentInstance.ctxBoolProp = true;
fixture.detectChanges();
dispatchEvent(getDOM().getGlobalEventTarget(doc, 'window'), 'domEvent');
expect(globalCounter).toEqual(2);
// need to destroy to release all remaining global event listeners
fixture.destroy();
});
describe('ViewContainerRef', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MyComp, DynamicViewport, ChildCompUsingService],
});
TestBed.overrideComponent(MyComp, {
add: {template: '<div><dynamic-vp #dynamic></dynamic-vp></div>'},
});
});
describe('.createComponent', () => {
it('should allow to create a component at any bound location', waitForAsync(() => {
const fixture = TestBed.configureTestingModule({
schemas: [NO_ERRORS_SCHEMA],
}).createComponent(MyComp);
const tc = fixture.debugElement.children[0].children[0];
const dynamicVp: DynamicViewport = tc.injector.get(DynamicViewport);
dynamicVp.create();
fixture.detectChanges();
expect(fixture.debugElement.children[0].children[1].nativeElement).toHaveText(
'dynamic greet',
);
}));
it('should allow to create multiple components at a location', waitForAsync(() => {
const fixture = TestBed.configureTestingModule({
schemas: [NO_ERRORS_SCHEMA],
}).createComponent(MyComp);
const tc = fixture.debugElement.children[0].children[0];
const dynamicVp: DynamicViewport = tc.injector.get(DynamicViewport);
dynamicVp.create();
dynamicVp.create();
fixture.detectChanges();
expect(fixture.debugElement.children[0].children[1].nativeElement).toHaveText(
'dynamic greet',
);
expect(fixture.debugElement.children[0].children[2].nativeElement).toHaveText(
'dynamic greet',
);
}));
it('should create a component that has been freshly compiled', () => {
@Component({
template: '',
standalone: false,
})
class RootComp {
constructor(public vc: ViewContainerRef) {}
}
@NgModule({
declarations: [RootComp],
providers: [{provide: 'someToken', useValue: 'someRootValue'}],
})
class RootModule {}
@Component({
template: '',
standalone: false,
})
class MyComp {
constructor(@Inject('someToken') public someToken: string) {}
}
@NgModule({
declarations: [MyComp],
providers: [{provide: 'someToken', useValue: 'someValue'}],
})
class MyModule {}
const compFixture = TestBed.configureTestingModule({
imports: [RootModule],
}).createComponent(RootComp);
const compiler = TestBed.inject(Compiler);
const myCompFactory = <ComponentFactory<MyComp>>(
compiler.compileModuleAndAllComponentsSync(MyModule).componentFactories[0]
);
// Note: the ComponentFactory was created directly via the compiler, i.e. it
// does not have an association to an NgModuleRef.
// -> expect the providers of the module that the view container belongs to.
const compRef = compFixture.componentInstance.vc.createComponent(myCompFactory);
expect(compRef.instance.someToken).toBe('someRootValue');
});
it('should create a component with the passed NgModuleRef', () => {
@Component({
template: '',
standalone: false,
})
class RootComp {
constructor(public vc: ViewContainerRef) {}
}
@Component({
template: '',
standalone: false,
})
class MyComp {
constructor(@Inject('someToken') public someToken: string) {}
}
@NgModule({
declarations: [RootComp, MyComp],
providers: [{provide: 'someToken', useValue: 'someRootValue'}],
})
class RootModule {}
@NgModule({providers: [{provide: 'someToken', useValue: 'someValue'}]})
class MyModule {}
const compFixture = TestBed.configureTestingModule({
imports: [RootModule],
}).createComponent(RootComp);
const compiler = TestBed.inject(Compiler);
const myModule = compiler
.compileModuleSync(MyModule)
.create(TestBed.inject(NgModuleRef).injector);
// Note: MyComp was declared as entryComponent in the RootModule,
// but we pass MyModule to the createComponent call.
// -> expect the providers of MyModule!
const compRef = compFixture.componentInstance.vc.createComponent(MyComp, {
ngModuleRef: myModule,
});
expect(compRef.instance.someToken).toBe('someValue');
});
it('should create a component with the NgModuleRef of the ComponentFactoryResolver', () => {
@Component({
template: '',
standalone: false,
})
class RootComp {
constructor(public vc: ViewContainerRef) {}
}
@NgModule({
declarations: [RootComp],
providers: [{provide: 'someToken', useValue: 'someRootValue'}],
})
class RootModule {}
@Component({
template: '',
standalone: false,
})
class MyComp {
constructor(@Inject('someToken') public someToken: string) {}
}
@NgModule({
declarations: [MyComp],
providers: [{provide: 'someToken', useValue: 'someValue'}],
})
class MyModule {}
const compFixture = TestBed.configureTestingModule({
imports: [RootModule],
}).createComponent(RootComp);
const compiler = TestBed.inject(Compiler);
const myModule = compiler
.compileModuleSync(MyModule)
.create(TestBed.inject(NgModuleRef).injector);
const myCompFactory = myModule.componentFactoryResolver.resolveComponentFactory(MyComp);
// Note: MyComp was declared as entryComponent in MyModule,
// and we don't pass an explicit ModuleRef to the createComponent call.
// -> expect the providers of MyModule!
const compRef = compFixture.componentInstance.vc.createComponent(myCompFactory);
expect(compRef.instance.someToken).toBe('someValue');
});
});
describe('.insert', () => {
it('should throw with destroyed views', waitForAsync(() => {
const fixture = TestBed.configureTestingModule({
schemas: [NO_ERRORS_SCHEMA],
}).createComponent(MyComp);
const tc = fixture.debugElement.children[0].children[0];
const dynamicVp: DynamicViewport = tc.injector.get(DynamicViewport);
const ref = dynamicVp.create();
fixture.detectChanges();
ref.destroy();
expect(() => {
dynamicVp.insert(ref.hostView);
}).toThrowError('Cannot insert a destroyed View in a ViewContainer!');
}));
});
describe('.move', () => {
it('should throw with destroyed views', waitForAsync(() => {
const fixture = TestBed.configureTestingModule({
schemas: [NO_ERRORS_SCHEMA],
}).createComponent(MyComp);
const tc = fixture.debugElement.children[0].children[0];
const dynamicVp: DynamicViewport = tc.injector.get(DynamicViewport);
const ref = dynamicVp.create();
fixture.detectChanges();
ref.destroy();
expect(() => {
dynamicVp.move(ref.hostView, 1);
}).toThrowError('Cannot move a destroyed View in a ViewContainer!');
}));
});
});
it('should support static attributes', () => {
TestBed.configureTestingModule({declarations: [MyComp, NeedsAttribute]});
const template = '<input static type="text" title>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const tc = fixture.debugElement.children[0];
const needsAttribute = tc.injector.get(NeedsAttribute);
expect(needsAttribute.typeAttribute).toEqual('text');
expect(needsAttribute.staticAttribute).toEqual('');
expect(needsAttribute.fooAttribute).toBeNull();
});
| {
"end_byte": 50389,
"start_byte": 40483,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/integration_spec.ts"
} |
angular/packages/core/test/linker/integration_spec.ts_50395_60324 | ('should support custom interpolation', () => {
TestBed.configureTestingModule({
declarations: [
MyComp,
ComponentWithCustomInterpolationA,
ComponentWithCustomInterpolationB,
ComponentWithDefaultInterpolation,
],
});
const template = `<div>{{ctxProp}}</div>
<cmp-with-custom-interpolation-a></cmp-with-custom-interpolation-a>
<cmp-with-custom-interpolation-b></cmp-with-custom-interpolation-b>`;
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = 'Default Interpolation';
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText(
'Default InterpolationCustom Interpolation ACustom Interpolation B (Default Interpolation)',
);
});
});
describe('dependency injection', () => {
it('should support bindings', () => {
TestBed.configureTestingModule({
declarations: [MyComp, DirectiveProvidingInjectable, DirectiveConsumingInjectable],
schemas: [NO_ERRORS_SCHEMA],
});
const template = `
<directive-providing-injectable >
<directive-consuming-injectable #consuming>
</directive-consuming-injectable>
</directive-providing-injectable>
`;
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const comp = fixture.debugElement.children[0].children[0].references['consuming'];
expect(comp.injectable).toBeInstanceOf(InjectableService);
});
it('should support viewProviders', () => {
TestBed.configureTestingModule({
declarations: [MyComp, DirectiveProvidingInjectableInView, DirectiveConsumingInjectable],
schemas: [NO_ERRORS_SCHEMA],
});
const template = `
<directive-consuming-injectable #consuming>
</directive-consuming-injectable>
`;
TestBed.overrideComponent(DirectiveProvidingInjectableInView, {set: {template}});
const fixture = TestBed.createComponent(DirectiveProvidingInjectableInView);
const comp = fixture.debugElement.children[0].references['consuming'];
expect(comp.injectable).toBeInstanceOf(InjectableService);
});
it('should support unbounded lookup', () => {
TestBed.configureTestingModule({
declarations: [
MyComp,
DirectiveProvidingInjectable,
DirectiveContainingDirectiveConsumingAnInjectable,
DirectiveConsumingInjectableUnbounded,
],
schemas: [NO_ERRORS_SCHEMA],
});
const template = `
<directive-providing-injectable>
<directive-containing-directive-consuming-an-injectable #dir>
</directive-containing-directive-consuming-an-injectable>
</directive-providing-injectable>
`;
TestBed.overrideComponent(MyComp, {set: {template}});
TestBed.overrideComponent(DirectiveContainingDirectiveConsumingAnInjectable, {
set: {
template: `
<directive-consuming-injectable-unbounded></directive-consuming-injectable-unbounded>
`,
},
});
const fixture = TestBed.createComponent(MyComp);
const comp = fixture.debugElement.children[0].children[0].references['dir'];
expect(comp.directive.injectable).toBeInstanceOf(InjectableService);
});
it('should support the event-bus scenario', () => {
TestBed.configureTestingModule({
declarations: [
MyComp,
GrandParentProvidingEventBus,
ParentProvidingEventBus,
ChildConsumingEventBus,
],
schemas: [NO_ERRORS_SCHEMA],
});
const template = `
<grand-parent-providing-event-bus>
<parent-providing-event-bus>
<child-consuming-event-bus>
</child-consuming-event-bus>
</parent-providing-event-bus>
</grand-parent-providing-event-bus>
`;
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const gpComp = fixture.debugElement.children[0];
const parentComp = gpComp.children[0];
const childComp = parentComp.children[0];
const grandParent = gpComp.injector.get(GrandParentProvidingEventBus);
const parent = parentComp.injector.get(ParentProvidingEventBus);
const child = childComp.injector.get(ChildConsumingEventBus);
expect(grandParent.bus.name).toEqual('grandparent');
expect(parent.bus.name).toEqual('parent');
expect(parent.grandParentBus).toBe(grandParent.bus);
expect(child.bus).toBe(parent.bus);
});
it('should instantiate bindings lazily', () => {
TestBed.configureTestingModule({
declarations: [MyComp, DirectiveConsumingInjectable, ComponentProvidingLoggingInjectable],
schemas: [NO_ERRORS_SCHEMA],
});
const template = `
<component-providing-logging-injectable #providing>
<directive-consuming-injectable *ngIf="ctxBoolProp">
</directive-consuming-injectable>
</component-providing-logging-injectable>
`;
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const providing = fixture.debugElement.children[0].references['providing'];
expect(providing.created).toBe(false);
fixture.componentInstance.ctxBoolProp = true;
fixture.detectChanges();
expect(providing.created).toBe(true);
});
});
describe('corner cases', () => {
it('should remove script tags from templates', () => {
TestBed.configureTestingModule({declarations: [MyComp]});
const template = `
<script>alert("Ooops");</script>
<div>before<script>alert("Ooops");</script><span>inside</span>after</div>`;
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
expect(fixture.nativeElement.querySelectorAll('script').length).toEqual(0);
});
it('should throw when using directives without selector in NgModule declarations', () => {
@Directive({
standalone: false,
})
class SomeDirective {}
@Component({
selector: 'comp',
template: '',
standalone: false,
})
class SomeComponent {}
TestBed.configureTestingModule({declarations: [MyComp, SomeDirective, SomeComponent]});
expect(() => TestBed.createComponent(MyComp)).toThrowError(
`Directive ${stringify(SomeDirective)} has no selector, please add it!`,
);
});
it('should not throw when using directives without selector as base class not in declarations', () => {
@Directive({
standalone: false,
})
abstract class Base {
constructor(readonly injector: Injector) {}
}
@Directive()
abstract class EmptyDir {}
@Directive({
inputs: ['a', 'b'],
standalone: false,
})
class TestDirWithInputs {}
@Component({
selector: 'comp',
template: '',
standalone: false,
})
class SomeComponent extends Base {}
@Component({
selector: 'comp2',
template: '',
standalone: false,
})
class SomeComponent2 extends EmptyDir {}
@Component({
selector: 'comp3',
template: '',
standalone: false,
})
class SomeComponent3 extends TestDirWithInputs {}
TestBed.configureTestingModule({
declarations: [MyComp, SomeComponent, SomeComponent2, SomeComponent3],
});
expect(() => TestBed.createComponent(MyComp)).not.toThrowError();
});
it('should throw when using directives with empty string selector', () => {
@Directive({
selector: '',
standalone: false,
})
class SomeDirective {}
@Component({
selector: 'comp',
template: '',
standalone: false,
})
class SomeComponent {}
TestBed.configureTestingModule({declarations: [MyComp, SomeDirective, SomeComponent]});
expect(() => TestBed.createComponent(MyComp)).toThrowError(
`Directive ${stringify(SomeDirective)} has no selector, please add it!`,
);
});
it('should use a default element name for components without selectors', () => {
@Component({
template: '----',
standalone: false,
})
class NoSelectorComponent {}
expect(reflectComponentType(NoSelectorComponent)?.selector).toBe('ng-component');
expect(
createComponent(NoSelectorComponent, {
environmentInjector: TestBed.inject(EnvironmentInjector),
}).location.nativeElement.nodeName.toLowerCase(),
).toEqual('ng-component');
});
});
describe('error handling', () => {
it('should report a meaningful error when a directive is missing annotation', () => {
TestBed.configureTestingModule({declarations: [MyComp, SomeDirectiveMissingAnnotation]});
expect(() => TestBed.createComponent(MyComp)).toThrowError(
`Unexpected value '${stringify(
SomeDirectiveMissingAnnotation,
)}' declared by the module 'DynamicTestModule'. Please add a @Pipe/@Directive/@Component annotation.`,
);
});
it('should report a meaningful error when a component is missing view annotation', () => {
TestBed.configureTestingModule({declarations: [MyComp, ComponentWithoutView]});
try {
TestBed.createComponent(ComponentWithoutView);
} catch (e) {
expect((e as Error).message).toContain(
`No template specified for component ${stringify(ComponentWithoutView)}`,
);
}
});
});
| {
"end_byte": 60324,
"start_byte": 50395,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/integration_spec.ts"
} |
angular/packages/core/test/linker/integration_spec.ts_60328_68755 | ('should support imperative views', () => {
TestBed.configureTestingModule({declarations: [MyComp, SimpleImperativeViewComponent]});
const template = '<simple-imp-cmp></simple-imp-cmp>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
expect(fixture.nativeElement).toHaveText('hello imp view');
});
it('should support moving embedded views around', () => {
TestBed.configureTestingModule({
declarations: [MyComp, SomeImperativeViewport],
providers: [{provide: ANCHOR_ELEMENT, useValue: el('<div></div>')}],
});
const template = '<div><div *someImpvp="ctxBoolProp">hello</div></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const anchorElement = getTestBed().get(ANCHOR_ELEMENT);
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(anchorElement).toHaveText('');
fixture.componentInstance.ctxBoolProp = true;
fixture.detectChanges();
expect(anchorElement).toHaveText('hello');
fixture.componentInstance.ctxBoolProp = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('');
});
describe('moving embedded views of projectable nodes in a dynamic component', () => {
@Component({
selector: 'menu-item',
template: '',
standalone: false,
})
class DynamicMenuItem {
@ViewChild('templateRef', {static: true}) templateRef!: TemplateRef<any>;
itemContent: string | undefined;
}
@Component({
selector: 'test',
template: `<ng-container #menuItemsContainer></ng-container>`,
standalone: false,
})
class TestCmp {
constructor(public cfr: ComponentFactoryResolver) {}
@ViewChild('menuItemsContainer', {static: true, read: ViewContainerRef})
menuItemsContainer!: ViewContainerRef;
}
beforeEach(() => {
TestBed.configureTestingModule({declarations: [TestCmp, DynamicMenuItem]});
});
const createElWithContent = (content: string, tagName = 'span') => {
const element = document.createElement(tagName);
element.textContent = content;
return element;
};
it('should support moving embedded views of projectable nodes', () => {
TestBed.overrideTemplate(
DynamicMenuItem,
`<ng-template #templateRef><ng-content></ng-content></ng-template>`,
);
const fixture = TestBed.createComponent(TestCmp);
const menuItemsContainer = fixture.componentInstance.menuItemsContainer;
const dynamicCmptFactory =
fixture.componentInstance.cfr.resolveComponentFactory(DynamicMenuItem);
const cmptRefWithAa = dynamicCmptFactory.create(Injector.NULL, [[createElWithContent('Aa')]]);
const cmptRefWithBb = dynamicCmptFactory.create(Injector.NULL, [[createElWithContent('Bb')]]);
const cmptRefWithCc = dynamicCmptFactory.create(Injector.NULL, [[createElWithContent('Cc')]]);
menuItemsContainer.insert(cmptRefWithAa.instance.templateRef.createEmbeddedView({}));
menuItemsContainer.insert(cmptRefWithBb.instance.templateRef.createEmbeddedView({}));
menuItemsContainer.insert(cmptRefWithCc.instance.templateRef.createEmbeddedView({}));
menuItemsContainer.move(menuItemsContainer.get(0)!, 1);
expect(fixture.nativeElement.textContent).toBe('BbAaCc');
menuItemsContainer.move(menuItemsContainer.get(2)!, 1);
expect(fixture.nativeElement.textContent).toBe('BbCcAa');
});
it('should support moving embedded views of projectable nodes in multiple slots', () => {
TestBed.overrideTemplate(
DynamicMenuItem,
`<ng-template #templateRef><ng-content select="span"></ng-content><ng-content select="button"></ng-content></ng-template>`,
);
const fixture = TestBed.createComponent(TestCmp);
const menuItemsContainer = fixture.componentInstance.menuItemsContainer;
const dynamicCmptFactory =
fixture.componentInstance.cfr.resolveComponentFactory(DynamicMenuItem);
const cmptRefWithAa = dynamicCmptFactory.create(Injector.NULL, [
[createElWithContent('A')],
[createElWithContent('a', 'button')],
]);
const cmptRefWithBb = dynamicCmptFactory.create(Injector.NULL, [
[createElWithContent('B')],
[createElWithContent('b', 'button')],
]);
const cmptRefWithCc = dynamicCmptFactory.create(Injector.NULL, [
[createElWithContent('C')],
[createElWithContent('c', 'button')],
]);
menuItemsContainer.insert(cmptRefWithAa.instance.templateRef.createEmbeddedView({}));
menuItemsContainer.insert(cmptRefWithBb.instance.templateRef.createEmbeddedView({}));
menuItemsContainer.insert(cmptRefWithCc.instance.templateRef.createEmbeddedView({}));
menuItemsContainer.move(menuItemsContainer.get(0)!, 1);
expect(fixture.nativeElement.textContent).toBe('BbAaCc');
menuItemsContainer.move(menuItemsContainer.get(2)!, 1);
expect(fixture.nativeElement.textContent).toBe('BbCcAa');
});
it('should support moving embedded views of projectable nodes in multiple slots and interpolations', () => {
TestBed.overrideTemplate(
DynamicMenuItem,
`<ng-template #templateRef><ng-content select="span"></ng-content>{{itemContent}}<ng-content select="button"></ng-content></ng-template>`,
);
TestBed.configureTestingModule({declarations: [TestCmp, DynamicMenuItem]});
const fixture = TestBed.createComponent(TestCmp);
const menuItemsContainer = fixture.componentInstance.menuItemsContainer;
const dynamicCmptFactory =
fixture.componentInstance.cfr.resolveComponentFactory(DynamicMenuItem);
const cmptRefWithAa = dynamicCmptFactory.create(Injector.NULL, [
[createElWithContent('A')],
[createElWithContent('a', 'button')],
]);
const cmptRefWithBb = dynamicCmptFactory.create(Injector.NULL, [
[createElWithContent('B')],
[createElWithContent('b', 'button')],
]);
const cmptRefWithCc = dynamicCmptFactory.create(Injector.NULL, [
[createElWithContent('C')],
[createElWithContent('c', 'button')],
]);
menuItemsContainer.insert(cmptRefWithAa.instance.templateRef.createEmbeddedView({}));
menuItemsContainer.insert(cmptRefWithBb.instance.templateRef.createEmbeddedView({}));
menuItemsContainer.insert(cmptRefWithCc.instance.templateRef.createEmbeddedView({}));
cmptRefWithAa.instance.itemContent = '0';
cmptRefWithBb.instance.itemContent = '1';
cmptRefWithCc.instance.itemContent = '2';
fixture.detectChanges();
menuItemsContainer.move(menuItemsContainer.get(0)!, 1);
expect(fixture.nativeElement.textContent).toBe('B1bA0aC2c');
menuItemsContainer.move(menuItemsContainer.get(2)!, 1);
expect(fixture.nativeElement.textContent).toBe('B1bC2cA0a');
});
it('should support moving embedded views with empty projectable slots', () => {
TestBed.overrideTemplate(
DynamicMenuItem,
`<ng-template #templateRef><ng-content></ng-content></ng-template>`,
);
const fixture = TestBed.createComponent(TestCmp);
const menuItemsContainer = fixture.componentInstance.menuItemsContainer;
const dynamicCmptFactory =
fixture.componentInstance.cfr.resolveComponentFactory(DynamicMenuItem);
const cmptRefWithAa = dynamicCmptFactory.create(Injector.NULL, [[]]);
const cmptRefWithBb = dynamicCmptFactory.create(Injector.NULL, [[createElWithContent('Bb')]]);
const cmptRefWithCc = dynamicCmptFactory.create(Injector.NULL, [[createElWithContent('Cc')]]);
menuItemsContainer.insert(cmptRefWithAa.instance.templateRef.createEmbeddedView({}));
menuItemsContainer.insert(cmptRefWithBb.instance.templateRef.createEmbeddedView({}));
menuItemsContainer.insert(cmptRefWithCc.instance.templateRef.createEmbeddedView({}));
menuItemsContainer.move(menuItemsContainer.get(0)!, 1); // [ Bb, NULL, Cc]
expect(fixture.nativeElement.textContent).toBe('BbCc');
menuItemsContainer.move(menuItemsContainer.get(2)!, 1); // [ Bb, Cc, NULL]
expect(fixture.nativeElement.textContent).toBe('BbCc');
menuItemsContainer.move(menuItemsContainer.get(0)!, 1); // [ Cc, Bb, NULL]
expect(fixture.nativeElement.textContent).toBe('CcBb');
});
});
| {
"end_byte": 68755,
"start_byte": 60328,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/integration_spec.ts"
} |
angular/packages/core/test/linker/integration_spec.ts_68759_78238 | scribe('Property bindings', () => {
it('should throw on bindings to unknown properties', () => {
TestBed.configureTestingModule({declarations: [MyComp]});
const template = '<div unknown="{{ctxProp}}"></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const spy = spyOn(console, 'error');
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(spy.calls.mostRecent().args[0]).toMatch(
/Can't bind to 'unknown' since it isn't a known property of 'div'./,
);
});
it('should throw on bindings to unknown properties', () => {
TestBed.configureTestingModule({imports: [CommonModule], declarations: [MyComp]});
const template = '<div *ngFor="let item in ctxArrProp">{{item}}</div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const spy = spyOn(console, 'error');
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(spy.calls.mostRecent().args[0]).toMatch(
/Can't bind to 'ngForIn' since it isn't a known property of 'div'./,
);
});
it('should not throw for property binding to a non-existing property when there is a matching directive property', () => {
TestBed.configureTestingModule({declarations: [MyComp, MyDir]});
const template = '<div my-dir [elprop]="ctxProp"></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
expect(() => TestBed.createComponent(MyComp)).not.toThrow();
});
it('should not be created when there is a directive with the same property', () => {
TestBed.configureTestingModule({declarations: [MyComp, DirectiveWithTitle]});
const template = '<span [title]="ctxProp"></span>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = 'TITLE';
fixture.detectChanges();
const el = fixture.nativeElement.querySelector('span');
expect(el.title).toBeFalsy();
});
it('should work when a directive uses hostProperty to update the DOM element', () => {
TestBed.configureTestingModule({declarations: [MyComp, DirectiveWithTitleAndHostProperty]});
const template = '<span [title]="ctxProp"></span>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = 'TITLE';
fixture.detectChanges();
const el = fixture.nativeElement.querySelector('span');
expect(el.title).toEqual('TITLE');
});
});
describe('logging property updates', () => {
it('should reflect property values as attributes', () => {
TestBed.configureTestingModule({declarations: [MyComp, MyDir]});
TestBed.overrideComponent(MyComp, {set: {template: `<div my-dir [elprop]="ctxProp"></div>`}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = 'hello';
fixture.detectChanges();
const html = fixture.nativeElement.innerHTML;
expect(html).toContain('ng-reflect-dir-prop="hello"');
});
it('should reflect property values on unbound inputs', () => {
TestBed.configureTestingModule({declarations: [MyComp, MyDir]});
TestBed.overrideComponent(MyComp, {
set: {template: `<div my-dir elprop="hello" title="Reflect test"></div>`},
});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const html = fixture.nativeElement.innerHTML;
expect(html).toContain('ng-reflect-dir-prop="hello"');
expect(html).not.toContain('ng-reflect-title');
});
it(`should work with prop names containing '$'`, () => {
TestBed.configureTestingModule({declarations: [ParentCmp, SomeCmpWithInput]});
const fixture = TestBed.createComponent(ParentCmp);
fixture.detectChanges();
const html = fixture.nativeElement.innerHTML;
expect(html).toContain('ng-reflect-test_="hello"');
});
it('should reflect property values on template comments', () => {
const fixture = TestBed.configureTestingModule({declarations: [MyComp]})
.overrideComponent(MyComp, {
set: {template: `<ng-template [ngIf]="ctxBoolProp"></ng-template>`},
})
.createComponent(MyComp);
fixture.componentInstance.ctxBoolProp = true;
fixture.detectChanges();
const html = fixture.nativeElement.innerHTML;
expect(html).toContain('"ng-reflect-ng-if": "true"');
});
it('should reflect property values on ng-containers', () => {
const fixture = TestBed.configureTestingModule({declarations: [MyComp]})
.overrideComponent(MyComp, {
set: {template: `<ng-container *ngIf="ctxBoolProp">content</ng-container>`},
})
.createComponent(MyComp);
fixture.componentInstance.ctxBoolProp = true;
fixture.detectChanges();
const html = fixture.nativeElement.innerHTML;
expect(html).toContain('"ng-reflect-ng-if": "true"');
});
it('should reflect property values of multiple directive bound to the same input name', () => {
TestBed.configureTestingModule({declarations: [MyComp, MyDir, MyDir2]});
TestBed.overrideComponent(MyComp, {
set: {template: `<div my-dir my-dir2 [elprop]="ctxProp"></div>`},
});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = 'hello';
fixture.detectChanges();
const html = fixture.nativeElement.innerHTML;
expect(html).toContain('ng-reflect-dir-prop="hello"');
expect(html).toContain('ng-reflect-dir-prop2="hello"');
});
it('should indicate when toString() throws', () => {
TestBed.configureTestingModule({declarations: [MyComp, MyDir]});
const template = '<div my-dir [elprop]="toStringThrow"></div>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toContain('[ERROR]');
});
it('should not reflect undefined values', () => {
TestBed.configureTestingModule({declarations: [MyComp, MyDir, MyDir2]});
TestBed.overrideComponent(MyComp, {set: {template: `<div my-dir [elprop]="ctxProp"></div>`}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = 'hello';
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toContain('ng-reflect-dir-prop="hello"');
fixture.componentInstance.ctxProp = undefined!;
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).not.toContain('ng-reflect-');
});
it('should not reflect null values', () => {
TestBed.configureTestingModule({declarations: [MyComp, MyDir, MyDir2]});
TestBed.overrideComponent(MyComp, {set: {template: `<div my-dir [elprop]="ctxProp"></div>`}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = 'hello';
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toContain('ng-reflect-dir-prop="hello"');
fixture.componentInstance.ctxProp = null!;
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).not.toContain('ng-reflect-');
});
it('should reflect empty strings', () => {
TestBed.configureTestingModule({declarations: [MyComp, MyDir, MyDir2]});
TestBed.overrideComponent(MyComp, {set: {template: `<div my-dir [elprop]="ctxProp"></div>`}});
const fixture = TestBed.createComponent(MyComp);
fixture.componentInstance.ctxProp = '';
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toContain('ng-reflect-dir-prop=""');
});
it('should not reflect in comment nodes when the value changes to undefined', () => {
const fixture = TestBed.configureTestingModule({declarations: [MyComp]})
.overrideComponent(MyComp, {
set: {template: `<ng-template [ngIf]="ctxBoolProp"></ng-template>`},
})
.createComponent(MyComp);
fixture.componentInstance.ctxBoolProp = true;
fixture.detectChanges();
let html = fixture.nativeElement.innerHTML;
expect(html).toContain('bindings={');
expect(html).toContain('"ng-reflect-ng-if": "true"');
fixture.componentInstance.ctxBoolProp = undefined!;
fixture.detectChanges();
html = fixture.nativeElement.innerHTML;
expect(html).toContain('bindings={');
expect(html).not.toContain('ng-reflect');
});
it('should reflect in comment nodes when the value changes to null', () => {
const fixture = TestBed.configureTestingModule({declarations: [MyComp]})
.overrideComponent(MyComp, {
set: {template: `<ng-template [ngIf]="ctxBoolProp"></ng-template>`},
})
.createComponent(MyComp);
fixture.componentInstance.ctxBoolProp = true;
fixture.detectChanges();
let html = fixture.nativeElement.innerHTML;
expect(html).toContain('bindings={');
expect(html).toContain('"ng-reflect-ng-if": "true"');
fixture.componentInstance.ctxBoolProp = null!;
fixture.detectChanges();
html = fixture.nativeElement.innerHTML;
expect(html).toContain('bindings={');
expect(html).toContain('"ng-reflect-ng-if": null');
});
});
| {
"end_byte": 78238,
"start_byte": 68759,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/integration_spec.ts"
} |
angular/packages/core/test/linker/integration_spec.ts_78242_87360 | scribe('property decorators', () => {
it('should support property decorators', () => {
TestBed.configureTestingModule({
declarations: [MyComp, DirectiveWithPropDecorators],
schemas: [NO_ERRORS_SCHEMA],
});
const template = '<with-prop-decorators elProp="aaa"></with-prop-decorators>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const dir = fixture.debugElement.children[0].injector.get(DirectiveWithPropDecorators);
expect(dir.dirProp).toEqual('aaa');
});
it('should support host binding decorators', () => {
TestBed.configureTestingModule({
declarations: [MyComp, DirectiveWithPropDecorators],
schemas: [NO_ERRORS_SCHEMA],
});
const template = '<with-prop-decorators></with-prop-decorators>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const dir = fixture.debugElement.children[0].injector.get(DirectiveWithPropDecorators);
dir.myAttr = 'aaa';
fixture.detectChanges();
expect(fixture.debugElement.children[0].nativeElement.outerHTML).toContain('my-attr="aaa"');
});
if (getDOM().supportsDOMEvents) {
it('should support event decorators', fakeAsync(() => {
TestBed.configureTestingModule({
declarations: [MyComp, DirectiveWithPropDecorators],
schemas: [NO_ERRORS_SCHEMA],
});
const template = `<with-prop-decorators (elEvent)="ctxProp='called'">`;
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
tick();
const emitter = fixture.debugElement.children[0].injector.get(DirectiveWithPropDecorators);
emitter.fireEvent('fired !');
tick();
expect(fixture.componentInstance.ctxProp).toEqual('called');
}));
it('should support host listener decorators', () => {
TestBed.configureTestingModule({
declarations: [MyComp, DirectiveWithPropDecorators],
schemas: [NO_ERRORS_SCHEMA],
});
const template = '<with-prop-decorators></with-prop-decorators>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const dir = fixture.debugElement.children[0].injector.get(DirectiveWithPropDecorators);
const native = fixture.debugElement.children[0].nativeElement;
getDOM().dispatchEvent(native, createMouseEvent('click'));
expect(dir.target).toBe(native);
});
}
it('should support defining views in the component decorator', () => {
TestBed.configureTestingModule({
declarations: [MyComp, ComponentWithTemplate],
imports: [CommonModule],
schemas: [NO_ERRORS_SCHEMA],
});
const template = '<component-with-template></component-with-template>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const native = fixture.debugElement.children[0].nativeElement;
expect(native).toHaveText('No View Decorator: 123');
});
});
describe('whitespaces in templates', () => {
it('should not remove whitespaces by default', waitForAsync(() => {
@Component({
selector: 'comp',
template: '<span>foo</span> <span>bar</span>',
standalone: false,
})
class MyCmp {}
const f = TestBed.configureTestingModule({declarations: [MyCmp]}).createComponent(MyCmp);
f.detectChanges();
expect(f.nativeElement.childNodes.length).toBe(2);
}));
it('should not remove whitespaces when explicitly requested not to do so', waitForAsync(() => {
@Component({
selector: 'comp',
template: '<span>foo</span> <span>bar</span>',
preserveWhitespaces: true,
standalone: false,
})
class MyCmp {}
const f = TestBed.configureTestingModule({declarations: [MyCmp]}).createComponent(MyCmp);
f.detectChanges();
expect(f.nativeElement.childNodes.length).toBe(3);
}));
it('should remove whitespaces when explicitly requested to do so', waitForAsync(() => {
@Component({
selector: 'comp',
template: '<span>foo</span> <span>bar</span>',
preserveWhitespaces: false,
standalone: false,
})
class MyCmp {}
const f = TestBed.configureTestingModule({declarations: [MyCmp]}).createComponent(MyCmp);
f.detectChanges();
expect(f.nativeElement.childNodes.length).toBe(2);
}));
});
describe('orphan components', () => {
it('should display correct error message for orphan component if forbidOrphanRendering option is set', () => {
@Component({
template: '...',
standalone: false,
})
class MainComp {}
ɵsetClassDebugInfo(MainComp, {
className: 'MainComp',
filePath: 'test.ts',
lineNumber: 11,
forbidOrphanRendering: true,
});
TestBed.configureTestingModule({declarations: [MainComp]});
expect(() => TestBed.createComponent(MainComp)).toThrowError(
/^NG0981: Orphan component found\! Trying to render the component MainComp \(at test\.ts:11\) without first loading the NgModule that declares it/,
);
});
it('should not throw error for orphan component if forbidOrphanRendering option is not set', () => {
@Component({
template: '...',
standalone: false,
})
class MainComp {}
ɵsetClassDebugInfo(MainComp, {
className: 'MainComp',
filePath: 'test.ts',
lineNumber: 11,
});
TestBed.configureTestingModule({declarations: [MainComp]});
expect(() => TestBed.createComponent(MainComp)).not.toThrow();
});
});
if (getDOM().supportsDOMEvents) {
describe('svg', () => {
it('should support svg elements', () => {
TestBed.configureTestingModule({declarations: [MyComp]});
const template = '<svg><use xlink:href="Port" /></svg>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const el = fixture.nativeElement;
const svg = el.childNodes[0];
const use = svg.childNodes[0];
expect(svg.namespaceURI).toEqual('http://www.w3.org/2000/svg');
expect(use.namespaceURI).toEqual('http://www.w3.org/2000/svg');
const firstAttribute = use.attributes[0];
expect(firstAttribute.name).toEqual('xlink:href');
expect(firstAttribute.namespaceURI).toEqual('http://www.w3.org/1999/xlink');
});
it('should support foreignObjects with document fragments', () => {
TestBed.configureTestingModule({declarations: [MyComp]});
const template =
'<svg><foreignObject><xhtml:div><p>Test</p></xhtml:div></foreignObject></svg>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
const el = fixture.nativeElement;
const svg = el.childNodes[0];
const foreignObject = svg.childNodes[0];
const p = foreignObject.childNodes[0];
expect(svg.namespaceURI).toEqual('http://www.w3.org/2000/svg');
expect(foreignObject.namespaceURI).toEqual('http://www.w3.org/2000/svg');
expect(p.namespaceURI).toEqual('http://www.w3.org/1999/xhtml');
});
});
describe('attributes', () => {
it('should support attributes with namespace', () => {
TestBed.configureTestingModule({declarations: [MyComp, SomeCmp]});
const template = '<svg:use xlink:href="#id" />';
TestBed.overrideComponent(SomeCmp, {set: {template}});
const fixture = TestBed.createComponent(SomeCmp);
const useEl = fixture.nativeElement.firstChild;
expect(useEl.getAttributeNS('http://www.w3.org/1999/xlink', 'href')).toEqual('#id');
});
it('should support binding to attributes with namespace', () => {
TestBed.configureTestingModule({declarations: [MyComp, SomeCmp]});
const template = '<svg:use [attr.xlink:href]="value" />';
TestBed.overrideComponent(SomeCmp, {set: {template}});
const fixture = TestBed.createComponent(SomeCmp);
const cmp = fixture.componentInstance;
const useEl = fixture.nativeElement.firstChild;
cmp.value = '#id';
fixture.detectChanges();
expect(useEl.getAttributeNS('http://www.w3.org/1999/xlink', 'href')).toEqual('#id');
cmp.value = null;
fixture.detectChanges();
expect(useEl.hasAttributeNS('http://www.w3.org/1999/xlink', 'href')).toEqual(false);
});
});
}
});
@Component({
selector: 'cmp-with-default-interpolation',
template: `{{text}}`,
standalone: false,
})
class ComponentWithDefaultInterpolation {
text = 'Default Interpolation';
}
@C | {
"end_byte": 87360,
"start_byte": 78242,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/integration_spec.ts"
} |
angular/packages/core/test/linker/integration_spec.ts_87362_94946 | ponent({
selector: 'cmp-with-custom-interpolation-a',
template: `<div>{%text%}</div>`,
interpolation: ['{%', '%}'],
standalone: false,
})
class ComponentWithCustomInterpolationA {
text = 'Custom Interpolation A';
}
@Component({
selector: 'cmp-with-custom-interpolation-b',
template: `<div>{**text%}</div> (<cmp-with-default-interpolation></cmp-with-default-interpolation>)`,
interpolation: ['{**', '%}'],
standalone: false,
})
class ComponentWithCustomInterpolationB {
text = 'Custom Interpolation B';
}
@Injectable()
class MyService {
greeting: string;
constructor() {
this.greeting = 'hello';
}
}
@Component({
selector: 'simple-imp-cmp',
template: '',
standalone: false,
})
class SimpleImperativeViewComponent {
done: any;
constructor(self: ElementRef) {
const hostElement = self.nativeElement;
hostElement.appendChild(el('hello imp view'));
}
}
@Directive({
selector: 'dynamic-vp',
standalone: false,
})
class DynamicViewport {
private injector: Injector;
constructor(private vc: ViewContainerRef) {
const myService = new MyService();
myService.greeting = 'dynamic greet';
this.injector = Injector.create({
providers: [{provide: MyService, useValue: myService}],
parent: vc.injector,
});
}
create(): ComponentRef<ChildCompUsingService> {
return this.vc.createComponent(ChildCompUsingService, {
index: this.vc.length,
injector: this.injector,
});
}
insert(viewRef: ViewRef, index?: number): ViewRef {
return this.vc.insert(viewRef, index);
}
move(viewRef: ViewRef, currentIndex: number): ViewRef {
return this.vc.move(viewRef, currentIndex);
}
}
@Directive({
selector: '[my-dir]',
inputs: ['dirProp: elprop'],
exportAs: 'mydir',
standalone: false,
})
class MyDir {
dirProp: string;
constructor() {
this.dirProp = '';
}
}
@Directive({
selector: '[my-dir2]',
inputs: ['dirProp2: elprop'],
exportAs: 'mydir2',
standalone: false,
})
class MyDir2 {
dirProp2: string;
constructor() {
this.dirProp2 = '';
}
}
@Directive({
selector: '[title]',
inputs: ['title'],
standalone: false,
})
class DirectiveWithTitle {
title: string | undefined;
}
@Directive({
selector: '[title]',
inputs: ['title'],
host: {'[title]': 'title'},
standalone: false,
})
class DirectiveWithTitleAndHostProperty {
title: string | undefined;
}
@Component({
selector: 'event-cmp',
template: '<div (click)="noop()"></div>',
standalone: false,
})
class EventCmp {
noop() {}
}
@Component({
selector: 'push-cmp',
inputs: ['prop'],
host: {'(click)': 'true'},
changeDetection: ChangeDetectionStrategy.OnPush,
template:
'{{field}}<div (click)="noop()"></div><div *ngIf="true" (click)="noop()"></div><event-cmp></event-cmp>',
standalone: false,
})
class PushCmp {
numberOfChecks: number;
prop: any;
constructor() {
this.numberOfChecks = 0;
}
noop() {}
get field() {
this.numberOfChecks++;
return 'fixed';
}
}
@Component({
selector: 'push-cmp-with-ref',
inputs: ['prop'],
changeDetection: ChangeDetectionStrategy.OnPush,
template: '{{field}}',
standalone: false,
})
class PushCmpWithRef {
numberOfChecks: number;
ref: ChangeDetectorRef;
prop: any;
constructor(ref: ChangeDetectorRef) {
this.numberOfChecks = 0;
this.ref = ref;
}
get field() {
this.numberOfChecks++;
return 'fixed';
}
propagate() {
this.ref.markForCheck();
}
}
@Component({
selector: 'push-cmp-with-host-event',
host: {'(click)': 'ctxCallback($event)'},
changeDetection: ChangeDetectionStrategy.OnPush,
template: '',
standalone: false,
})
class PushCmpWithHostEvent {
ctxCallback: Function = (_: any) => {};
}
@Component({
selector: 'push-cmp-with-async',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '{{field | async}}',
standalone: false,
})
class PushCmpWithAsyncPipe {
numberOfChecks: number = 0;
resolve!: (result: any) => void;
promise: Promise<any>;
constructor() {
this.promise = new Promise((resolve) => {
this.resolve = resolve;
});
}
get field() {
this.numberOfChecks++;
return this.promise;
}
}
@Component({
selector: 'my-comp',
template: '',
standalone: false,
})
class MyComp {
ctxProp: string;
ctxNumProp: number;
ctxBoolProp: boolean;
ctxArrProp: number[];
toStringThrow = {
toString: function () {
throw 'boom';
},
};
constructor() {
this.ctxProp = 'initial value';
this.ctxNumProp = 0;
this.ctxBoolProp = false;
this.ctxArrProp = [0, 1, 2];
}
throwError() {
throw 'boom';
}
}
@Component({
selector: 'child-cmp',
inputs: ['dirProp'],
viewProviders: [MyService],
template: '{{ctxProp}}',
standalone: false,
})
class ChildComp {
ctxProp: string;
dirProp: string | null;
constructor(service: MyService) {
this.ctxProp = service.greeting;
this.dirProp = null;
}
}
@Component({
selector: 'child-cmp-no-template',
template: '',
standalone: false,
})
class ChildCompNoTemplate {
ctxProp: string = 'hello';
}
@Component({
selector: 'child-cmp-svc',
template: '{{ctxProp}}',
standalone: false,
})
class ChildCompUsingService {
ctxProp: string;
constructor(service: MyService) {
this.ctxProp = service.greeting;
}
}
@Directive({
selector: 'some-directive',
standalone: false,
})
class SomeDirective {}
class SomeDirectiveMissingAnnotation {}
@Component({
selector: 'cmp-with-host',
template: '<p>Component with an injected host</p>',
standalone: false,
})
class CompWithHost {
myHost: SomeDirective;
constructor(@Host() someComp: SomeDirective) {
this.myHost = someComp;
}
}
@Component({
selector: '[child-cmp2]',
viewProviders: [MyService],
standalone: false,
})
class ChildComp2 {
ctxProp: string;
dirProp: string | null;
constructor(service: MyService) {
this.ctxProp = service.greeting;
this.dirProp = null;
}
}
class SomeViewportContext {
constructor(public someTmpl: string) {}
}
@Directive({
selector: '[some-viewport]',
standalone: false,
})
class SomeViewport {
constructor(
public container: ViewContainerRef,
templateRef: TemplateRef<SomeViewportContext>,
) {
container.createEmbeddedView(templateRef, new SomeViewportContext('hello'));
container.createEmbeddedView(templateRef, new SomeViewportContext('again'));
}
}
@Directive({
selector: '[pollutedContext]',
standalone: false,
})
class PollutedContext {
constructor(
private tplRef: TemplateRef<any>,
private vcRef: ViewContainerRef,
) {
const evRef = this.vcRef.createEmbeddedView(this.tplRef);
evRef.context.bar = 'baz';
}
}
@Directive({
selector: '[noContext]',
standalone: false,
})
class NoContext {
constructor(
private tplRef: TemplateRef<any>,
private vcRef: ViewContainerRef,
) {
this.vcRef.createEmbeddedView(this.tplRef);
}
}
@Pipe({
name: 'double',
standalone: false,
})
class DoublePipe implements PipeTransform, OnDestroy {
ngOnDestroy() {}
transform(value: any) {
return `${value}${value}`;
}
}
@Directive({
selector: '[emitter]',
outputs: ['event'],
standalone: false,
})
class DirectiveEmittingEvent {
msg: string;
event: EventEmitter<any>;
constructor() {
this.msg = '';
this.event = new EventEmitter();
}
fireEvent(msg: string) {
this.event.emit(msg);
}
}
@Directive({
selector: '[update-host-attributes]',
host: {'role': 'button'},
standalone: false,
})
class DirectiveUpdatingHostAttributes {}
@D | {
"end_byte": 94946,
"start_byte": 87362,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/integration_spec.ts"
} |
angular/packages/core/test/linker/integration_spec.ts_94948_102303 | ective({
selector: '[update-host-properties]',
host: {'[id]': 'id'},
standalone: false,
})
class DirectiveUpdatingHostProperties {
id: string;
constructor() {
this.id = 'one';
}
}
@Directive({
selector: '[listener]',
host: {'(event)': 'onEvent($event)'},
standalone: false,
})
class DirectiveListeningEvent {
msg: string;
constructor() {
this.msg = '';
}
onEvent(msg: string) {
this.msg = msg;
}
}
@Directive({
selector: '[listener]',
host: {
'(domEvent)': 'onEvent($event.type)',
'(window:domEvent)': 'onWindowEvent($event.type)',
'(document:domEvent)': 'onDocumentEvent($event.type)',
'(body:domEvent)': 'onBodyEvent($event.type)',
},
standalone: false,
})
class DirectiveListeningDomEvent {
eventTypes: string[] = [];
onEvent(eventType: string) {
this.eventTypes.push(eventType);
}
onWindowEvent(eventType: string) {
this.eventTypes.push('window_' + eventType);
}
onDocumentEvent(eventType: string) {
this.eventTypes.push('document_' + eventType);
}
onBodyEvent(eventType: string) {
this.eventTypes.push('body_' + eventType);
}
}
let globalCounter = 0;
@Directive({
selector: '[listenerother]',
host: {'(window:domEvent)': 'onEvent($event.type)'},
standalone: false,
})
class DirectiveListeningDomEventOther {
eventType: string;
constructor() {
this.eventType = '';
}
onEvent(eventType: string) {
globalCounter++;
this.eventType = 'other_' + eventType;
}
}
@Directive({
selector: '[listenerprevent]',
host: {'(click)': 'onEvent($event)'},
standalone: false,
})
class DirectiveListeningDomEventPrevent {
onEvent(event: any) {
return false;
}
}
@Directive({
selector: '[listenernoprevent]',
host: {'(click)': 'onEvent($event)'},
standalone: false,
})
class DirectiveListeningDomEventNoPrevent {
onEvent(event: any) {
return true;
}
}
@Directive({
selector: '[id]',
inputs: ['id'],
standalone: false,
})
class IdDir {
id: string | undefined;
}
@Directive({
selector: '[customEvent]',
standalone: false,
})
class EventDir {
@Output() customEvent = new EventEmitter();
doSomething() {}
}
@Directive({
selector: '[static]',
standalone: false,
})
class NeedsAttribute {
typeAttribute: string;
staticAttribute: string;
fooAttribute: string;
constructor(
@Attribute('type') typeAttribute: string,
@Attribute('static') staticAttribute: string,
@Attribute('foo') fooAttribute: string,
) {
this.typeAttribute = typeAttribute;
this.staticAttribute = staticAttribute;
this.fooAttribute = fooAttribute;
}
}
@Injectable()
class PublicApi {}
@Directive({
selector: '[public-api]',
providers: [{provide: PublicApi, useExisting: PrivateImpl, deps: []}],
standalone: false,
})
class PrivateImpl extends PublicApi {}
@Directive({
selector: '[needs-public-api]',
standalone: false,
})
class NeedsPublicApi {
constructor(@Host() api: PublicApi) {
expect(api instanceof PrivateImpl).toBe(true);
}
}
class ToolbarContext {
constructor(public toolbarProp: string) {}
}
@Directive({
selector: '[toolbarpart]',
standalone: false,
})
class ToolbarPart {
templateRef: TemplateRef<ToolbarContext>;
constructor(templateRef: TemplateRef<ToolbarContext>) {
this.templateRef = templateRef;
}
}
@Directive({
selector: '[toolbarVc]',
inputs: ['toolbarVc'],
standalone: false,
})
class ToolbarViewContainer {
constructor(public vc: ViewContainerRef) {}
set toolbarVc(part: ToolbarPart) {
this.vc.createEmbeddedView(part.templateRef, new ToolbarContext('From toolbar'), 0);
}
}
@Component({
selector: 'toolbar',
template: 'TOOLBAR(<div *ngFor="let part of query" [toolbarVc]="part"></div>)',
standalone: false,
})
class ToolbarComponent {
@ContentChildren(ToolbarPart) query!: QueryList<ToolbarPart>;
ctxProp: string = 'hello world';
constructor() {}
}
@Directive({
selector: '[two-way]',
inputs: ['control'],
outputs: ['controlChange'],
standalone: false,
})
class DirectiveWithTwoWayBinding {
controlChange = new EventEmitter();
control: any = null;
triggerChange(value: any) {
this.controlChange.emit(value);
}
}
@Injectable()
class InjectableService {}
function createInjectableWithLogging(inj: Injector) {
inj.get(ComponentProvidingLoggingInjectable).created = true;
return new InjectableService();
}
@Component({
selector: 'component-providing-logging-injectable',
providers: [
{provide: InjectableService, useFactory: createInjectableWithLogging, deps: [Injector]},
],
template: '',
standalone: false,
})
class ComponentProvidingLoggingInjectable {
created: boolean = false;
}
@Directive({
selector: 'directive-providing-injectable',
providers: [[InjectableService]],
standalone: false,
})
class DirectiveProvidingInjectable {}
@Component({
selector: 'directive-providing-injectable',
viewProviders: [[InjectableService]],
template: '',
standalone: false,
})
class DirectiveProvidingInjectableInView {}
@Component({
selector: 'directive-providing-injectable',
providers: [{provide: InjectableService, useValue: 'host'}],
viewProviders: [{provide: InjectableService, useValue: 'view'}],
template: '',
standalone: false,
})
class DirectiveProvidingInjectableInHostAndView {}
@Component({
selector: 'directive-consuming-injectable',
template: '',
standalone: false,
})
class DirectiveConsumingInjectable {
injectable: any;
constructor(@Host() @Inject(InjectableService) injectable: any) {
this.injectable = injectable;
}
}
@Component({
selector: 'directive-containing-directive-consuming-an-injectable',
standalone: false,
})
class DirectiveContainingDirectiveConsumingAnInjectable {
directive: any;
}
@Component({
selector: 'directive-consuming-injectable-unbounded',
template: '',
standalone: false,
})
class DirectiveConsumingInjectableUnbounded {
injectable: any;
constructor(
injectable: InjectableService,
@SkipSelf() parent: DirectiveContainingDirectiveConsumingAnInjectable,
) {
this.injectable = injectable;
parent.directive = this;
}
}
class EventBus {
parentEventBus: EventBus;
name: string;
constructor(parentEventBus: EventBus, name: string) {
this.parentEventBus = parentEventBus;
this.name = name;
}
}
@Directive({
selector: 'grand-parent-providing-event-bus',
providers: [{provide: EventBus, useValue: new EventBus(null!, 'grandparent')}],
standalone: false,
})
class GrandParentProvidingEventBus {
bus: EventBus;
constructor(bus: EventBus) {
this.bus = bus;
}
}
function createParentBus(peb: EventBus) {
return new EventBus(peb, 'parent');
}
@Component({
selector: 'parent-providing-event-bus',
providers: [{provide: EventBus, useFactory: createParentBus, deps: [[EventBus, new SkipSelf()]]}],
template: `<child-consuming-event-bus></child-consuming-event-bus>`,
standalone: false,
})
class ParentProvidingEventBus {
bus: EventBus;
grandParentBus: EventBus;
constructor(bus: EventBus, @SkipSelf() grandParentBus: EventBus) {
this.bus = bus;
this.grandParentBus = grandParentBus;
}
}
@Directive({
selector: 'child-consuming-event-bus',
standalone: false,
})
class ChildConsumingEventBus {
bus: EventBus;
constructor(@SkipSelf() bus: EventBus) {
this.bus = bus;
}
}
@D | {
"end_byte": 102303,
"start_byte": 94948,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/integration_spec.ts"
} |
angular/packages/core/test/linker/integration_spec.ts_102305_105051 | ective({
selector: '[someImpvp]',
inputs: ['someImpvp'],
standalone: false,
})
class SomeImperativeViewport {
view: EmbeddedViewRef<Object> | null;
anchor: any;
constructor(
public vc: ViewContainerRef,
public templateRef: TemplateRef<Object>,
@Inject(ANCHOR_ELEMENT) anchor: any,
) {
this.view = null;
this.anchor = anchor;
}
set someImpvp(value: boolean) {
if (this.view) {
this.vc.clear();
this.view = null;
}
if (value) {
this.view = this.vc.createEmbeddedView(this.templateRef);
const nodes = this.view.rootNodes;
for (let i = 0; i < nodes.length; i++) {
this.anchor.appendChild(nodes[i]);
}
}
}
}
@Directive({
selector: '[export-dir]',
exportAs: 'dir',
standalone: false,
})
class ExportDir {}
@Directive({
selector: '[multiple-export-as]',
exportAs: 'dirX, dirY',
standalone: false,
})
export class DirectiveWithMultipleExportAsNames {}
@Component({
selector: 'comp',
standalone: false,
})
class ComponentWithoutView {}
@Directive({
selector: '[no-duplicate]',
standalone: false,
})
class DuplicateDir {
constructor(elRef: ElementRef) {
elRef.nativeElement.textContent += 'noduplicate';
}
}
@Directive({
selector: '[no-duplicate]',
standalone: false,
})
class OtherDuplicateDir {
constructor(elRef: ElementRef) {
elRef.nativeElement.textContent += 'othernoduplicate';
}
}
@Directive({
selector: 'directive-throwing-error',
standalone: false,
})
class DirectiveThrowingAnError {
constructor() {
throw new Error('BOOM');
}
}
@Component({
selector: 'component-with-template',
template: `No View Decorator: <div *ngFor="let item of items">{{item}}</div>`,
standalone: false,
})
class ComponentWithTemplate {
items = [1, 2, 3];
}
@Directive({
selector: 'with-prop-decorators',
standalone: false,
})
class DirectiveWithPropDecorators {
target: any;
@Input('elProp') dirProp: string | undefined;
@Output('elEvent') event = new EventEmitter();
@HostBinding('attr.my-attr') myAttr: string | undefined;
@HostListener('click', ['$event.target'])
onClick(target: any) {
this.target = target;
}
fireEvent(msg: any) {
this.event.emit(msg);
}
}
@Component({
selector: 'some-cmp',
standalone: false,
})
class SomeCmp {
value: any;
}
@Component({
selector: 'parent-cmp',
template: `<cmp [test$]="name"></cmp>`,
standalone: false,
})
export class ParentCmp {
name: string = 'hello';
}
@Component({
selector: 'cmp',
template: '',
standalone: false,
})
class SomeCmpWithInput {
@Input() test$: any;
}
function isPrevented(evt: Event): boolean {
return evt.defaultPrevented || (evt.returnValue != null && !evt.returnValue);
}
| {
"end_byte": 105051,
"start_byte": 102305,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/integration_spec.ts"
} |
angular/packages/core/test/linker/projection_integration_spec.ts_0_741 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ɵgetDOM as getDOM} from '@angular/common';
import {
Component,
ComponentRef,
createComponent,
Directive,
ElementRef,
EnvironmentInjector,
Injector,
Input,
NgModule,
NO_ERRORS_SCHEMA,
OnInit,
reflectComponentType,
TemplateRef,
ViewChild,
ViewContainerRef,
ViewEncapsulation,
} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser/src/dom/debug/by';
import {expect} from '@angular/platform-browser/testing/src/matchers';
| {
"end_byte": 741,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/projection_integration_spec.ts"
} |
angular/packages/core/test/linker/projection_integration_spec.ts_743_9218 | escribe('projection', () => {
beforeEach(() => TestBed.configureTestingModule({declarations: [MainComp, OtherComp, Simple]}));
it('should support simple components', () => {
const template = '<simple><div>A</div></simple>';
TestBed.overrideComponent(MainComp, {set: {template}});
const main = TestBed.createComponent(MainComp);
expect(main.nativeElement).toHaveText('SIMPLE(A)');
});
it('should support simple components with text interpolation as direct children', () => {
const template = "{{'START('}}<simple>" + '{{text}}' + "</simple>{{')END'}}";
TestBed.overrideComponent(MainComp, {set: {template}});
const main = TestBed.createComponent(MainComp);
main.componentInstance.text = 'A';
main.detectChanges();
expect(main.nativeElement).toHaveText('START(SIMPLE(A))END');
});
it('should support projecting text interpolation to a non bound element', () => {
TestBed.overrideComponent(Simple, {
set: {template: 'SIMPLE(<div><ng-content></ng-content></div>)'},
});
TestBed.overrideComponent(MainComp, {set: {template: '<simple>{{text}}</simple>'}});
const main = TestBed.createComponent(MainComp);
main.componentInstance.text = 'A';
main.detectChanges();
expect(main.nativeElement).toHaveText('SIMPLE(A)');
});
it('should support projecting text interpolation to a non bound element with other bound elements after it', () => {
TestBed.overrideComponent(Simple, {
set: {template: 'SIMPLE(<div><ng-content></ng-content></div><div [tabIndex]="0">EL</div>)'},
});
TestBed.overrideComponent(MainComp, {set: {template: '<simple>{{text}}</simple>'}});
const main = TestBed.createComponent(MainComp);
main.componentInstance.text = 'A';
main.detectChanges();
expect(main.nativeElement).toHaveText('SIMPLE(AEL)');
});
it('should project content components', () => {
TestBed.overrideComponent(Simple, {
set: {template: 'SIMPLE({{0}}|<ng-content></ng-content>|{{2}})'},
});
TestBed.overrideComponent(OtherComp, {set: {template: '{{1}}'}});
TestBed.overrideComponent(MainComp, {set: {template: '<simple><other></other></simple>'}});
const main = TestBed.createComponent(MainComp);
main.detectChanges();
expect(main.nativeElement).toHaveText('SIMPLE(0|1|2)');
});
it('should not show the light dom even if there is no content tag', () => {
TestBed.configureTestingModule({declarations: [Empty]});
TestBed.overrideComponent(MainComp, {set: {template: '<empty>A</empty>'}});
const main = TestBed.createComponent(MainComp);
expect(main.nativeElement).toHaveText('');
});
it('should project a single class-based tag', () => {
TestBed.configureTestingModule({declarations: [SingleContentTagComponent]});
TestBed.overrideComponent(MainComp, {
set: {
template:
'<single-content-tag>' +
'<div class="target">I AM PROJECTED</div>' +
'</single-content-tag>',
},
});
const main = TestBed.createComponent(MainComp);
expect(main.nativeElement).toHaveText('I AM PROJECTED');
});
it('should support multiple content tags', () => {
TestBed.configureTestingModule({declarations: [MultipleContentTagsComponent]});
TestBed.overrideComponent(MainComp, {
set: {
template:
'<multiple-content-tags>' +
'<div>B</div>' +
'<div>C</div>' +
'<div class="left">A</div>' +
'</multiple-content-tags>',
},
});
const main = TestBed.createComponent(MainComp);
expect(main.nativeElement).toHaveText('(A, BC)');
});
it('should support passing projectable nodes via factory function', () => {
@Component({
selector: 'multiple-content-tags',
template: '(<ng-content SELECT="h1"></ng-content>, <ng-content></ng-content>)',
standalone: false,
})
class MultipleContentTagsComponent {}
TestBed.configureTestingModule({declarations: [MultipleContentTagsComponent]});
const injector: Injector = TestBed.inject(Injector);
expect(reflectComponentType(MultipleContentTagsComponent)?.ngContentSelectors).toEqual([
'h1',
'*',
]);
const nodeOne = getDOM().getDefaultDocument().createTextNode('one');
const nodeTwo = getDOM().getDefaultDocument().createTextNode('two');
const component = createComponent(MultipleContentTagsComponent, {
environmentInjector: injector as EnvironmentInjector,
projectableNodes: [[nodeOne], [nodeTwo]],
});
expect(component.location.nativeElement).toHaveText('(one, two)');
});
it('should redistribute only direct children', () => {
TestBed.configureTestingModule({declarations: [MultipleContentTagsComponent]});
TestBed.overrideComponent(MainComp, {
set: {
template:
'<multiple-content-tags>' +
'<div>B<div class="left">A</div></div>' +
'<div>C</div>' +
'</multiple-content-tags>',
},
});
const main = TestBed.createComponent(MainComp);
expect(main.nativeElement).toHaveText('(, BAC)');
});
it('should redistribute direct child viewcontainers when the light dom changes', () => {
TestBed.configureTestingModule({
declarations: [MultipleContentTagsComponent, ManualViewportDirective],
});
TestBed.overrideComponent(MainComp, {
set: {
template:
'<multiple-content-tags>' +
'<ng-template manual class="left"><div>A1</div></ng-template>' +
'<div>B</div>' +
'</multiple-content-tags>',
},
});
const main = TestBed.createComponent(MainComp);
const viewportDirectives = main.debugElement.children[0].childNodes
.filter(By.directive(ManualViewportDirective))
.map((de) => de.injector.get(ManualViewportDirective));
expect(main.nativeElement).toHaveText('(, B)');
viewportDirectives.forEach((d) => d.show());
main.detectChanges();
expect(main.nativeElement).toHaveText('(A1, B)');
viewportDirectives.forEach((d) => d.hide());
main.detectChanges();
expect(main.nativeElement).toHaveText('(, B)');
});
it('should support nested components', () => {
TestBed.configureTestingModule({declarations: [OuterWithIndirectNestedComponent]});
TestBed.overrideComponent(MainComp, {
set: {
template:
'<outer-with-indirect-nested>' +
'<div>A</div>' +
'<div>B</div>' +
'</outer-with-indirect-nested>',
},
});
const main = TestBed.createComponent(MainComp);
expect(main.nativeElement).toHaveText('OUTER(SIMPLE(AB))');
});
it('should support nesting with content being direct child of a nested component', () => {
TestBed.configureTestingModule({
declarations: [InnerComponent, InnerInnerComponent, OuterComponent, ManualViewportDirective],
});
TestBed.overrideComponent(MainComp, {
set: {
template:
'<outer>' +
'<ng-template manual class="left"><div>A</div></ng-template>' +
'<div>B</div>' +
'<div>C</div>' +
'</outer>',
},
});
const main = TestBed.createComponent(MainComp);
const viewportDirective = main.debugElement
.queryAllNodes(By.directive(ManualViewportDirective))[0]
.injector.get(ManualViewportDirective);
expect(main.nativeElement).toHaveText('OUTER(INNER(INNERINNER(,BC)))');
viewportDirective.show();
expect(main.nativeElement).toHaveText('OUTER(INNER(INNERINNER(A,BC)))');
});
it('should redistribute when the shadow dom changes', () => {
TestBed.configureTestingModule({
declarations: [ConditionalContentComponent, ManualViewportDirective],
});
TestBed.overrideComponent(MainComp, {
set: {
template:
'<conditional-content>' +
'<div class="left">A</div>' +
'<div>B</div>' +
'<div>C</div>' +
'</conditional-content>',
},
});
const main = TestBed.createComponent(MainComp);
const viewportDirective = main.debugElement
.queryAllNodes(By.directive(ManualViewportDirective))[0]
.injector.get(ManualViewportDirective);
expect(main.nativeElement).toHaveText('(, BC)');
viewportDirective.show();
main.detectChanges();
expect(main.nativeElement).toHaveText('(A, BC)');
viewportDirective.hide();
main.detectChanges();
expect(main.nativeElement).toHaveText('(, BC)');
});
| {
"end_byte": 9218,
"start_byte": 743,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/projection_integration_spec.ts"
} |
angular/packages/core/test/linker/projection_integration_spec.ts_9222_17719 | t('should redistribute non-continuous blocks of nodes when the shadow dom changes', () => {
@Component({
selector: 'child',
template: `<ng-content></ng-content>(<ng-template [ngIf]="showing"><ng-content select="div"></ng-content></ng-template>)`,
standalone: false,
})
class Child {
@Input() showing!: boolean;
}
@Component({
selector: 'app',
template: `<child [showing]="showing">
<div>A</div>
<span>B</span>
<div>A</div>
<span>B</span>
</child>`,
standalone: false,
})
class App {
showing = false;
}
TestBed.configureTestingModule({declarations: [App, Child]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('BB()');
fixture.componentInstance.showing = true;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('BB(AA)');
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('BB()');
});
// GH-2095 - https://github.com/angular/angular/issues/2095
// important as we are removing the ng-content element during compilation,
// which could skrew up text node indices.
it('should support text nodes after content tags', () => {
TestBed.overrideComponent(MainComp, {set: {template: '<simple stringProp="text"></simple>'}});
TestBed.overrideComponent(Simple, {
set: {template: '<ng-content></ng-content><p>P,</p>{{stringProp}}'},
});
const main = TestBed.createComponent(MainComp);
main.detectChanges();
expect(main.nativeElement).toHaveText('P,text');
});
// important as we are moving style tags around during compilation,
// which could skrew up text node indices.
it('should support text nodes after style tags', () => {
TestBed.overrideComponent(MainComp, {set: {template: '<simple stringProp="text"></simple>'}});
TestBed.overrideComponent(Simple, {set: {template: '<style></style><p>P,</p>{{stringProp}}'}});
const main = TestBed.createComponent(MainComp);
main.detectChanges();
expect(main.nativeElement).toHaveText('P,text');
});
it('should support moving non projected light dom around', () => {
let sourceDirective: ManualViewportDirective = undefined!;
@Directive({
selector: '[manual]',
standalone: false,
})
class ManualViewportDirective {
constructor(public templateRef: TemplateRef<Object>) {
sourceDirective = this;
}
}
TestBed.configureTestingModule({
declarations: [Empty, ProjectDirective, ManualViewportDirective],
});
TestBed.overrideComponent(MainComp, {
set: {
template:
'<empty>' +
' <ng-template manual><div>A</div></ng-template>' +
'</empty>' +
'START(<div project></div>)END',
},
});
const main = TestBed.createComponent(MainComp);
const projectDirective: ProjectDirective = main.debugElement
.queryAllNodes(By.directive(ProjectDirective))[0]
.injector.get(ProjectDirective);
expect(main.nativeElement).toHaveText('START()END');
projectDirective.show(sourceDirective.templateRef);
expect(main.nativeElement).toHaveText('START(A)END');
});
it('should support moving projected light dom around', () => {
TestBed.configureTestingModule({
declarations: [Empty, ProjectDirective, ManualViewportDirective],
});
TestBed.overrideComponent(MainComp, {
set: {
template:
'<simple><ng-template manual><div>A</div></ng-template></simple>' +
'START(<div project></div>)END',
},
});
const main = TestBed.createComponent(MainComp);
const sourceDirective: ManualViewportDirective = main.debugElement
.queryAllNodes(By.directive(ManualViewportDirective))[0]
.injector.get(ManualViewportDirective);
const projectDirective: ProjectDirective = main.debugElement
.queryAllNodes(By.directive(ProjectDirective))[0]
.injector.get(ProjectDirective);
expect(main.nativeElement).toHaveText('SIMPLE()START()END');
projectDirective.show(sourceDirective.templateRef);
expect(main.nativeElement).toHaveText('SIMPLE()START(A)END');
});
it('should support moving ng-content around', () => {
TestBed.configureTestingModule({
declarations: [ConditionalContentComponent, ProjectDirective, ManualViewportDirective],
});
TestBed.overrideComponent(MainComp, {
set: {
template:
'<conditional-content>' +
'<div class="left">A</div>' +
'<div>B</div>' +
'</conditional-content>' +
'START(<div project></div>)END',
},
});
const main = TestBed.createComponent(MainComp);
const sourceDirective: ManualViewportDirective = main.debugElement
.queryAllNodes(By.directive(ManualViewportDirective))[0]
.injector.get(ManualViewportDirective);
const projectDirective: ProjectDirective = main.debugElement
.queryAllNodes(By.directive(ProjectDirective))[0]
.injector.get(ProjectDirective);
expect(main.nativeElement).toHaveText('(, B)START()END');
projectDirective.show(sourceDirective.templateRef);
expect(main.nativeElement).toHaveText('(, B)START(A)END');
// Stamping ng-content multiple times should not produce the content multiple
// times...
projectDirective.show(sourceDirective.templateRef);
expect(main.nativeElement).toHaveText('(, B)START(A)END');
});
// Note: This does not use a ng-content element, but
// is still important as we are merging proto views independent of
// the presence of ng-content elements!
it('should still allow to implement a recursive trees', () => {
TestBed.configureTestingModule({declarations: [Tree, ManualViewportDirective]});
TestBed.overrideComponent(MainComp, {set: {template: '<tree></tree>'}});
const main = TestBed.createComponent(MainComp);
main.detectChanges();
const manualDirective: ManualViewportDirective = main.debugElement
.queryAllNodes(By.directive(ManualViewportDirective))[0]
.injector.get(ManualViewportDirective);
expect(main.nativeElement).toHaveText('TREE(0:)');
manualDirective.show();
main.detectChanges();
expect(main.nativeElement).toHaveText('TREE(0:TREE(1:))');
});
// Note: This does not use a ng-content element, but
// is still important as we are merging proto views independent of
// the presence of ng-content elements!
it('should still allow to implement a recursive trees via multiple components', () => {
TestBed.configureTestingModule({declarations: [Tree, Tree2, ManualViewportDirective]});
TestBed.overrideComponent(MainComp, {set: {template: '<tree></tree>'}});
TestBed.overrideComponent(Tree, {
set: {template: 'TREE({{depth}}:<tree2 *manual [depth]="depth+1"></tree2>)'},
});
const main = TestBed.createComponent(MainComp);
main.detectChanges();
expect(main.nativeElement).toHaveText('TREE(0:)');
const tree = main.debugElement.query(By.directive(Tree));
let manualDirective: ManualViewportDirective = tree
.queryAllNodes(By.directive(ManualViewportDirective))[0]
.injector.get(ManualViewportDirective);
manualDirective.show();
main.detectChanges();
expect(main.nativeElement).toHaveText('TREE(0:TREE2(1:))');
const tree2 = main.debugElement.query(By.directive(Tree2));
manualDirective = tree2
.queryAllNodes(By.directive(ManualViewportDirective))[0]
.injector.get(ManualViewportDirective);
manualDirective.show();
main.detectChanges();
expect(main.nativeElement).toHaveText('TREE(0:TREE2(1:TREE(2:)))');
});
if (!isNode) {
it('should support shadow dom content projection and isolate styles per component', () => {
TestBed.configureTestingModule({declarations: [SimpleShadowDom1, SimpleShadowDom2]});
TestBed.overrideComponent(MainComp, {
set: {
template:
'<simple-shadow-dom1><div>A</div></simple-shadow-dom1>' +
'<simple-shadow-dom2><div>B</div></simple-shadow-dom2>',
},
});
const main = TestBed.createComponent(MainComp);
const childNodes = main.nativeElement.childNodes;
expect(childNodes[0]).toHaveText('div {color: red}SIMPLE1(A)');
expect(childNodes[1]).toHaveText('div {color: blue}SIMPLE2(B)');
main.destroy();
});
}
| {
"end_byte": 17719,
"start_byte": 9222,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/projection_integration_spec.ts"
} |
angular/packages/core/test/linker/projection_integration_spec.ts_17723_25491 | f (getDOM().supportsDOMEvents) {
it('should support non emulated styles', () => {
TestBed.configureTestingModule({declarations: [OtherComp]});
TestBed.overrideComponent(MainComp, {
set: {
template: '<div class="redStyle"></div>',
styles: ['.redStyle { color: red}'],
encapsulation: ViewEncapsulation.None,
},
});
const main = TestBed.createComponent(MainComp);
const mainEl = main.nativeElement;
const div1 = mainEl.firstChild;
const div2 = getDOM().createElement('div');
div2.setAttribute('class', 'redStyle');
mainEl.appendChild(div2);
expect(getComputedStyle(div1).color).toEqual('rgb(255, 0, 0)');
expect(getComputedStyle(div2).color).toEqual('rgb(255, 0, 0)');
});
it('should support emulated style encapsulation', () => {
TestBed.configureTestingModule({declarations: [OtherComp]});
TestBed.overrideComponent(MainComp, {
set: {
template: '<div></div>',
styles: ['div { color: red}'],
encapsulation: ViewEncapsulation.Emulated,
},
});
const main = TestBed.createComponent(MainComp);
const mainEl = main.nativeElement;
const div1 = mainEl.firstChild;
const div2 = getDOM().createElement('div');
mainEl.appendChild(div2);
expect(getComputedStyle(div1).color).toEqual('rgb(255, 0, 0)');
expect(getComputedStyle(div2).color).toEqual('rgb(0, 0, 0)');
});
}
it('should support nested conditionals that contain ng-contents', () => {
TestBed.configureTestingModule({
declarations: [ConditionalTextComponent, ManualViewportDirective],
});
TestBed.overrideComponent(MainComp, {
set: {template: `<conditional-text>a</conditional-text>`},
});
const main = TestBed.createComponent(MainComp);
expect(main.nativeElement).toHaveText('MAIN()');
let viewportElement = main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0];
viewportElement.injector.get(ManualViewportDirective).show();
expect(main.nativeElement).toHaveText('MAIN(FIRST())');
viewportElement = main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[1];
viewportElement.injector.get(ManualViewportDirective).show();
expect(main.nativeElement).toHaveText('MAIN(FIRST(SECOND(a)))');
});
it('should allow to switch the order of nested components via ng-content', () => {
TestBed.configureTestingModule({declarations: [CmpA, CmpB, CmpD, CmpC]});
TestBed.overrideComponent(MainComp, {set: {template: `<cmp-a><cmp-b></cmp-b></cmp-a>`}});
const main = TestBed.createComponent(MainComp);
main.detectChanges();
expect(main.nativeElement.innerHTML).toEqual(
'<cmp-a><cmp-b><cmp-d><i>cmp-d</i></cmp-d></cmp-b>' + '<cmp-c><b>cmp-c</b></cmp-c></cmp-a>',
);
});
it('should create nested components in the right order', () => {
TestBed.configureTestingModule({declarations: [CmpA1, CmpA2, CmpB11, CmpB12, CmpB21, CmpB22]});
TestBed.overrideComponent(MainComp, {set: {template: `<cmp-a1></cmp-a1><cmp-a2></cmp-a2>`}});
const main = TestBed.createComponent(MainComp);
main.detectChanges();
expect(main.nativeElement.innerHTML).toEqual(
'<cmp-a1>a1<cmp-b11>b11</cmp-b11><cmp-b12>b12</cmp-b12></cmp-a1>' +
'<cmp-a2>a2<cmp-b21>b21</cmp-b21><cmp-b22>b22</cmp-b22></cmp-a2>',
);
});
it("should project nodes into nested templates when the main template doesn't have <ng-content>", () => {
@Component({
selector: 'content-in-template',
template: `(<ng-template manual><ng-content select="[id=left]"></ng-content></ng-template>)`,
standalone: false,
})
class ContentInATemplateComponent {}
TestBed.configureTestingModule({
declarations: [ContentInATemplateComponent, ManualViewportDirective],
});
TestBed.overrideComponent(MainComp, {
set: {template: `<content-in-template><div id="left">A</div></content-in-template>`},
});
const main = TestBed.createComponent(MainComp);
main.detectChanges();
expect(main.nativeElement).toHaveText('()');
let viewportElement = main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0];
viewportElement.injector.get(ManualViewportDirective).show();
expect(main.nativeElement).toHaveText('(A)');
});
it('should project nodes into nested templates and the main template', () => {
@Component({
selector: 'content-in-main-and-template',
template: `<ng-content></ng-content>(<ng-template manual><ng-content select="[id=left]"></ng-content></ng-template>)`,
standalone: false,
})
class ContentInMainAndTemplateComponent {}
TestBed.configureTestingModule({
declarations: [ContentInMainAndTemplateComponent, ManualViewportDirective],
});
TestBed.overrideComponent(MainComp, {
set: {
template: `<content-in-main-and-template><div id="left">A</div>B</content-in-main-and-template>`,
},
});
const main = TestBed.createComponent(MainComp);
main.detectChanges();
expect(main.nativeElement).toHaveText('B()');
let viewportElement = main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0];
viewportElement.injector.get(ManualViewportDirective).show();
expect(main.nativeElement).toHaveText('B(A)');
});
it('should project view containers', () => {
TestBed.configureTestingModule({
declarations: [SingleContentTagComponent, ManualViewportDirective],
});
TestBed.overrideComponent(MainComp, {
set: {
template:
'<single-content-tag>' +
'<div class="target">A</div>' +
'<ng-template manual class="target">B</ng-template>' +
'<div class="target">C</div>' +
'</single-content-tag>',
},
});
const main = TestBed.createComponent(MainComp);
const manualDirective = main.debugElement
.queryAllNodes(By.directive(ManualViewportDirective))[0]
.injector.get(ManualViewportDirective);
expect(main.nativeElement).toHaveText('AC');
manualDirective.show();
main.detectChanges();
expect(main.nativeElement).toHaveText('ABC');
});
it('should project filled view containers into a view container', () => {
TestBed.configureTestingModule({
declarations: [ConditionalContentComponent, ManualViewportDirective],
});
TestBed.overrideComponent(MainComp, {
set: {
template:
'<conditional-content>' +
'<div class="left">A</div>' +
'<ng-template manual class="left">B</ng-template>' +
'<div class="left">C</div>' +
'<div>D</div>' +
'</conditional-content>',
},
});
const main = TestBed.createComponent(MainComp);
const conditionalComp = main.debugElement.query(By.directive(ConditionalContentComponent));
const viewViewportDir = conditionalComp
.queryAllNodes(By.directive(ManualViewportDirective))[0]
.injector.get(ManualViewportDirective);
expect(main.nativeElement).toHaveText('(, D)');
expect(main.nativeElement).toHaveText('(, D)');
viewViewportDir.show();
main.detectChanges();
expect(main.nativeElement).toHaveText('(AC, D)');
const contentViewportDir = conditionalComp
.queryAllNodes(By.directive(ManualViewportDirective))[1]
.injector.get(ManualViewportDirective);
contentViewportDir.show();
main.detectChanges();
expect(main.nativeElement).toHaveText('(ABC, D)');
// hide view viewport, and test that it also hides
// the content viewport's views
viewViewportDir.hide();
main.detectChanges();
expect(main.nativeElement).toHaveText('(, D)');
});
| {
"end_byte": 25491,
"start_byte": 17723,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/projection_integration_spec.ts"
} |
angular/packages/core/test/linker/projection_integration_spec.ts_25495_33688 | escribe('projectable nodes', () => {
@Component({
selector: 'test',
template: '',
standalone: false,
})
class TestComponent {
constructor(public vcr: ViewContainerRef) {}
}
@Component({
selector: 'with-content',
template: '',
standalone: false,
})
class WithContentCmpt {
@ViewChild('ref', {static: true}) directiveRef: any;
}
@Component({
selector: 're-project',
template: '<ng-content></ng-content>',
standalone: false,
})
class ReProjectCmpt {}
@Directive({
selector: '[insert]',
standalone: false,
})
class InsertTplRef implements OnInit {
constructor(
private _vcRef: ViewContainerRef,
private _tplRef: TemplateRef<{}>,
) {}
ngOnInit() {
this._vcRef.createEmbeddedView(this._tplRef);
}
}
@Directive({
selector: '[delayedInsert]',
exportAs: 'delayedInsert',
standalone: false,
})
class DelayedInsertTplRef {
constructor(
public vc: ViewContainerRef,
public templateRef: TemplateRef<Object>,
) {}
show() {
this.vc.createEmbeddedView(this.templateRef);
}
hide() {
this.vc.clear();
}
}
let fixture: ComponentFixture<TestComponent>;
function createCmptInstance(
tpl: string,
projectableNodes: any[][],
): ComponentRef<WithContentCmpt> {
TestBed.configureTestingModule({
declarations: [
WithContentCmpt,
InsertTplRef,
DelayedInsertTplRef,
ReProjectCmpt,
TestComponent,
],
});
TestBed.overrideTemplate(WithContentCmpt, tpl);
fixture = TestBed.createComponent(TestComponent);
const vcr = fixture.componentInstance.vcr;
const cmptRef = vcr.createComponent(WithContentCmpt, {
injector: Injector.NULL,
projectableNodes,
});
cmptRef.changeDetectorRef.detectChanges();
return cmptRef;
}
it('should pass nodes to the default ng-content without selectors', () => {
const cmptRef = createCmptInstance('<div>(<ng-content></ng-content>)</div>', [
[document.createTextNode('A')],
]);
expect(cmptRef.location.nativeElement).toHaveText('(A)');
});
it('should pass nodes to the default ng-content at the root', () => {
const cmptRef = createCmptInstance('<ng-content></ng-content>', [
[document.createTextNode('A')],
]);
expect(cmptRef.location.nativeElement).toHaveText('A');
});
it('should pass nodes to multiple ng-content tags', () => {
const cmptRef = createCmptInstance(
'A:(<ng-content></ng-content>)B:(<ng-content select="b"></ng-content>)C:(<ng-content select="c"></ng-content>)',
[
[document.createTextNode('A')],
[document.createTextNode('B')],
[document.createTextNode('C')],
],
);
expect(cmptRef.location.nativeElement).toHaveText('A:(A)B:(B)C:(C)');
});
it('should pass nodes to the default ng-content inside ng-container', () => {
const cmptRef = createCmptInstance(
'A<ng-container>(<ng-content></ng-content>)</ng-container>C',
[[document.createTextNode('B')]],
);
expect(cmptRef.location.nativeElement).toHaveText('A(B)C');
});
it('should pass nodes to the default ng-content inside an embedded view', () => {
const cmptRef = createCmptInstance(
'A<ng-template insert>(<ng-content></ng-content>)</ng-template>C',
[[document.createTextNode('B')]],
);
expect(cmptRef.location.nativeElement).toHaveText('A(B)C');
});
it('should pass nodes to the default ng-content inside a delayed embedded view', () => {
const cmptRef = createCmptInstance(
'A(<ng-template #ref="delayedInsert" delayedInsert>[<ng-content></ng-content>]</ng-template>)C',
[[document.createTextNode('B')]],
);
expect(cmptRef.location.nativeElement).toHaveText('A()C');
const delayedInsert = cmptRef.instance.directiveRef as DelayedInsertTplRef;
delayedInsert.show();
cmptRef.changeDetectorRef.detectChanges();
expect(cmptRef.location.nativeElement).toHaveText('A([B])C');
delayedInsert.hide();
cmptRef.changeDetectorRef.detectChanges();
expect(cmptRef.location.nativeElement).toHaveText('A()C');
});
it('should re-project at the root', () => {
const cmptRef = createCmptInstance(
'A[<re-project>(<ng-content></ng-content>)</re-project>]C',
[[document.createTextNode('B')]],
);
expect(cmptRef.location.nativeElement).toHaveText('A[(B)]C');
});
});
});
@Component({
selector: 'main',
template: '',
standalone: false,
})
class MainComp {
text: string = '';
}
@Component({
selector: 'other',
template: '',
standalone: false,
})
class OtherComp {
text: string = '';
}
@Component({
selector: 'simple',
inputs: ['stringProp'],
template: 'SIMPLE(<ng-content></ng-content>)',
standalone: false,
})
class Simple {
stringProp: string = '';
}
@Component({
selector: 'simple-shadow-dom1',
template: 'SIMPLE1(<slot></slot>)',
encapsulation: ViewEncapsulation.ShadowDom,
styles: ['div {color: red}'],
standalone: false,
})
class SimpleShadowDom1 {}
@Component({
selector: 'simple-shadow-dom2',
template: 'SIMPLE2(<slot></slot>)',
encapsulation: ViewEncapsulation.ShadowDom,
styles: ['div {color: blue}'],
standalone: false,
})
class SimpleShadowDom2 {}
@Component({
selector: 'empty',
template: '',
standalone: false,
})
class Empty {}
@Component({
selector: 'multiple-content-tags',
template: '(<ng-content SELECT=".left"></ng-content>, <ng-content></ng-content>)',
standalone: false,
})
class MultipleContentTagsComponent {}
@Component({
selector: 'single-content-tag',
template: '<ng-content SELECT=".target"></ng-content>',
standalone: false,
})
class SingleContentTagComponent {}
@Directive({
selector: '[manual]',
standalone: false,
})
class ManualViewportDirective {
constructor(
public vc: ViewContainerRef,
public templateRef: TemplateRef<Object>,
) {}
show() {
this.vc.createEmbeddedView(this.templateRef);
}
hide() {
this.vc.clear();
}
}
@Directive({
selector: '[project]',
standalone: false,
})
class ProjectDirective {
constructor(public vc: ViewContainerRef) {}
show(templateRef: TemplateRef<Object>) {
this.vc.createEmbeddedView(templateRef);
}
hide() {
this.vc.clear();
}
}
@Component({
selector: 'outer-with-indirect-nested',
template: 'OUTER(<simple><div><ng-content></ng-content></div></simple>)',
standalone: false,
})
class OuterWithIndirectNestedComponent {}
@Component({
selector: 'outer',
template:
'OUTER(<inner><ng-content select=".left" class="left"></ng-content><ng-content></ng-content></inner>)',
standalone: false,
})
class OuterComponent {}
@Component({
selector: 'inner',
template:
'INNER(<innerinner><ng-content select=".left" class="left"></ng-content><ng-content></ng-content></innerinner>)',
standalone: false,
})
class InnerComponent {}
@Component({
selector: 'innerinner',
template: 'INNERINNER(<ng-content select=".left"></ng-content>,<ng-content></ng-content>)',
standalone: false,
})
class InnerInnerComponent {}
@Component({
selector: 'conditional-content',
template:
'<div>(<div *manual><ng-content select=".left"></ng-content></div>, <ng-content></ng-content>)</div>',
standalone: false,
})
class ConditionalContentComponent {}
@Component({
selector: 'conditional-text',
template:
'MAIN(<ng-template manual>FIRST(<ng-template manual>SECOND(<ng-content></ng-content>)</ng-template>)</ng-template>)',
standalone: false,
})
class ConditionalTextComponent {}
@Component({
selector: 'tab',
template: '<div><div *manual>TAB(<ng-content></ng-content>)</div></div>',
standalone: false,
})
class Tab {}
@Component({
selector: 'tree2',
inputs: ['depth'],
template: 'TREE2({{depth}}:<tree *manual [depth]="depth+1"></tree>)',
standalone: false,
})
class Tree2 {
depth = 0;
}
| {
"end_byte": 33688,
"start_byte": 25495,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/projection_integration_spec.ts"
} |
angular/packages/core/test/linker/projection_integration_spec.ts_33690_35282 | Component({
selector: 'tree',
inputs: ['depth'],
template: 'TREE({{depth}}:<tree *manual [depth]="depth+1"></tree>)',
standalone: false,
})
class Tree {
depth = 0;
}
@Component({
selector: 'cmp-d',
template: `<i>{{tagName}}</i>`,
standalone: false,
})
class CmpD {
tagName: string;
constructor(elementRef: ElementRef) {
this.tagName = elementRef.nativeElement.tagName.toLowerCase();
}
}
@Component({
selector: 'cmp-c',
template: `<b>{{tagName}}</b>`,
standalone: false,
})
class CmpC {
tagName: string;
constructor(elementRef: ElementRef) {
this.tagName = elementRef.nativeElement.tagName.toLowerCase();
}
}
@Component({
selector: 'cmp-b',
template: `<ng-content></ng-content><cmp-d></cmp-d>`,
standalone: false,
})
class CmpB {}
@Component({
selector: 'cmp-a',
template: `<ng-content></ng-content><cmp-c></cmp-c>`,
standalone: false,
})
class CmpA {}
@Component({
selector: 'cmp-b11',
template: `{{'b11'}}`,
standalone: false,
})
class CmpB11 {}
@Component({
selector: 'cmp-b12',
template: `{{'b12'}}`,
standalone: false,
})
class CmpB12 {}
@Component({
selector: 'cmp-b21',
template: `{{'b21'}}`,
standalone: false,
})
class CmpB21 {}
@Component({
selector: 'cmp-b22',
template: `{{'b22'}}`,
standalone: false,
})
class CmpB22 {}
@Component({
selector: 'cmp-a1',
template: `{{'a1'}}<cmp-b11></cmp-b11><cmp-b12></cmp-b12>`,
standalone: false,
})
class CmpA1 {}
@Component({
selector: 'cmp-a2',
template: `{{'a2'}}<cmp-b21></cmp-b21><cmp-b22></cmp-b22>`,
standalone: false,
})
class CmpA2 {}
| {
"end_byte": 35282,
"start_byte": 33690,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/projection_integration_spec.ts"
} |
angular/packages/core/test/linker/view_injector_integration_spec.ts_0_7152 | /**
* @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 {
Attribute,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
createComponent as coreCreateComponent,
createEnvironmentInjector,
DebugElement,
Directive,
ElementRef,
EmbeddedViewRef,
EnvironmentInjector,
Host,
Inject,
InjectionToken,
Injector,
Input,
NgModule,
Optional,
Pipe,
PipeTransform,
Provider,
Self,
SkipSelf,
TemplateRef,
Type,
ViewContainerRef,
} from '@angular/core';
import {ComponentFixture, fakeAsync, TestBed} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers';
@Directive({
selector: '[simpleDirective]',
standalone: false,
})
class SimpleDirective {
@Input('simpleDirective') value: any = null;
}
@Component({
selector: '[simpleComponent]',
template: '',
standalone: false,
})
class SimpleComponent {}
@Directive({
selector: '[someOtherDirective]',
standalone: false,
})
class SomeOtherDirective {}
@Directive({
selector: '[cycleDirective]',
standalone: false,
})
class CycleDirective {
constructor(self: CycleDirective) {}
}
@Directive({
selector: '[needsDirectiveFromSelf]',
standalone: false,
})
class NeedsDirectiveFromSelf {
dependency: SimpleDirective;
constructor(@Self() dependency: SimpleDirective) {
this.dependency = dependency;
}
}
@Directive({
selector: '[optionallyNeedsDirective]',
standalone: false,
})
class OptionallyNeedsDirective {
dependency: SimpleDirective;
constructor(@Self() @Optional() dependency: SimpleDirective) {
this.dependency = dependency;
}
}
@Directive({
selector: '[needsComponentFromHost]',
standalone: false,
})
class NeedsComponentFromHost {
dependency: SimpleComponent;
constructor(@Host() dependency: SimpleComponent) {
this.dependency = dependency;
}
}
@Directive({
selector: '[needsDirectiveFromHost]',
standalone: false,
})
class NeedsDirectiveFromHost {
dependency: SimpleDirective;
constructor(@Host() dependency: SimpleDirective) {
this.dependency = dependency;
}
}
@Directive({
selector: '[needsDirective]',
standalone: false,
})
class NeedsDirective {
dependency: SimpleDirective;
constructor(dependency: SimpleDirective) {
this.dependency = dependency;
}
}
@Directive({
selector: '[needsService]',
standalone: false,
})
class NeedsService {
service: any;
constructor(@Inject('service') service: any) {
this.service = service;
}
}
@Directive({
selector: '[needsAppService]',
standalone: false,
})
class NeedsAppService {
service: any;
constructor(@Inject('appService') service: any) {
this.service = service;
}
}
@Component({
selector: '[needsHostAppService]',
template: '',
standalone: false,
})
class NeedsHostAppService {
service: any;
constructor(@Host() @Inject('appService') service: any) {
this.service = service;
}
}
@Component({
selector: '[needsServiceComponent]',
template: '',
standalone: false,
})
class NeedsServiceComponent {
service: any;
constructor(@Inject('service') service: any) {
this.service = service;
}
}
@Directive({
selector: '[needsServiceFromHost]',
standalone: false,
})
class NeedsServiceFromHost {
service: any;
constructor(@Host() @Inject('service') service: any) {
this.service = service;
}
}
@Directive({
selector: '[needsAttribute]',
standalone: false,
})
class NeedsAttribute {
typeAttribute: any;
titleAttribute: any;
fooAttribute: any;
constructor(
@Attribute('type') typeAttribute: String,
@Attribute('title') titleAttribute: String,
@Attribute('foo') fooAttribute: String,
) {
this.typeAttribute = typeAttribute;
this.titleAttribute = titleAttribute;
this.fooAttribute = fooAttribute;
}
}
@Directive({
selector: '[needsAttributeNoType]',
standalone: false,
})
class NeedsAttributeNoType {
constructor(@Attribute('foo') public fooAttribute: any) {}
}
@Directive({
selector: '[needsElementRef]',
standalone: false,
})
class NeedsElementRef {
constructor(public elementRef: ElementRef) {}
}
@Directive({
selector: '[needsViewContainerRef]',
standalone: false,
})
class NeedsViewContainerRef {
constructor(public viewContainer: ViewContainerRef) {}
}
@Directive({
selector: '[needsTemplateRef]',
standalone: false,
})
class NeedsTemplateRef {
constructor(public templateRef: TemplateRef<Object>) {}
}
@Directive({
selector: '[optionallyNeedsTemplateRef]',
standalone: false,
})
class OptionallyNeedsTemplateRef {
constructor(@Optional() public templateRef: TemplateRef<Object>) {}
}
@Directive({
selector: '[directiveNeedsChangeDetectorRef]',
standalone: false,
})
class DirectiveNeedsChangeDetectorRef {
constructor(public changeDetectorRef: ChangeDetectorRef) {}
}
@Component({
selector: '[componentNeedsChangeDetectorRef]',
template: '{{counter}}',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
class PushComponentNeedsChangeDetectorRef {
counter: number = 0;
constructor(public changeDetectorRef: ChangeDetectorRef) {}
}
@Pipe({
name: 'purePipe',
pure: true,
standalone: false,
})
class PurePipe implements PipeTransform {
constructor() {}
transform(value: any): any {
return this;
}
}
@Pipe({
name: 'impurePipe',
pure: false,
standalone: false,
})
class ImpurePipe implements PipeTransform {
constructor() {}
transform(value: any): any {
return this;
}
}
@Pipe({
name: 'pipeNeedsChangeDetectorRef',
standalone: false,
})
class PipeNeedsChangeDetectorRef {
constructor(public changeDetectorRef: ChangeDetectorRef) {}
transform(value: any): any {
return this;
}
}
@Pipe({
name: 'pipeNeedsService',
standalone: false,
})
export class PipeNeedsService implements PipeTransform {
service: any;
constructor(@Inject('service') service: any) {
this.service = service;
}
transform(value: any): any {
return this;
}
}
@Pipe({
name: 'duplicatePipe',
standalone: false,
})
export class DuplicatePipe1 implements PipeTransform {
transform(value: any): any {
return this;
}
}
@Pipe({
name: 'duplicatePipe',
standalone: false,
})
export class DuplicatePipe2 implements PipeTransform {
transform(value: any): any {
return this;
}
}
@Component({
selector: 'root',
template: '',
standalone: false,
})
class TestComp {}
function createComponentFixture<T>(
template: string,
providers?: Provider[] | null,
comp?: Type<T>,
): ComponentFixture<T> {
if (!comp) {
comp = <any>TestComp;
}
TestBed.overrideComponent(comp!, {set: {template}});
if (providers && providers.length) {
TestBed.overrideComponent(comp!, {add: {providers: providers}});
}
return TestBed.createComponent(comp!);
}
function createComponent(template: string, providers?: Provider[], comp?: Type<any>): DebugElement {
const fixture = createComponentFixture(template, providers, comp);
fixture.detectChanges();
return fixture.debugElement;
} | {
"end_byte": 7152,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/view_injector_integration_spec.ts"
} |
angular/packages/core/test/linker/view_injector_integration_spec.ts_7154_15111 | describe('View injector', () => {
const TOKEN = new InjectionToken<string>('token');
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestComp],
providers: [
{provide: TOKEN, useValue: 'appService'},
{provide: 'appService', useFactory: (v: string) => v, deps: [TOKEN]},
],
});
});
describe('injection', () => {
it('should instantiate directives that have no dependencies', () => {
TestBed.configureTestingModule({declarations: [SimpleDirective]});
const el = createComponent('<div simpleDirective>');
expect(el.children[0].injector.get(SimpleDirective)).toBeInstanceOf(SimpleDirective);
});
it('should instantiate directives that depend on another directive', () => {
TestBed.configureTestingModule({declarations: [SimpleDirective, NeedsDirective]});
const el = createComponent('<div simpleDirective needsDirective>');
const d = el.children[0].injector.get(NeedsDirective);
expect(d).toBeInstanceOf(NeedsDirective);
expect(d.dependency).toBeInstanceOf(SimpleDirective);
});
it('should support useValue with different values', () => {
const el = createComponent('', [
{provide: 'numLiteral', useValue: 0},
{provide: 'boolLiteral', useValue: true},
{provide: 'strLiteral', useValue: 'a'},
{provide: 'null', useValue: null},
{provide: 'array', useValue: [1]},
{provide: 'map', useValue: {'a': 1}},
{provide: 'instance', useValue: new TestValue('a')},
{provide: 'nested', useValue: [{'a': [1]}, new TestValue('b')]},
]);
expect(el.injector.get('numLiteral')).toBe(0);
expect(el.injector.get('boolLiteral')).toBe(true);
expect(el.injector.get('strLiteral')).toBe('a');
expect(el.injector.get('null')).toBe(null);
expect(el.injector.get('array')).toEqual([1]);
expect(el.injector.get('map')).toEqual({'a': 1});
expect(el.injector.get('instance')).toEqual(new TestValue('a'));
expect(el.injector.get('nested')).toEqual([{'a': [1]}, new TestValue('b')]);
});
it('should instantiate providers that have dependencies with SkipSelf', () => {
TestBed.configureTestingModule({declarations: [SimpleDirective, SomeOtherDirective]});
TestBed.overrideDirective(SimpleDirective, {
add: {providers: [{provide: 'injectable1', useValue: 'injectable1'}]},
});
TestBed.overrideDirective(SomeOtherDirective, {
add: {
providers: [
{provide: 'injectable1', useValue: 'new-injectable1'},
{
provide: 'injectable2',
useFactory: (val: any) => `${val}-injectable2`,
deps: [[new Inject('injectable1'), new SkipSelf()]],
},
],
},
});
const el = createComponent('<div simpleDirective><span someOtherDirective></span></div>');
expect(el.children[0].children[0].injector.get('injectable2')).toEqual(
'injectable1-injectable2',
);
});
it('should instantiate providers that have dependencies', () => {
TestBed.configureTestingModule({declarations: [SimpleDirective]});
const providers = [
{provide: 'injectable1', useValue: 'injectable1'},
{
provide: 'injectable2',
useFactory: (val: any) => `${val}-injectable2`,
deps: ['injectable1'],
},
];
TestBed.overrideDirective(SimpleDirective, {add: {providers}});
const el = createComponent('<div simpleDirective></div>');
expect(el.children[0].injector.get('injectable2')).toEqual('injectable1-injectable2');
});
it('should instantiate viewProviders that have dependencies', () => {
TestBed.configureTestingModule({declarations: [SimpleComponent]});
const viewProviders = [
{provide: 'injectable1', useValue: 'injectable1'},
{
provide: 'injectable2',
useFactory: (val: any) => `${val}-injectable2`,
deps: ['injectable1'],
},
];
TestBed.overrideComponent(SimpleComponent, {set: {viewProviders}});
const el = createComponent('<div simpleComponent></div>');
expect(el.children[0].injector.get('injectable2')).toEqual('injectable1-injectable2');
});
it('should instantiate components that depend on viewProviders providers', () => {
TestBed.configureTestingModule({declarations: [NeedsServiceComponent]});
TestBed.overrideComponent(NeedsServiceComponent, {
set: {providers: [{provide: 'service', useValue: 'service'}]},
});
const el = createComponent('<div needsServiceComponent></div>');
expect(el.children[0].injector.get(NeedsServiceComponent).service).toEqual('service');
});
it('should instantiate multi providers', () => {
TestBed.configureTestingModule({declarations: [SimpleDirective]});
const providers = [
{provide: 'injectable1', useValue: 'injectable11', multi: true},
{provide: 'injectable1', useValue: 'injectable12', multi: true},
];
TestBed.overrideDirective(SimpleDirective, {set: {providers}});
const el = createComponent('<div simpleDirective></div>');
expect(el.children[0].injector.get('injectable1')).toEqual(['injectable11', 'injectable12']);
});
it('should instantiate providers lazily', () => {
TestBed.configureTestingModule({declarations: [SimpleDirective]});
let created = false;
TestBed.overrideDirective(SimpleDirective, {
set: {providers: [{provide: 'service', useFactory: () => (created = true)}]},
});
const el = createComponent('<div simpleDirective></div>');
expect(created).toBe(false);
el.children[0].injector.get('service');
expect(created).toBe(true);
});
it('should provide undefined', () => {
let factoryCounter = 0;
const el = createComponent('', [
{
provide: 'token',
useFactory: () => {
factoryCounter++;
return undefined;
},
},
]);
expect(el.injector.get('token')).toBeUndefined();
expect(el.injector.get('token')).toBeUndefined();
expect(factoryCounter).toBe(1);
});
describe('injecting lazy providers into an eager provider via Injector.get', () => {
it('should inject providers that were declared before it', () => {
@Component({
template: '',
providers: [
{provide: 'lazy', useFactory: () => 'lazyValue'},
{
provide: 'eager',
useFactory: (i: Injector) => `eagerValue: ${i.get('lazy')}`,
deps: [Injector],
},
],
standalone: false,
})
class MyComp {
// Component is eager, which makes all of its deps eager
constructor(@Inject('eager') eager: any) {}
}
const ctx = TestBed.configureTestingModule({declarations: [MyComp]}).createComponent(
MyComp,
);
expect(ctx.debugElement.injector.get('eager')).toBe('eagerValue: lazyValue');
});
it('should inject providers that were declared after it', () => {
@Component({
template: '',
providers: [
{
provide: 'eager',
useFactory: (i: Injector) => `eagerValue: ${i.get('lazy')}`,
deps: [Injector],
},
{provide: 'lazy', useFactory: () => 'lazyValue'},
],
standalone: false,
})
class MyComp {
// Component is eager, which makes all of its deps eager
constructor(@Inject('eager') eager: any) {}
}
const ctx = TestBed.configureTestingModule({declarations: [MyComp]}).createComponent(
MyComp,
);
expect(ctx.debugElement.injector.get('eager')).toBe('eagerValue: lazyValue');
});
}); | {
"end_byte": 15111,
"start_byte": 7154,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/view_injector_integration_spec.ts"
} |
angular/packages/core/test/linker/view_injector_integration_spec.ts_15117_23556 | describe('injecting eager providers into an eager provider via Injector.get', () => {
it('should inject providers that were declared before it', () => {
@Component({
template: '',
providers: [
{provide: 'eager1', useFactory: () => 'v1'},
{
provide: 'eager2',
useFactory: (i: Injector) => `v2: ${i.get('eager1')}`,
deps: [Injector],
},
],
standalone: false,
})
class MyComp {
// Component is eager, which makes all of its deps eager
constructor(@Inject('eager1') eager1: any, @Inject('eager2') eager2: any) {}
}
const ctx = TestBed.configureTestingModule({declarations: [MyComp]}).createComponent(
MyComp,
);
expect(ctx.debugElement.injector.get('eager2')).toBe('v2: v1');
});
it('should inject providers that were declared after it', () => {
@Component({
template: '',
providers: [
{
provide: 'eager1',
useFactory: (i: Injector) => `v1: ${i.get('eager2')}`,
deps: [Injector],
},
{provide: 'eager2', useFactory: () => 'v2'},
],
standalone: false,
})
class MyComp {
// Component is eager, which makes all of its deps eager
constructor(@Inject('eager1') eager1: any, @Inject('eager2') eager2: any) {}
}
const ctx = TestBed.configureTestingModule({declarations: [MyComp]}).createComponent(
MyComp,
);
expect(ctx.debugElement.injector.get('eager1')).toBe('v1: v2');
});
});
it('should allow injecting lazy providers via Injector.get from an eager provider that is declared earlier', () => {
@Component({
providers: [{provide: 'a', useFactory: () => 'aValue'}],
template: '',
standalone: false,
})
class SomeComponent {
public a: string;
constructor(injector: Injector) {
this.a = injector.get('a');
}
}
const comp = TestBed.configureTestingModule({declarations: [SomeComponent]}).createComponent(
SomeComponent,
);
expect(comp.componentInstance.a).toBe('aValue');
});
it('should support ngOnDestroy for lazy providers', () => {
let created = false;
let destroyed = false;
class SomeInjectable {
constructor() {
created = true;
}
ngOnDestroy() {
destroyed = true;
}
}
@Component({
providers: [SomeInjectable],
template: '',
standalone: false,
})
class SomeComp {}
TestBed.configureTestingModule({declarations: [SomeComp]});
let compRef = TestBed.createComponent(SomeComp).componentRef;
expect(created).toBe(false);
expect(destroyed).toBe(false);
// no error if the provider was not yet created
compRef.destroy();
expect(created).toBe(false);
expect(destroyed).toBe(false);
compRef = TestBed.createComponent(SomeComp).componentRef;
compRef.injector.get(SomeInjectable);
expect(created).toBe(true);
compRef.destroy();
expect(destroyed).toBe(true);
});
it('should instantiate view providers lazily', () => {
let created = false;
TestBed.configureTestingModule({declarations: [SimpleComponent]});
TestBed.overrideComponent(SimpleComponent, {
set: {viewProviders: [{provide: 'service', useFactory: () => (created = true)}]},
});
const el = createComponent('<div simpleComponent></div>');
expect(created).toBe(false);
el.children[0].injector.get('service');
expect(created).toBe(true);
});
it('should not instantiate other directives that depend on viewProviders providers (same element)', () => {
TestBed.configureTestingModule({declarations: [SimpleComponent, NeedsService]});
TestBed.overrideComponent(SimpleComponent, {
set: {viewProviders: [{provide: 'service', useValue: 'service'}]},
});
expect(() => createComponent('<div simpleComponent needsService></div>')).toThrowError(
/No provider for service!/,
);
});
it('should not instantiate other directives that depend on viewProviders providers (child element)', () => {
TestBed.configureTestingModule({declarations: [SimpleComponent, NeedsService]});
TestBed.overrideComponent(SimpleComponent, {
set: {viewProviders: [{provide: 'service', useValue: 'service'}]},
});
expect(() =>
createComponent('<div simpleComponent><div needsService></div></div>'),
).toThrowError(/No provider for service!/);
});
it('should instantiate directives that depend on providers of other directives', () => {
TestBed.configureTestingModule({declarations: [SimpleDirective, NeedsService]});
TestBed.overrideDirective(SimpleDirective, {
set: {providers: [{provide: 'service', useValue: 'parentService'}]},
});
const el = createComponent('<div simpleDirective><div needsService></div></div>');
expect(el.children[0].children[0].injector.get(NeedsService).service).toEqual(
'parentService',
);
});
it('should instantiate directives that depend on providers in a parent view', () => {
TestBed.configureTestingModule({declarations: [SimpleDirective, NeedsService]});
TestBed.overrideDirective(SimpleDirective, {
set: {providers: [{provide: 'service', useValue: 'parentService'}]},
});
const el = createComponent(
'<div simpleDirective><ng-container *ngIf="true"><div *ngIf="true" needsService></div></ng-container></div>',
);
expect(el.children[0].children[0].injector.get(NeedsService).service).toEqual(
'parentService',
);
});
it('should instantiate directives that depend on providers of a component', () => {
TestBed.configureTestingModule({declarations: [SimpleComponent, NeedsService]});
TestBed.overrideComponent(SimpleComponent, {
set: {providers: [{provide: 'service', useValue: 'hostService'}]},
});
TestBed.overrideComponent(SimpleComponent, {set: {template: '<div needsService></div>'}});
const el = createComponent('<div simpleComponent></div>');
expect(el.children[0].children[0].injector.get(NeedsService).service).toEqual('hostService');
});
it('should instantiate directives that depend on view providers of a component', () => {
TestBed.configureTestingModule({declarations: [SimpleComponent, NeedsService]});
TestBed.overrideComponent(SimpleComponent, {
set: {providers: [{provide: 'service', useValue: 'hostService'}]},
});
TestBed.overrideComponent(SimpleComponent, {set: {template: '<div needsService></div>'}});
const el = createComponent('<div simpleComponent></div>');
expect(el.children[0].children[0].injector.get(NeedsService).service).toEqual('hostService');
});
it('should instantiate directives in a root embedded view that depend on view providers of a component', () => {
TestBed.configureTestingModule({declarations: [SimpleComponent, NeedsService]});
TestBed.overrideComponent(SimpleComponent, {
set: {providers: [{provide: 'service', useValue: 'hostService'}]},
});
TestBed.overrideComponent(SimpleComponent, {
set: {template: '<div *ngIf="true" needsService></div>'},
});
const el = createComponent('<div simpleComponent></div>');
expect(el.children[0].children[0].injector.get(NeedsService).service).toEqual('hostService');
});
it('should instantiate directives that depend on instances in the app injector', () => {
TestBed.configureTestingModule({declarations: [NeedsAppService]});
const el = createComponent('<div needsAppService></div>');
expect(el.children[0].injector.get(NeedsAppService).service).toEqual('appService');
});
it('should not instantiate a directive with cyclic dependencies', () => {
TestBed.configureTestingModule({declarations: [CycleDirective]});
expect(() => createComponent('<div cycleDirective></div>')).toThrowError(
'NG0200: Circular dependency in DI detected for CycleDirective. Find more at https://angular.dev/errors/NG0200',
);
}); | {
"end_byte": 23556,
"start_byte": 15117,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/view_injector_integration_spec.ts"
} |
angular/packages/core/test/linker/view_injector_integration_spec.ts_23562_29254 | it(
'should not instantiate a directive in a view that has a host dependency on providers' +
' of the component',
() => {
TestBed.configureTestingModule({declarations: [SimpleComponent, NeedsServiceFromHost]});
TestBed.overrideComponent(SimpleComponent, {
set: {providers: [{provide: 'service', useValue: 'hostService'}]},
});
TestBed.overrideComponent(SimpleComponent, {
set: {template: '<div needsServiceFromHost><div>'},
});
expect(() => createComponent('<div simpleComponent></div>')).toThrowError(
'NG0201: No provider for service found in NodeInjector. Find more at https://angular.dev/errors/NG0201',
);
},
);
it(
'should not instantiate a directive in a view that has a host dependency on providers' +
' of a decorator directive',
() => {
TestBed.configureTestingModule({
declarations: [SimpleComponent, SomeOtherDirective, NeedsServiceFromHost],
});
TestBed.overrideComponent(SimpleComponent, {
set: {providers: [{provide: 'service', useValue: 'hostService'}]},
});
TestBed.overrideComponent(SimpleComponent, {
set: {template: '<div needsServiceFromHost><div>'},
});
expect(() =>
createComponent('<div simpleComponent someOtherDirective></div>'),
).toThrowError(
'NG0201: No provider for service found in NodeInjector. Find more at https://angular.dev/errors/NG0201',
);
},
);
it('should not instantiate a directive in a view that has a self dependency on a parent directive', () => {
TestBed.configureTestingModule({declarations: [SimpleDirective, NeedsDirectiveFromSelf]});
expect(() =>
createComponent('<div simpleDirective><div needsDirectiveFromSelf></div></div>'),
).toThrowError(
'NG0201: No provider for SimpleDirective found in NodeInjector. Find more at https://angular.dev/errors/NG0201',
);
});
it('should instantiate directives that depend on other directives', fakeAsync(() => {
TestBed.configureTestingModule({declarations: [SimpleDirective, NeedsDirective]});
const el = createComponent('<div simpleDirective><div needsDirective></div></div>');
const d = el.children[0].children[0].injector.get(NeedsDirective);
expect(d).toBeInstanceOf(NeedsDirective);
expect(d.dependency).toBeInstanceOf(SimpleDirective);
}));
it('should throw when a dependency cannot be resolved', fakeAsync(() => {
TestBed.configureTestingModule({declarations: [NeedsService]});
expect(() => createComponent('<div needsService></div>')).toThrowError(
/No provider for service!/,
);
}));
it('should inject null when an optional dependency cannot be resolved', () => {
TestBed.configureTestingModule({declarations: [OptionallyNeedsDirective]});
const el = createComponent('<div optionallyNeedsDirective></div>');
const d = el.children[0].injector.get(OptionallyNeedsDirective);
expect(d.dependency).toBeNull();
});
it('should instantiate directives that depends on the host component', () => {
TestBed.configureTestingModule({declarations: [SimpleComponent, NeedsComponentFromHost]});
TestBed.overrideComponent(SimpleComponent, {
set: {template: '<div needsComponentFromHost></div>'},
});
const el = createComponent('<div simpleComponent></div>');
const d = el.children[0].children[0].injector.get(NeedsComponentFromHost);
expect(d.dependency).toBeInstanceOf(SimpleComponent);
});
it('should not instantiate directives that depend on other directives on the host element', () => {
TestBed.configureTestingModule({
declarations: [SimpleComponent, SimpleDirective, NeedsDirectiveFromHost],
});
TestBed.overrideComponent(SimpleComponent, {
set: {template: '<div needsDirectiveFromHost></div>'},
});
expect(() => createComponent('<div simpleComponent simpleDirective></div>')).toThrowError(
'NG0201: No provider for SimpleDirective found in NodeInjector. Find more at https://angular.dev/errors/NG0201',
);
});
it('should allow to use the NgModule injector from a root ViewContainerRef.parentInjector', () => {
@Component({
template: '',
standalone: false,
})
class MyComp {
constructor(public vc: ViewContainerRef) {}
}
const compFixture = TestBed.configureTestingModule({
declarations: [MyComp],
providers: [{provide: 'someToken', useValue: 'someValue'}],
}).createComponent(MyComp);
expect(compFixture.componentInstance.vc.parentInjector.get('someToken')).toBe('someValue');
});
});
describe('static attributes', () => {
it('should be injectable', () => {
TestBed.configureTestingModule({declarations: [NeedsAttribute]});
const el = createComponent('<div needsAttribute type="text" title></div>');
const needsAttribute = el.children[0].injector.get(NeedsAttribute);
expect(needsAttribute.typeAttribute).toEqual('text');
expect(needsAttribute.titleAttribute).toEqual('');
expect(needsAttribute.fooAttribute).toEqual(null);
});
it('should be injectable without type annotation', () => {
TestBed.configureTestingModule({declarations: [NeedsAttributeNoType]});
const el = createComponent('<div needsAttributeNoType foo="bar"></div>');
const needsAttribute = el.children[0].injector.get(NeedsAttributeNoType);
expect(needsAttribute.fooAttribute).toEqual('bar');
});
}); | {
"end_byte": 29254,
"start_byte": 23562,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/view_injector_integration_spec.ts"
} |
angular/packages/core/test/linker/view_injector_integration_spec.ts_29258_35986 | describe('refs', () => {
it('should inject ElementRef', () => {
TestBed.configureTestingModule({declarations: [NeedsElementRef]});
const el = createComponent('<div needsElementRef></div>');
expect(el.children[0].injector.get(NeedsElementRef).elementRef.nativeElement).toBe(
el.children[0].nativeElement,
);
});
it("should inject ChangeDetectorRef of the component's view into the component", () => {
TestBed.configureTestingModule({declarations: [PushComponentNeedsChangeDetectorRef]});
const cf = createComponentFixture('<div componentNeedsChangeDetectorRef></div>');
cf.detectChanges();
const compEl = cf.debugElement.children[0];
const comp = compEl.injector.get(PushComponentNeedsChangeDetectorRef);
comp.counter = 1;
cf.detectChanges();
expect(compEl.nativeElement).toHaveText('0');
comp.changeDetectorRef.markForCheck();
cf.detectChanges();
expect(compEl.nativeElement).toHaveText('1');
});
it('should inject ChangeDetectorRef of the containing component into directives', () => {
TestBed.configureTestingModule({
declarations: [PushComponentNeedsChangeDetectorRef, DirectiveNeedsChangeDetectorRef],
});
TestBed.overrideComponent(PushComponentNeedsChangeDetectorRef, {
set: {
template:
'{{counter}}<div directiveNeedsChangeDetectorRef></div><div *ngIf="true" directiveNeedsChangeDetectorRef></div>',
},
});
const cf = createComponentFixture('<div componentNeedsChangeDetectorRef></div>');
cf.detectChanges();
const compEl = cf.debugElement.children[0];
const comp: PushComponentNeedsChangeDetectorRef = compEl.injector.get(
PushComponentNeedsChangeDetectorRef,
);
comp.counter = 1;
cf.detectChanges();
expect(compEl.nativeElement).toHaveText('0');
/**
* Compares two `ChangeDetectorRef` instances. The logic depends on the engine, as the
* implementation details of `ViewRef` vary.
*/
function _compareChangeDetectorRefs(a: ChangeDetectorRef, b: ChangeDetectorRef) {
expect((a as any)._lView).toEqual((b as any)._lView);
expect((a as any).context).toEqual((b as any).context);
}
_compareChangeDetectorRefs(
compEl.children[0].injector.get(DirectiveNeedsChangeDetectorRef).changeDetectorRef,
comp.changeDetectorRef,
);
_compareChangeDetectorRefs(
compEl.children[1].injector.get(DirectiveNeedsChangeDetectorRef).changeDetectorRef,
comp.changeDetectorRef,
);
comp.changeDetectorRef.markForCheck();
cf.detectChanges();
expect(compEl.nativeElement).toHaveText('1');
});
it('should inject ChangeDetectorRef of a same element component into a directive', () => {
TestBed.configureTestingModule({
declarations: [PushComponentNeedsChangeDetectorRef, DirectiveNeedsChangeDetectorRef],
});
const cf = createComponentFixture(
'<div componentNeedsChangeDetectorRef directiveNeedsChangeDetectorRef></div>',
);
cf.detectChanges();
const compEl = cf.debugElement.children[0];
const comp = compEl.injector.get(PushComponentNeedsChangeDetectorRef);
const dir = compEl.injector.get(DirectiveNeedsChangeDetectorRef);
comp.counter = 1;
cf.detectChanges();
expect(compEl.nativeElement).toHaveText('0');
dir.changeDetectorRef.markForCheck();
cf.detectChanges();
expect(compEl.nativeElement).toHaveText('1');
});
it(`should not inject ChangeDetectorRef of a parent element's component into a directive`, () => {
TestBed.configureTestingModule({
declarations: [PushComponentNeedsChangeDetectorRef, DirectiveNeedsChangeDetectorRef],
}).overrideComponent(PushComponentNeedsChangeDetectorRef, {
set: {template: '<ng-content></ng-content>{{counter}}'},
});
const cf = createComponentFixture(
'<div componentNeedsChangeDetectorRef><div directiveNeedsChangeDetectorRef></div></div>',
);
cf.detectChanges();
const compEl = cf.debugElement.children[0];
const comp = compEl.injector.get(PushComponentNeedsChangeDetectorRef);
const dirEl = compEl.children[0];
const dir = dirEl.injector.get(DirectiveNeedsChangeDetectorRef);
comp.counter = 1;
cf.detectChanges();
expect(compEl.nativeElement).toHaveText('0');
dir.changeDetectorRef.markForCheck();
cf.detectChanges();
expect(compEl.nativeElement).toHaveText('0');
});
it('should inject ViewContainerRef', () => {
TestBed.configureTestingModule({declarations: [NeedsViewContainerRef]});
const el = createComponent('<div needsViewContainerRef></div>');
expect(
el.children[0].injector.get(NeedsViewContainerRef).viewContainer.element.nativeElement,
).toBe(el.children[0].nativeElement);
});
it('should inject ViewContainerRef', () => {
@Component({
template: '',
standalone: false,
})
class TestComp {
constructor(public vcr: ViewContainerRef) {}
}
TestBed.configureTestingModule({declarations: [TestComp]});
const environmentInjector = createEnvironmentInjector(
[{provide: 'someToken', useValue: 'someNewValue'}],
TestBed.inject(EnvironmentInjector),
);
const component = coreCreateComponent(TestComp, {environmentInjector});
expect(component.instance.vcr.parentInjector.get('someToken')).toBe('someNewValue');
});
it('should inject TemplateRef', () => {
TestBed.configureTestingModule({declarations: [NeedsViewContainerRef, NeedsTemplateRef]});
const el = createComponent(
'<ng-template needsViewContainerRef needsTemplateRef></ng-template>',
);
expect(el.childNodes[0].injector.get(NeedsTemplateRef).templateRef.elementRef).toEqual(
el.childNodes[0].injector.get(NeedsViewContainerRef).viewContainer.element,
);
});
it('should throw if there is no TemplateRef', () => {
TestBed.configureTestingModule({declarations: [NeedsTemplateRef]});
expect(() => createComponent('<div needsTemplateRef></div>')).toThrowError(
/No provider for TemplateRef/,
);
});
it('should inject null if there is no TemplateRef when the dependency is optional', () => {
TestBed.configureTestingModule({declarations: [OptionallyNeedsTemplateRef]});
const el = createComponent('<div optionallyNeedsTemplateRef></div>');
const instance = el.children[0].injector.get(OptionallyNeedsTemplateRef);
expect(instance.templateRef).toBeNull();
});
}); | {
"end_byte": 35986,
"start_byte": 29258,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/view_injector_integration_spec.ts"
} |
angular/packages/core/test/linker/view_injector_integration_spec.ts_35990_40108 | describe('pipes', () => {
it('should instantiate pipes that have dependencies', () => {
TestBed.configureTestingModule({declarations: [SimpleDirective, PipeNeedsService]});
const el = createComponent('<div [simpleDirective]="true | pipeNeedsService"></div>', [
{provide: 'service', useValue: 'pipeService'},
]);
expect(el.children[0].injector.get(SimpleDirective).value.service).toEqual('pipeService');
});
it('should overwrite pipes with later entry in the pipes array', () => {
TestBed.configureTestingModule({
declarations: [SimpleDirective, DuplicatePipe1, DuplicatePipe2],
});
const el = createComponent('<div [simpleDirective]="true | duplicatePipe"></div>');
expect(el.children[0].injector.get(SimpleDirective).value).toBeInstanceOf(DuplicatePipe2);
});
it('should inject ChangeDetectorRef into pipes', () => {
TestBed.configureTestingModule({
declarations: [
SimpleDirective,
PipeNeedsChangeDetectorRef,
DirectiveNeedsChangeDetectorRef,
],
});
const el = createComponent(
'<div [simpleDirective]="true | pipeNeedsChangeDetectorRef" directiveNeedsChangeDetectorRef></div>',
);
const cdRef = el.children[0].injector.get(DirectiveNeedsChangeDetectorRef).changeDetectorRef;
expect(el.children[0].injector.get(SimpleDirective).value.changeDetectorRef).toEqual(cdRef);
});
it('should not cache impure pipes', () => {
TestBed.configureTestingModule({declarations: [SimpleDirective, ImpurePipe]});
const el = createComponent(
'<div [simpleDirective]="true | impurePipe"></div><div [simpleDirective]="true | impurePipe"></div>' +
'<div *ngFor="let x of [1,2]" [simpleDirective]="true | impurePipe"></div>',
);
const impurePipe1 = el.children[0].injector.get(SimpleDirective).value;
const impurePipe2 = el.children[1].injector.get(SimpleDirective).value;
const impurePipe3 = el.children[2].injector.get(SimpleDirective).value;
const impurePipe4 = el.children[3].injector.get(SimpleDirective).value;
expect(impurePipe1).toBeInstanceOf(ImpurePipe);
expect(impurePipe2).toBeInstanceOf(ImpurePipe);
expect(impurePipe2).not.toBe(impurePipe1);
expect(impurePipe3).toBeInstanceOf(ImpurePipe);
expect(impurePipe3).not.toBe(impurePipe1);
expect(impurePipe4).toBeInstanceOf(ImpurePipe);
expect(impurePipe4).not.toBe(impurePipe1);
});
});
describe('view destruction', () => {
@Component({
selector: 'some-component',
template: '',
standalone: false,
})
class SomeComponent {}
@Component({
selector: 'listener-and-on-destroy',
template: '',
standalone: false,
})
class ComponentThatLoadsAnotherComponentThenMovesIt {
constructor(private viewContainerRef: ViewContainerRef) {}
ngOnInit() {
// Dynamically load some component.
const componentRef = this.viewContainerRef.createComponent(SomeComponent, {
index: this.viewContainerRef.length,
});
// Manually move the loaded component to some arbitrary DOM node.
const componentRootNode = (componentRef.hostView as EmbeddedViewRef<any>)
.rootNodes[0] as HTMLElement;
document.createElement('div').appendChild(componentRootNode);
// Destroy the component we just moved to ensure that it does not error during
// destruction.
componentRef.destroy();
}
}
it('should not error when destroying a component that has been moved in the DOM', () => {
TestBed.configureTestingModule({
declarations: [ComponentThatLoadsAnotherComponentThenMovesIt, SomeComponent],
});
const fixture = createComponentFixture(`<listener-and-on-destroy></listener-and-on-destroy>`);
fixture.detectChanges();
// This test will fail if the ngOnInit of ComponentThatLoadsAnotherComponentThenMovesIt
// throws an error.
});
});
});
class TestValue {
constructor(public value: string) {}
} | {
"end_byte": 40108,
"start_byte": 35990,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/view_injector_integration_spec.ts"
} |
angular/packages/core/test/linker/resource_loader_mock.ts_0_4030 | /**
* @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 {ResourceLoader} from '@angular/compiler';
/**
* A mock implementation of {@link ResourceLoader} that allows outgoing requests to be mocked
* and responded to within a single test, without going to the network.
*/
export class MockResourceLoader extends ResourceLoader {
private _expectations: _Expectation[] = [];
private _definitions = new Map<string, string>();
private _requests: _PendingRequest[] = [];
override get(url: string): Promise<string> {
const request = new _PendingRequest(url);
this._requests.push(request);
return request.getPromise();
}
hasPendingRequests() {
return !!this._requests.length;
}
/**
* Add an expectation for the given URL. Incoming requests will be checked against
* the next expectation (in FIFO order). The `verifyNoOutstandingExpectations` method
* can be used to check if any expectations have not yet been met.
*
* The response given will be returned if the expectation matches.
*/
expect(url: string, response: string) {
const expectation = new _Expectation(url, response);
this._expectations.push(expectation);
}
/**
* Add a definition for the given URL to return the given response. Unlike expectations,
* definitions have no order and will satisfy any matching request at any time. Also
* unlike expectations, unused definitions do not cause `verifyNoOutstandingExpectations`
* to return an error.
*/
when(url: string, response: string) {
this._definitions.set(url, response);
}
/**
* Process pending requests and verify there are no outstanding expectations. Also fails
* if no requests are pending.
*/
flush() {
if (this._requests.length === 0) {
throw new Error('No pending requests to flush');
}
do {
this._processRequest(this._requests.shift()!);
} while (this._requests.length > 0);
this.verifyNoOutstandingExpectations();
}
/**
* Throw an exception if any expectations have not been satisfied.
*/
verifyNoOutstandingExpectations() {
if (this._expectations.length === 0) return;
const urls: string[] = [];
for (let i = 0; i < this._expectations.length; i++) {
const expectation = this._expectations[i];
urls.push(expectation.url);
}
throw new Error(`Unsatisfied requests: ${urls.join(', ')}`);
}
private _processRequest(request: _PendingRequest) {
const url = request.url;
if (this._expectations.length > 0) {
const expectation = this._expectations[0];
if (expectation.url == url) {
remove(this._expectations, expectation);
request.complete(expectation.response);
return;
}
}
if (this._definitions.has(url)) {
const response = this._definitions.get(url);
request.complete(response == null ? null : response);
return;
}
throw new Error(`Unexpected request ${url}`);
}
}
class _PendingRequest {
// Using non null assertion, these fields are defined below
// within the `new Promise` callback (synchronously).
resolve!: (result: string) => void;
reject!: (error: any) => void;
promise: Promise<string>;
constructor(public url: string) {
this.promise = new Promise((res, rej) => {
this.resolve = res;
this.reject = rej;
});
}
complete(response: string | null) {
if (response == null) {
this.reject(`Failed to load ${this.url}`);
} else {
this.resolve(response);
}
}
getPromise(): Promise<string> {
return this.promise;
}
}
class _Expectation {
url: string;
response: string;
constructor(url: string, response: string) {
this.url = url;
this.response = response;
}
}
function remove<T>(list: T[], el: T): void {
const index = list.indexOf(el);
if (index > -1) {
list.splice(index, 1);
}
}
| {
"end_byte": 4030,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/resource_loader_mock.ts"
} |
angular/packages/core/test/linker/regression_integration_spec.ts_0_963 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {DOCUMENT, ɵgetDOM as getDOM} from '@angular/common';
import {
ApplicationRef,
Component,
ComponentRef,
ContentChild,
createComponent,
destroyPlatform,
Directive,
EnvironmentInjector,
ErrorHandler,
EventEmitter,
HostListener,
InjectionToken,
Injector,
Input,
NgModule,
NgZone,
Output,
Pipe,
PipeTransform,
Provider,
QueryList,
Renderer2,
SimpleChanges,
TemplateRef,
ViewChildren,
ViewContainerRef,
} from '@angular/core';
import {fakeAsync, inject, TestBed, tick} from '@angular/core/testing';
import {BrowserModule, By} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {expect} from '@angular/platform-browser/testing/src/matchers';
| {
"end_byte": 963,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/regression_integration_spec.ts"
} |
angular/packages/core/test/linker/regression_integration_spec.ts_965_9834 | escribe('regressions', () => {
beforeEach(() => {
TestBed.configureTestingModule({declarations: [MyComp1, PlatformPipe]});
});
describe('platform pipes', () => {
it('should overwrite them by custom pipes', () => {
TestBed.configureTestingModule({declarations: [CustomPipe]});
const template = '{{true | somePipe}}';
TestBed.overrideComponent(MyComp1, {set: {template}});
const fixture = TestBed.createComponent(MyComp1);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('someCustomPipe');
});
});
describe('expressions', () => {
it('should evaluate conditional and boolean operators with right precedence - #8244', () => {
const template = `{{'red' + (true ? ' border' : '')}}`;
TestBed.overrideComponent(MyComp1, {set: {template}});
const fixture = TestBed.createComponent(MyComp1);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('red border');
});
it('should evaluate conditional and unary operators with right precedence - #8235', () => {
const template = `{{!null?.length}}`;
TestBed.overrideComponent(MyComp1, {set: {template}});
const fixture = TestBed.createComponent(MyComp1);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('true');
});
it('should only evaluate stateful pipes once - #10639', () => {
TestBed.configureTestingModule({declarations: [CountingPipe]});
const template = '{{(null|countingPipe)?.value}}';
TestBed.overrideComponent(MyComp1, {set: {template}});
const fixture = TestBed.createComponent(MyComp1);
CountingPipe.reset();
fixture.detectChanges(/* checkNoChanges */ false);
expect(fixture.nativeElement).toHaveText('counting pipe value');
expect(CountingPipe.calls).toBe(1);
});
it('should only update the bound property when using asyncPipe - #15205', fakeAsync(() => {
@Component({
template: '<div myDir [a]="p | async" [b]="2"></div>',
standalone: false,
})
class MyComp {
p = Promise.resolve(1);
}
@Directive({
selector: '[myDir]',
standalone: false,
})
class MyDir {
setterCalls: {[key: string]: any} = {};
changes: SimpleChanges | undefined;
@Input()
set a(v: number) {
this.setterCalls['a'] = v;
}
@Input()
set b(v: number) {
this.setterCalls['b'] = v;
}
ngOnChanges(changes: SimpleChanges) {
this.changes = changes;
}
}
TestBed.configureTestingModule({declarations: [MyDir, MyComp]});
const fixture = TestBed.createComponent(MyComp);
const dir = fixture.debugElement.query(By.directive(MyDir)).injector.get(MyDir) as MyDir;
fixture.detectChanges();
expect(dir.setterCalls).toEqual({'a': null, 'b': 2});
expect(Object.keys(dir.changes ?? {})).toEqual(['a', 'b']);
dir.setterCalls = {};
dir.changes = {};
tick();
fixture.detectChanges();
expect(dir.setterCalls).toEqual({'a': 1});
expect(Object.keys(dir.changes)).toEqual(['a']);
}));
it('should only evaluate methods once - #10639', () => {
TestBed.configureTestingModule({declarations: [MyCountingComp]});
const template = '{{method()?.value}}';
TestBed.overrideComponent(MyCountingComp, {set: {template}});
const fixture = TestBed.createComponent(MyCountingComp);
MyCountingComp.reset();
fixture.detectChanges(/* checkNoChanges */ false);
expect(fixture.nativeElement).toHaveText('counting method value');
expect(MyCountingComp.calls).toBe(1);
});
it('should evaluate a conditional in a statement binding', () => {
@Component({
selector: 'some-comp',
template: '<p (click)="nullValue?.click()"></p>',
standalone: false,
})
class SomeComponent {
nullValue: SomeReferencedClass | undefined;
}
class SomeReferencedClass {
click() {}
}
expect(() => {
const fixture = TestBed.configureTestingModule({
declarations: [SomeComponent],
}).createComponent(SomeComponent);
fixture.detectChanges(/* checkNoChanges */ false);
}).not.toThrow();
});
});
describe('providers', () => {
function createInjector(providers: Provider[]): Injector {
TestBed.overrideComponent(MyComp1, {add: {providers}});
return TestBed.createComponent(MyComp1).componentInstance.injector;
}
it('should support providers with an InjectionToken that contains a `.` in the name', () => {
const token = new InjectionToken('a.b');
const tokenValue = 1;
const injector = createInjector([{provide: token, useValue: tokenValue}]);
expect(injector.get(token)).toEqual(tokenValue);
});
it('should support providers with string token with a `.` in it', () => {
const token = 'a.b';
const tokenValue = 1;
const injector = createInjector([{provide: token, useValue: tokenValue}]);
expect(injector.get(token)).toEqual(tokenValue);
});
it('should support providers with an anonymous function as token', () => {
const token = () => true;
const tokenValue = 1;
const injector = createInjector([{provide: token, useValue: tokenValue}]);
expect(injector.get(token)).toEqual(tokenValue);
});
it('should support providers with an InjectionToken that has a StringMap as value', () => {
const token1 = new InjectionToken('someToken');
const token2 = new InjectionToken('someToken');
const tokenValue1 = {'a': 1};
const tokenValue2 = {'a': 1};
const injector = createInjector([
{provide: token1, useValue: tokenValue1},
{provide: token2, useValue: tokenValue2},
]);
expect(injector.get(token1)).toEqual(tokenValue1);
expect(injector.get(token2)).toEqual(tokenValue2);
});
it('should support providers that have a `name` property with a number value', () => {
class TestClass {
constructor(public name: number) {}
}
const data = [new TestClass(1), new TestClass(2)];
const injector = createInjector([{provide: 'someToken', useValue: data}]);
expect(injector.get('someToken')).toEqual(data);
});
});
it('should allow logging a previous elements class binding via interpolation', () => {
const template = `<div [class.a]="true" #el>Class: {{el.className}}</div>`;
TestBed.overrideComponent(MyComp1, {set: {template}});
const fixture = TestBed.createComponent(MyComp1);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('Class: a');
});
it('should support ngClass before a component and content projection inside of an ngIf', () => {
TestBed.configureTestingModule({declarations: [CmpWithNgContent]});
const template = `A<cmp-content *ngIf="true" [ngClass]="'red'">B</cmp-content>C`;
TestBed.overrideComponent(MyComp1, {set: {template}});
const fixture = TestBed.createComponent(MyComp1);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('ABC');
});
it('should handle mutual recursion entered from multiple sides - #7084', () => {
TestBed.configureTestingModule({declarations: [FakeRecursiveComp, LeftComp, RightComp]});
const fixture = TestBed.createComponent(FakeRecursiveComp);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('[]');
});
it('should generate the correct output when constructors have the same name', () => {
function ComponentFactory(selector: string, template: string) {
@Component({
selector,
template,
standalone: false,
})
class MyComponent {}
return MyComponent;
}
const HeroComponent = ComponentFactory('my-hero', 'my hero');
const VillainComponent = ComponentFactory('a-villain', 'a villain');
const MainComponent = ComponentFactory(
'my-app',
'I was saved by <my-hero></my-hero> from <a-villain></a-villain>.',
);
TestBed.configureTestingModule({
declarations: [HeroComponent, VillainComponent, MainComponent],
});
const fixture = TestBed.createComponent(MainComponent);
expect(fixture.nativeElement).toHaveText('I was saved by my hero from a villain.');
});
it('should allow to use the renderer outside of views', () => {
@Component({
template: '',
standalone: false,
})
class MyComp {
constructor(public renderer: Renderer2) {}
}
TestBed.configureTestingModule({declarations: [MyComp]});
const ctx = TestBed.createComponent(MyComp);
const txtNode = ctx.componentInstance.renderer.createText('test');
expect(txtNode).toHaveText('test');
});
| {
"end_byte": 9834,
"start_byte": 965,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/regression_integration_spec.ts"
} |
angular/packages/core/test/linker/regression_integration_spec.ts_9838_18412 | t('should not recreate TemplateRef references during dirty checking', () => {
@Component({
template: '<div [someDir]="someRef"></div><ng-template #someRef></ng-template>',
standalone: false,
})
class MyComp {}
@Directive({
selector: '[someDir]',
standalone: false,
})
class MyDir {
@Input('someDir') template: TemplateRef<any> | undefined;
}
const ctx = TestBed.configureTestingModule({declarations: [MyComp, MyDir]}).createComponent(
MyComp,
);
const dir = <MyDir>ctx.debugElement.query(By.directive(MyDir)).injector.get(MyDir);
expect(dir.template).toBeUndefined();
ctx.detectChanges();
const template = dir.template;
expect(template).toBeDefined();
ctx.detectChanges();
expect(dir.template).toBe(template);
});
it('should not recreate ViewContainerRefs in queries', () => {
@Component({
template: '<div #vc></div><div *ngIf="show" #vc></div>',
standalone: false,
})
class MyComp {
@ViewChildren('vc', {read: ViewContainerRef}) viewContainers!: QueryList<ViewContainerRef>;
show = true;
}
const ctx = TestBed.configureTestingModule({declarations: [MyComp]}).createComponent(MyComp);
ctx.componentInstance.show = true;
ctx.detectChanges();
expect(ctx.componentInstance.viewContainers.length).toBe(2);
const vc = ctx.componentInstance.viewContainers.first;
expect(vc).toBeDefined();
ctx.componentInstance.show = false;
ctx.detectChanges();
expect(ctx.componentInstance.viewContainers.first).toBe(vc);
});
it('should not throw when encountering an empty class attribute', () => {
const template = '<div class=""></div>';
TestBed.overrideComponent(MyComp1, {set: {template}});
expect(() => TestBed.createComponent(MyComp1)).not.toThrow();
});
describe('empty templates - #15143', () => {
it('should allow empty components', () => {
@Component({
template: '',
standalone: false,
})
class MyComp {}
const fixture = TestBed.configureTestingModule({declarations: [MyComp]}).createComponent(
MyComp,
);
fixture.detectChanges();
expect(fixture.debugElement.childNodes.length).toBe(0);
});
});
it('should throw if @ContentChild and @Input are on the same property', () => {
@Directive({
selector: 'test',
standalone: false,
})
class Test {
@Input() @ContentChild(TemplateRef, {static: true}) tpl: TemplateRef<any> | undefined;
}
@Component({
selector: 'my-app',
template: `<test></test>`,
standalone: false,
})
class App {}
expect(() => {
TestBed.configureTestingModule({declarations: [App, Test]}).createComponent(App);
}).toThrowError(/Cannot combine @Input decorators with query decorators/);
});
it('should not add ng-version for dynamically created components', () => {
@Component({
template: '',
standalone: false,
})
class App {}
const compRef = createComponent(App, {
environmentInjector: TestBed.inject(EnvironmentInjector),
});
expect(compRef.location.nativeElement.hasAttribute('ng-version')).toBe(false);
compRef.destroy();
});
});
describe('regressions using bootstrap', () => {
const COMP_SELECTOR = 'root-comp';
class MockConsole {
errors: any[][] = [];
error(...s: any[]): void {
this.errors.push(s);
}
}
let logger: MockConsole;
let errorHandler: ErrorHandler;
beforeEach(inject([DOCUMENT], (doc: any) => {
destroyPlatform();
const el = getDOM().createElement(COMP_SELECTOR, doc);
doc.body.appendChild(el);
logger = new MockConsole();
errorHandler = new ErrorHandler();
(errorHandler as any)._console = logger as any;
}));
afterEach(() => {
destroyPlatform();
});
if (getDOM().supportsDOMEvents) {
// This test needs a real DOM....
it('should keep change detecting if there was an error', (done) => {
@Component({
selector: COMP_SELECTOR,
template:
'<button (click)="next()"></button><button (click)="nextAndThrow()"></button><button (dirClick)="nextAndThrow()"></button><span>Value:{{value}}</span><span>{{throwIfNeeded()}}</span>',
standalone: false,
})
class ErrorComp {
value = 0;
thrownValue = 0;
next() {
this.value++;
}
nextAndThrow() {
this.value++;
this.throwIfNeeded();
}
throwIfNeeded() {
NgZone.assertInAngularZone();
if (this.thrownValue !== this.value) {
this.thrownValue = this.value;
throw new Error(`Error: ${this.value}`);
}
}
}
@Directive({
selector: '[dirClick]',
standalone: false,
})
class EventDir {
@Output() dirClick = new EventEmitter();
@HostListener('click', ['$event'])
onClick(event: any) {
this.dirClick.next(event);
}
}
@NgModule({
imports: [BrowserModule],
declarations: [ErrorComp, EventDir],
bootstrap: [ErrorComp],
providers: [{provide: ErrorHandler, useValue: errorHandler}],
})
class TestModule {}
platformBrowserDynamic()
.bootstrapModule(TestModule)
.then((ref) => {
NgZone.assertNotInAngularZone();
const appRef = ref.injector.get(ApplicationRef) as ApplicationRef;
const compRef = appRef.components[0] as ComponentRef<ErrorComp>;
const compEl = compRef.location.nativeElement;
const nextBtn = compEl.children[0];
const nextAndThrowBtn = compEl.children[1];
const nextAndThrowDirBtn = compEl.children[2];
const errorDelta = 1;
let currentErrorIndex = 0;
nextBtn.click();
assertValueAndErrors(compEl, 1, currentErrorIndex);
currentErrorIndex += errorDelta;
nextBtn.click();
assertValueAndErrors(compEl, 2, currentErrorIndex);
currentErrorIndex += errorDelta;
nextAndThrowBtn.click();
assertValueAndErrors(compEl, 3, currentErrorIndex);
currentErrorIndex += errorDelta;
nextAndThrowBtn.click();
assertValueAndErrors(compEl, 4, currentErrorIndex);
currentErrorIndex += errorDelta;
nextAndThrowDirBtn.click();
assertValueAndErrors(compEl, 5, currentErrorIndex);
currentErrorIndex += errorDelta;
nextAndThrowDirBtn.click();
assertValueAndErrors(compEl, 6, currentErrorIndex);
currentErrorIndex += errorDelta;
// Assert that there were no more errors
expect(logger.errors.length).toBe(currentErrorIndex);
done();
});
function assertValueAndErrors(compEl: any, value: number, errorIndex: number) {
expect(compEl).toHaveText(`Value:${value}`);
expect(logger.errors[errorIndex][0]).toBe('ERROR');
expect(logger.errors[errorIndex][1].message).toBe(`Error: ${value}`);
}
});
} else {
// Jasmine will throw if there are no tests.
it('should pass', () => {});
}
});
@Component({
selector: 'my-comp',
template: '',
standalone: false,
})
class MyComp1 {
constructor(public injector: Injector) {}
}
@Pipe({
name: 'somePipe',
pure: true,
standalone: false,
})
class PlatformPipe implements PipeTransform {
transform(value: any): any {
return 'somePlatformPipe';
}
}
@Pipe({
name: 'somePipe',
pure: true,
standalone: false,
})
class CustomPipe implements PipeTransform {
transform(value: any): any {
return 'someCustomPipe';
}
}
@Component({
selector: 'cmp-content',
template: `<ng-content></ng-content>`,
standalone: false,
})
class CmpWithNgContent {}
@Component({
selector: 'counting-cmp',
template: '',
standalone: false,
})
class MyCountingComp {
method(): {value: string} | undefined {
MyCountingComp.calls++;
return {value: 'counting method value'};
}
static reset() {
MyCountingComp.calls = 0;
}
static calls = 0;
}
@Pipe({
name: 'countingPipe',
standalone: false,
})
class CountingPipe implements PipeTransform {
transform(value: any): any {
CountingPipe.calls++;
return {value: 'counting pipe value'};
}
static reset() {
CountingPipe.calls = 0;
}
static calls = 0;
}
@Component({
selector: 'left',
template: `L<right *ngIf="false"></right>`,
standalone: false,
})
class LeftComp {}
| {
"end_byte": 18412,
"start_byte": 9838,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/regression_integration_spec.ts"
} |
angular/packages/core/test/linker/regression_integration_spec.ts_18414_18713 | Component({
selector: 'right',
template: `R<left *ngIf="false"></left>`,
standalone: false,
})
class RightComp {}
@Component({
selector: 'fakeRecursiveComp',
template: `[<left *ngIf="false"></left><right *ngIf="false"></right>]`,
standalone: false,
})
export class FakeRecursiveComp {}
| {
"end_byte": 18713,
"start_byte": 18414,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/regression_integration_spec.ts"
} |
angular/packages/core/test/linker/query_integration_spec.ts_0_1843 | /**
* @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 {
AfterContentChecked,
AfterContentInit,
AfterViewChecked,
AfterViewInit,
asNativeElements,
Component,
ContentChild,
ContentChildren,
Directive,
QueryList,
TemplateRef,
Type,
ViewChild,
ViewChildren,
ViewContainerRef,
} from '@angular/core';
import {ElementRef} from '@angular/core/src/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {Subject} from 'rxjs';
import {stringify} from '../../src/util/stringify';
describe('Query API', () => {
beforeEach(() =>
TestBed.configureTestingModule({
declarations: [
MyComp0,
NeedsQuery,
NeedsQueryDesc,
NeedsQueryByLabel,
NeedsQueryByTwoLabels,
NeedsQueryAndProject,
NeedsViewQuery,
NeedsViewQueryIf,
NeedsViewQueryNestedIf,
NeedsViewQueryOrder,
NeedsViewQueryByLabel,
NeedsViewQueryOrderWithParent,
NeedsContentChildren,
NeedsViewChildren,
NeedsViewChild,
NeedsStaticContentAndViewChild,
NeedsContentChild,
DirectiveNeedsContentChild,
NeedsTpl,
NeedsNamedTpl,
TextDirective,
InertDirective,
NeedsFourQueries,
NeedsContentChildrenWithRead,
NeedsContentChildWithRead,
NeedsViewChildrenWithRead,
NeedsViewChildWithRead,
NeedsContentChildrenShallow,
NeedsContentChildTemplateRef,
NeedsContentChildTemplateRefApp,
NeedsViewContainerWithRead,
ManualProjecting,
],
}),
); | {
"end_byte": 1843,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/query_integration_spec.ts"
} |
angular/packages/core/test/linker/query_integration_spec.ts_1847_9898 | describe('querying by directive type', () => {
it('should contain all direct child directives in the light dom (constructor)', () => {
const template = `
<div text="1"></div>
<needs-query text="2">
<div text="3">
<div text="too-deep"></div>
</div>
</needs-query>
<div text="4"></div>
`;
const view = createTestCmpAndDetectChanges(MyComp0, template);
// Queries don't match host nodes of a directive that defines a content query.
expect(asNativeElements(view.debugElement.children)).toHaveText('3|');
});
it('should contain all direct child directives in the content dom', () => {
const template = '<needs-content-children #q><div text="foo"></div></needs-content-children>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q = view.debugElement.children[0].references!['q'];
view.detectChanges();
expect(q.textDirChildren.length).toEqual(1);
expect(q.numberOfChildrenAfterContentInit).toEqual(1);
});
it('should contain the first content child', () => {
const template =
'<needs-content-child #q><div *ngIf="shouldShow" text="foo"></div></needs-content-child>';
const view = createTestCmp(MyComp0, template);
view.componentInstance.shouldShow = true;
view.detectChanges();
const q: NeedsContentChild = view.debugElement.children[0].references!['q'];
expect(q.logs).toEqual([
['setter', 'foo'],
['init', 'foo'],
['check', 'foo'],
]);
view.componentInstance.shouldShow = false;
view.detectChanges();
expect(q.logs).toEqual([
['setter', 'foo'],
['init', 'foo'],
['check', 'foo'],
['setter', null],
['check', null],
]);
});
it('should contain the first content child when target is on <ng-template> with embedded view (issue #16568)', () => {
const template = `
<div directive-needs-content-child>
<ng-template text="foo" [ngIf]="true">
<div text="bar"></div>
</ng-template>
</div>
<needs-content-child #q>
<ng-template text="foo" [ngIf]="true">
<div text="bar"></div>
</ng-template>
</needs-content-child>
`;
const view = createTestCmp(MyComp0, template);
view.detectChanges();
const q: NeedsContentChild = view.debugElement.children[1].references!['q'];
expect(q.child?.text).toEqual('foo');
const directive: DirectiveNeedsContentChild = view.debugElement.children[0].injector.get(
DirectiveNeedsContentChild,
);
expect(directive.child.text).toEqual('foo');
});
it('should contain the first view child', () => {
const template = '<needs-view-child #q></needs-view-child>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q: NeedsViewChild = view.debugElement.children[0].references!['q'];
expect(q.logs).toEqual([
['setter', 'foo'],
['init', 'foo'],
['check', 'foo'],
]);
q.shouldShow = false;
view.detectChanges();
expect(q.logs).toEqual([
['setter', 'foo'],
['init', 'foo'],
['check', 'foo'],
['setter', null],
['check', null],
]);
});
it('should contain the first view child across embedded views', () => {
TestBed.overrideComponent(MyComp0, {
set: {template: '<needs-view-child #q></needs-view-child>'},
});
TestBed.overrideComponent(NeedsViewChild, {
set: {
template:
'<div *ngIf="true"><div *ngIf="shouldShow" text="foo"></div></div><div *ngIf="shouldShow2" text="bar"></div>',
},
});
const view = TestBed.createComponent(MyComp0);
view.detectChanges();
const q: NeedsViewChild = view.debugElement.children[0].references!['q'];
expect(q.logs).toEqual([
['setter', 'foo'],
['init', 'foo'],
['check', 'foo'],
]);
q.shouldShow = false;
q.shouldShow2 = true;
q.logs = [];
view.detectChanges();
expect(q.logs).toEqual([
['setter', 'bar'],
['check', 'bar'],
]);
q.shouldShow = false;
q.shouldShow2 = false;
q.logs = [];
view.detectChanges();
expect(q.logs).toEqual([
['setter', null],
['check', null],
]);
});
it('should contain all directives in the light dom when descendants flag is used', () => {
const template =
'<div text="1"></div>' +
'<needs-query-desc text="2"><div text="3">' +
'<div text="4"></div>' +
'</div></needs-query-desc>' +
'<div text="5"></div>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
// Queries don't match host nodes of a directive that defines a content query.
expect(asNativeElements(view.debugElement.children)).toHaveText('3|4|');
});
it('should contain all directives in the light dom', () => {
const template =
'<div text="1"></div>' +
'<needs-query text="2"><div text="3"></div></needs-query>' +
'<div text="4"></div>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
// Queries don't match host nodes of a directive that defines a content query.
expect(asNativeElements(view.debugElement.children)).toHaveText('3|');
});
it('should reflect dynamically inserted directives', () => {
const template =
'<div text="1"></div>' +
'<needs-query text="2"><div *ngIf="shouldShow" [text]="\'3\'"></div></needs-query>' +
'<div text="4"></div>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
// Queries don't match host nodes of a directive that defines a content query.
expect(asNativeElements(view.debugElement.children)).toHaveText('');
view.componentInstance.shouldShow = true;
view.detectChanges();
// Queries don't match host nodes of a directive that defines a content query.
expect(asNativeElements(view.debugElement.children)).toHaveText('3|');
});
it('should be cleanly destroyed when a query crosses view boundaries', () => {
const template =
'<div text="1"></div>' +
'<needs-query text="2"><div *ngIf="shouldShow" [text]="\'3\'"></div></needs-query>' +
'<div text="4"></div>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
view.componentInstance.shouldShow = true;
view.detectChanges();
view.destroy();
});
it('should reflect moved directives', () => {
const template =
'<div text="1"></div>' +
'<needs-query text="2"><div *ngFor="let i of list" [text]="i"></div></needs-query>' +
'<div text="4"></div>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
// Queries don't match host nodes of a directive that defines a content query.
expect(asNativeElements(view.debugElement.children)).toHaveText('1d|2d|3d|');
view.componentInstance.list = ['3d', '2d'];
view.detectChanges();
// Queries don't match host nodes of a directive that defines a content query.
expect(asNativeElements(view.debugElement.children)).toHaveText('3d|2d|');
});
it('should throw with descriptive error when query selectors are not present', () => {
TestBed.configureTestingModule({declarations: [MyCompBroken0, HasNullQueryCondition]});
const template = '<has-null-query-condition></has-null-query-condition>';
TestBed.overrideComponent(MyCompBroken0, {set: {template}});
expect(() => TestBed.createComponent(MyCompBroken0)).toThrowError(
`Can't construct a query for the property "errorTrigger" of "${stringify(
HasNullQueryCondition,
)}" since the query selector wasn't defined.`,
);
});
}); | {
"end_byte": 9898,
"start_byte": 1847,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/query_integration_spec.ts"
} |
angular/packages/core/test/linker/query_integration_spec.ts_9902_18431 | describe('query for TemplateRef', () => {
it('should find TemplateRefs in the light and shadow dom', () => {
const template = '<needs-tpl><ng-template><div>light</div></ng-template></needs-tpl>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const needsTpl: NeedsTpl = view.debugElement.children[0].injector.get(NeedsTpl);
expect(needsTpl.vc.createEmbeddedView(needsTpl.query.first).rootNodes[0]).toHaveText('light');
expect(needsTpl.vc.createEmbeddedView(needsTpl.viewQuery.first).rootNodes[0]).toHaveText(
'shadow',
);
});
it('should find named TemplateRefs', () => {
const template =
'<needs-named-tpl><ng-template #tpl><div>light</div></ng-template></needs-named-tpl>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const needsTpl: NeedsNamedTpl = view.debugElement.children[0].injector.get(NeedsNamedTpl);
expect(needsTpl.vc.createEmbeddedView(needsTpl.contentTpl).rootNodes[0]).toHaveText('light');
expect(needsTpl.vc.createEmbeddedView(needsTpl.viewTpl).rootNodes[0]).toHaveText('shadow');
});
});
describe('read a different token', () => {
it('should contain the first content child', () => {
const template =
'<needs-content-child-read><div #q text="ca"></div></needs-content-child-read>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const comp: NeedsContentChildWithRead =
view.debugElement.children[0].injector.get(NeedsContentChildWithRead);
expect(comp.textDirChild.text).toEqual('ca');
});
it('should contain the first descendant content child', () => {
const template =
'<needs-content-child-read>' +
'<div dir><div #q text="ca"></div></div>' +
'</needs-content-child-read>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const comp: NeedsContentChildWithRead =
view.debugElement.children[0].injector.get(NeedsContentChildWithRead);
expect(comp.textDirChild.text).toEqual('ca');
});
it('should contain the first descendant content child for shallow queries', () => {
const template = `<needs-content-children-shallow>
<div #q></div>
</needs-content-children-shallow>`;
const view = createTestCmpAndDetectChanges(MyComp0, template);
const comp = view.debugElement.children[0].injector.get(NeedsContentChildrenShallow);
expect(comp.children.length).toBe(1);
});
it('should contain the first descendant content child in an embedded template for shallow queries', () => {
const template = `<needs-content-children-shallow>
<ng-template [ngIf]="true">
<div #q></div>
</ng-template>
</needs-content-children-shallow>`;
const view = createTestCmpAndDetectChanges(MyComp0, template);
const comp = view.debugElement.children[0].injector.get(NeedsContentChildrenShallow);
expect(comp.children.length).toBe(1);
});
it('should contain the first descendant content child in an embedded template for shallow queries and additional directive', () => {
const template = `<needs-content-children-shallow>
<ng-template [ngIf]="true">
<div #q directive-needs-content-child></div>
</ng-template>
</needs-content-children-shallow>`;
const view = createTestCmpAndDetectChanges(MyComp0, template);
const comp = view.debugElement.children[0].injector.get(NeedsContentChildrenShallow);
expect(comp.children.length).toBe(1);
});
it('should contain the first descendant content child in an embedded template for shallow queries and additional directive (star syntax)', () => {
const template = `<needs-content-children-shallow>
<div *ngIf="true" #q directive-needs-content-child></div>
</needs-content-children-shallow>`;
const view = createTestCmpAndDetectChanges(MyComp0, template);
const comp = view.debugElement.children[0].injector.get(NeedsContentChildrenShallow);
expect(comp.children.length).toBe(1);
});
it('should not cross ng-container boundaries with shallow queries', () => {
const template = `<needs-content-children-shallow>
<ng-container>
<div #q></div>
</ng-container>
</needs-content-children-shallow>`;
const view = createTestCmpAndDetectChanges(MyComp0, template);
const comp = view.debugElement.children[0].injector.get(NeedsContentChildrenShallow);
expect(comp.children.length).toBe(1);
});
it('should contain the first descendant content child templateRef', () => {
const template =
'<needs-content-child-template-ref-app>' + '</needs-content-child-template-ref-app>';
const view = createTestCmp(MyComp0, template);
// can't execute checkNoChanges as our view modifies our content children (via a query).
view.detectChanges(false);
expect(view.nativeElement).toHaveText('OUTER');
});
it('should contain the first view child', () => {
const template = '<needs-view-child-read></needs-view-child-read>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const comp: NeedsViewChildWithRead =
view.debugElement.children[0].injector.get(NeedsViewChildWithRead);
expect(comp.textDirChild.text).toEqual('va');
});
it('should contain all child directives in the view', () => {
const template = '<needs-view-children-read></needs-view-children-read>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const comp: NeedsViewChildrenWithRead =
view.debugElement.children[0].injector.get(NeedsViewChildrenWithRead);
expect(comp.textDirChildren.map((textDirective) => textDirective.text)).toEqual(['va', 'vb']);
});
it('should support reading a ViewContainer', () => {
const template =
'<needs-viewcontainer-read><ng-template>hello</ng-template></needs-viewcontainer-read>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const comp: NeedsViewContainerWithRead = view.debugElement.children[0].injector.get(
NeedsViewContainerWithRead,
);
comp.createView();
expect(view.debugElement.children[0].nativeElement).toHaveText('hello');
});
});
describe('changes', () => {
it('should notify query on change', waitForAsync(() => {
const template =
'<needs-query #q>' +
'<div text="1"></div>' +
'<div *ngIf="shouldShow" text="2"></div>' +
'</needs-query>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q = view.debugElement.children[0].references!['q'];
q.query.changes.subscribe({
next: () => {
expect(q.query.first.text).toEqual('1');
expect(q.query.last.text).toEqual('2');
},
});
view.componentInstance.shouldShow = true;
view.detectChanges();
}));
it('should correctly clean-up when destroyed together with the directives it is querying', () => {
const template = '<needs-query #q *ngIf="shouldShow"><div text="foo"></div></needs-query>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
view.componentInstance.shouldShow = true;
view.detectChanges();
let isQueryListCompleted = false;
const q: NeedsQuery = view.debugElement.children[0].references!['q'];
const changes = <Subject<any>>q.query.changes;
expect(q.query.length).toEqual(1);
expect(changes.closed).toBeFalsy();
changes.subscribe(
() => {},
() => {},
() => {
isQueryListCompleted = true;
},
);
view.componentInstance.shouldShow = false;
view.detectChanges();
expect(changes.closed).toBeTruthy();
expect(isQueryListCompleted).toBeTruthy();
view.componentInstance.shouldShow = true;
view.detectChanges();
const q2: NeedsQuery = view.debugElement.children[0].references!['q'];
expect(q2.query.length).toEqual(1);
expect(changes.closed).toBeTruthy();
expect((<Subject<any>>q2.query.changes).closed).toBeFalsy();
});
}); | {
"end_byte": 18431,
"start_byte": 9902,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/query_integration_spec.ts"
} |
angular/packages/core/test/linker/query_integration_spec.ts_18435_26210 | describe('querying by var binding', () => {
it('should contain all the child directives in the light dom with the given var binding', () => {
const template =
'<needs-query-by-ref-binding #q>' +
'<div *ngFor="let item of list" [text]="item" #textLabel="textDir"></div>' +
'</needs-query-by-ref-binding>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q = view.debugElement.children[0].references!['q'];
view.componentInstance.list = ['1d', '2d'];
view.detectChanges();
expect(q.query.first.text).toEqual('1d');
expect(q.query.last.text).toEqual('2d');
});
it('should support querying by multiple var bindings', () => {
const template =
'<needs-query-by-ref-bindings #q>' +
'<div text="one" #textLabel1="textDir"></div>' +
'<div text="two" #textLabel2="textDir"></div>' +
'</needs-query-by-ref-bindings>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q = view.debugElement.children[0].references!['q'];
expect(q.query.first.text).toEqual('one');
expect(q.query.last.text).toEqual('two');
});
it('should support dynamically inserted directives', () => {
const template =
'<needs-query-by-ref-binding #q>' +
'<div *ngFor="let item of list" [text]="item" #textLabel="textDir"></div>' +
'</needs-query-by-ref-binding>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q = view.debugElement.children[0].references!['q'];
view.componentInstance.list = ['1d', '2d'];
view.detectChanges();
view.componentInstance.list = ['2d', '1d'];
view.detectChanges();
expect(q.query.last.text).toEqual('1d');
});
it('should contain all the elements in the light dom with the given var binding', () => {
const template =
'<needs-query-by-ref-binding #q>' +
'<div *ngFor="let item of list">' +
'<div #textLabel>{{item}}</div>' +
'</div>' +
'</needs-query-by-ref-binding>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q = view.debugElement.children[0].references!['q'];
view.componentInstance.list = ['1d', '2d'];
view.detectChanges();
expect(q.query.first.nativeElement).toHaveText('1d');
expect(q.query.last.nativeElement).toHaveText('2d');
});
it('should contain all the elements in the light dom even if they get projected', () => {
const template =
'<needs-query-and-project #q>' +
'<div text="hello"></div><div text="world"></div>' +
'</needs-query-and-project>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
expect(asNativeElements(view.debugElement.children)).toHaveText('hello|world|');
});
it('should support querying the view by using a view query', () => {
const template = '<needs-view-query-by-ref-binding #q></needs-view-query-by-ref-binding>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q: NeedsViewQueryByLabel = view.debugElement.children[0].references!['q'];
expect(q.query.first.nativeElement).toHaveText('text');
});
it('should contain all child directives in the view dom', () => {
const template = '<needs-view-children #q></needs-view-children>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q = view.debugElement.children[0].references!['q'];
expect(q.textDirChildren.length).toEqual(1);
expect(q.numberOfChildrenAfterViewInit).toEqual(1);
});
});
describe('querying in the view', () => {
it('should contain all the elements in the view with that have the given directive', () => {
const template = '<needs-view-query #q><div text="ignoreme"></div></needs-view-query>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q: NeedsViewQuery = view.debugElement.children[0].references!['q'];
expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1', '2', '3', '4']);
});
it('should not include directive present on the host element', () => {
const template = '<needs-view-query #q text="self"></needs-view-query>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q: NeedsViewQuery = view.debugElement.children[0].references!['q'];
expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1', '2', '3', '4']);
});
it('should reflect changes in the component', () => {
const template = '<needs-view-query-if #q></needs-view-query-if>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q: NeedsViewQueryIf = view.debugElement.children[0].references!['q'];
expect(q.query.length).toBe(0);
q.show = true;
view.detectChanges();
expect(q.query.length).toBe(1);
expect(q.query.first.text).toEqual('1');
});
it('should not be affected by other changes in the component', () => {
const template = '<needs-view-query-nested-if #q></needs-view-query-nested-if>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q: NeedsViewQueryNestedIf = view.debugElement.children[0].references!['q'];
expect(q.query.length).toEqual(1);
expect(q.query.first.text).toEqual('1');
q.show = false;
view.detectChanges();
expect(q.query.length).toEqual(1);
expect(q.query.first.text).toEqual('1');
});
it('should maintain directives in pre-order depth-first DOM order after dynamic insertion', () => {
const template = '<needs-view-query-order #q></needs-view-query-order>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q: NeedsViewQueryOrder = view.debugElement.children[0].references!['q'];
expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1', '2', '3', '4']);
q.list = ['-3', '2'];
view.detectChanges();
expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1', '-3', '2', '4']);
});
it('should maintain directives in pre-order depth-first DOM order after dynamic insertion', () => {
const template = '<needs-view-query-order-with-p #q></needs-view-query-order-with-p>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q: NeedsViewQueryOrderWithParent = view.debugElement.children[0].references!['q'];
expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1', '2', '3', '4']);
q.list = ['-3', '2'];
view.detectChanges();
expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1', '-3', '2', '4']);
});
it('should handle long ngFor cycles', () => {
const template = '<needs-view-query-order #q></needs-view-query-order>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q: NeedsViewQueryOrder = view.debugElement.children[0].references!['q'];
// no significance to 50, just a reasonably large cycle.
for (let i = 0; i < 50; i++) {
const newString = i.toString();
q.list = [newString];
view.detectChanges();
expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1', newString, '4']);
}
});
it('should support more than three queries', () => {
const template = '<needs-four-queries #q><div text="1"></div></needs-four-queries>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q = view.debugElement.children[0].references!['q'];
expect(q.query1).toBeDefined();
expect(q.query2).toBeDefined();
expect(q.query3).toBeDefined();
expect(q.query4).toBeDefined();
});
}); | {
"end_byte": 26210,
"start_byte": 18435,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/query_integration_spec.ts"
} |
angular/packages/core/test/linker/query_integration_spec.ts_26214_34436 | describe('query over moved templates', () => {
it('should include manually projected templates in queries', () => {
const template =
'<manual-projecting #q><ng-template><div text="1"></div></ng-template></manual-projecting>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q = view.debugElement.children[0].references!['q'];
expect(q.query.length).toBe(0);
q.create();
view.detectChanges();
expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1']);
q.destroy();
view.detectChanges();
expect(q.query.length).toBe(0);
});
it('should update queries when a view is detached and re-inserted', () => {
const template = `<manual-projecting #q>
<ng-template let-x="x">
<div [text]="x"></div>
</ng-template>
</manual-projecting>`;
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q = view.debugElement.children[0].references!['q'] as ManualProjecting;
expect(q.query.length).toBe(0);
const view1 = q.vc.createEmbeddedView(q.template, {'x': '1'});
const view2 = q.vc.createEmbeddedView(q.template, {'x': '2'});
// 2 views were created and inserted so we've got 2 matching results
view.detectChanges();
expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1', '2']);
q.vc.detach(1);
q.vc.detach(0);
// both views were detached so query results from those views should not be reported
view.detectChanges();
expect(q.query.map((d: TextDirective) => d.text)).toEqual([]);
q.vc.insert(view2);
q.vc.insert(view1);
// previously detached views are re-inserted in the different order so:
// - query results from the inserted views are reported again
// - the order results from views reflects orders of views
view.detectChanges();
expect(q.query.map((d: TextDirective) => d.text)).toEqual(['2', '1']);
});
it('should remove manually projected templates if their parent view is destroyed', () => {
const template = `
<manual-projecting #q><ng-template #tpl><div text="1"></div></ng-template></manual-projecting>
<div *ngIf="shouldShow">
<ng-container [ngTemplateOutlet]="tpl"></ng-container>
</div>
`;
const view = createTestCmp(MyComp0, template);
const q = view.debugElement.children[0].references!['q'];
view.componentInstance.shouldShow = true;
view.detectChanges();
expect(q.query.length).toBe(1);
view.componentInstance.shouldShow = false;
view.detectChanges();
expect(q.query.length).toBe(0);
});
it('should not throw if a content template is queried and created in the view during change detection - fixed in ivy', () => {
@Component({
selector: 'auto-projecting',
template: '<div *ngIf="true; then: content"></div>',
standalone: false,
})
class AutoProjecting {
@ContentChild(TemplateRef) content!: TemplateRef<any>;
@ContentChildren(TextDirective) query!: QueryList<TextDirective>;
}
TestBed.configureTestingModule({declarations: [AutoProjecting]});
const template =
'<auto-projecting #q><ng-template><div text="1"></div></ng-template></auto-projecting>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q = view.debugElement.children[0].references!['q'];
expect(q.query.length).toBe(1);
});
});
});
@Directive({
selector: '[text]',
inputs: ['text'],
exportAs: 'textDir',
standalone: false,
})
class TextDirective {
text: string | undefined;
}
@Component({
selector: 'needs-content-children',
template: '',
standalone: false,
})
class NeedsContentChildren implements AfterContentInit {
@ContentChildren(TextDirective) textDirChildren!: QueryList<TextDirective>;
numberOfChildrenAfterContentInit!: number;
ngAfterContentInit() {
this.numberOfChildrenAfterContentInit = this.textDirChildren.length;
}
}
@Component({
selector: 'needs-view-children',
template: '<div text></div>',
standalone: false,
})
class NeedsViewChildren implements AfterViewInit {
@ViewChildren(TextDirective) textDirChildren!: QueryList<TextDirective>;
numberOfChildrenAfterViewInit!: number;
ngAfterViewInit() {
this.numberOfChildrenAfterViewInit = this.textDirChildren.length;
}
}
@Component({
selector: 'needs-content-child',
template: '',
standalone: false,
})
class NeedsContentChild implements AfterContentInit, AfterContentChecked {
private _child: TextDirective | undefined;
@ContentChild(TextDirective)
set child(value) {
this._child = value;
this.logs.push(['setter', value?.text ?? null]);
}
get child() {
return this._child;
}
logs: (string | null)[][] = [];
ngAfterContentInit() {
this.logs.push(['init', this.child?.text ?? null]);
}
ngAfterContentChecked() {
this.logs.push(['check', this.child?.text ?? null]);
}
}
@Directive({
selector: '[directive-needs-content-child]',
standalone: false,
})
class DirectiveNeedsContentChild {
@ContentChild(TextDirective) child!: TextDirective;
}
@Component({
selector: 'needs-view-child',
template: `<div *ngIf="shouldShow" text="foo"></div>`,
standalone: false,
})
class NeedsViewChild implements AfterViewInit, AfterViewChecked {
shouldShow: boolean = true;
shouldShow2: boolean = false;
private _child: TextDirective | undefined;
@ViewChild(TextDirective)
set child(value) {
this._child = value;
this.logs.push(['setter', value?.text ?? null]);
}
get child() {
return this._child;
}
logs: (string | null)[][] = [];
ngAfterViewInit() {
this.logs.push(['init', this.child?.text ?? null]);
}
ngAfterViewChecked() {
this.logs.push(['check', this.child?.text ?? null]);
}
}
function createTestCmp<T>(type: Type<T>, template: string): ComponentFixture<T> {
const view = TestBed.overrideComponent(type, {set: {template}}).createComponent(type);
return view;
}
function createTestCmpAndDetectChanges<T>(type: Type<T>, template: string): ComponentFixture<T> {
const view = createTestCmp(type, template);
view.detectChanges();
return view;
}
@Component({
selector: 'needs-static-content-view-child',
template: `<div text="viewFoo"></div>`,
standalone: false,
})
class NeedsStaticContentAndViewChild {
@ContentChild(TextDirective, {static: true}) contentChild!: TextDirective;
@ViewChild(TextDirective, {static: true}) viewChild!: TextDirective;
}
@Directive({
selector: '[dir]',
standalone: false,
})
class InertDirective {}
@Component({
selector: 'needs-query',
template: '<div text="ignoreme"></div><b *ngFor="let dir of query">{{dir.text}}|</b>',
standalone: false,
})
class NeedsQuery {
@ContentChildren(TextDirective) query!: QueryList<TextDirective>;
}
@Component({
selector: 'needs-four-queries',
template: '',
standalone: false,
})
class NeedsFourQueries {
@ContentChild(TextDirective) query1!: TextDirective;
@ContentChild(TextDirective) query2!: TextDirective;
@ContentChild(TextDirective) query3!: TextDirective;
@ContentChild(TextDirective) query4!: TextDirective;
}
@Component({
selector: 'needs-query-desc',
template: '<ng-content></ng-content><div *ngFor="let dir of query">{{dir.text}}|</div>',
standalone: false,
})
class NeedsQueryDesc {
@ContentChildren(TextDirective, {descendants: true}) query!: QueryList<TextDirective>;
}
@Component({
selector: 'needs-query-by-ref-binding',
template: '<ng-content>',
standalone: false,
})
class NeedsQueryByLabel {
@ContentChildren('textLabel', {descendants: true}) query!: QueryList<any>;
}
@Component({
selector: 'needs-view-query-by-ref-binding',
template: '<div #textLabel>text</div>',
standalone: false,
})
class NeedsViewQueryByLabel {
@ViewChildren('textLabel') query!: QueryList<any>;
}
@Component({
selector: 'needs-query-by-ref-bindings',
template: '<ng-content>',
standalone: false,
})
class NeedsQueryByTwoLabels {
@ContentChildren('textLabel1,textLabel2', {descendants: true}) query!: QueryList<any>;
} | {
"end_byte": 34436,
"start_byte": 26214,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/query_integration_spec.ts"
} |
angular/packages/core/test/linker/query_integration_spec.ts_34438_40241 | @Component({
selector: 'needs-query-and-project',
template: '<div *ngFor="let dir of query">{{dir.text}}|</div><ng-content></ng-content>',
standalone: false,
})
class NeedsQueryAndProject {
@ContentChildren(TextDirective) query!: QueryList<TextDirective>;
}
@Component({
selector: 'needs-view-query',
template: '<div text="1"><div text="2"></div></div><div text="3"></div><div text="4"></div>',
standalone: false,
})
class NeedsViewQuery {
@ViewChildren(TextDirective) query!: QueryList<TextDirective>;
}
@Component({
selector: 'needs-view-query-if',
template: '<div *ngIf="show" text="1"></div>',
standalone: false,
})
class NeedsViewQueryIf {
show: boolean = false;
@ViewChildren(TextDirective) query!: QueryList<TextDirective>;
}
@Component({
selector: 'needs-view-query-nested-if',
template: '<div text="1"><div *ngIf="show"><div dir></div></div></div>',
standalone: false,
})
class NeedsViewQueryNestedIf {
show: boolean = true;
@ViewChildren(TextDirective) query!: QueryList<TextDirective>;
}
@Component({
selector: 'needs-view-query-order',
template:
'<div text="1"></div>' +
'<div *ngFor="let i of list" [text]="i"></div>' +
'<div text="4"></div>',
standalone: false,
})
class NeedsViewQueryOrder {
@ViewChildren(TextDirective) query!: QueryList<TextDirective>;
list: string[] = ['2', '3'];
}
@Component({
selector: 'needs-view-query-order-with-p',
template:
'<div dir><div text="1"></div>' +
'<div *ngFor="let i of list" [text]="i"></div>' +
'<div text="4"></div></div>',
standalone: false,
})
class NeedsViewQueryOrderWithParent {
@ViewChildren(TextDirective) query!: QueryList<TextDirective>;
list: string[] = ['2', '3'];
}
@Component({
selector: 'needs-tpl',
template: '<ng-template><div>shadow</div></ng-template>',
standalone: false,
})
class NeedsTpl {
@ViewChildren(TemplateRef) viewQuery!: QueryList<TemplateRef<Object>>;
@ContentChildren(TemplateRef) query!: QueryList<TemplateRef<Object>>;
constructor(public vc: ViewContainerRef) {}
}
@Component({
selector: 'needs-named-tpl',
template: '<ng-template #tpl><div>shadow</div></ng-template>',
standalone: false,
})
class NeedsNamedTpl {
@ViewChild('tpl', {static: true}) viewTpl!: TemplateRef<Object>;
@ContentChild('tpl', {static: true}) contentTpl!: TemplateRef<Object>;
constructor(public vc: ViewContainerRef) {}
}
@Component({
selector: 'needs-content-children-read',
template: '',
standalone: false,
})
class NeedsContentChildrenWithRead {
@ContentChildren('q', {read: TextDirective}) textDirChildren!: QueryList<TextDirective>;
@ContentChildren('nonExisting', {read: TextDirective}) nonExistingVar!: QueryList<TextDirective>;
}
@Component({
selector: 'needs-content-child-read',
template: '',
standalone: false,
})
class NeedsContentChildWithRead {
@ContentChild('q', {read: TextDirective}) textDirChild!: TextDirective;
@ContentChild('nonExisting', {read: TextDirective}) nonExistingVar!: TextDirective;
}
@Component({
selector: 'needs-content-children-shallow',
template: '',
standalone: false,
})
class NeedsContentChildrenShallow {
@ContentChildren('q', {descendants: false}) children!: QueryList<ElementRef>;
}
@Component({
selector: 'needs-content-child-template-ref',
template: '<div [ngTemplateOutlet]="templateRef"></div>',
standalone: false,
})
class NeedsContentChildTemplateRef {
@ContentChild(TemplateRef, {static: true}) templateRef!: TemplateRef<any>;
}
@Component({
selector: 'needs-content-child-template-ref-app',
template:
'<needs-content-child-template-ref>' +
'<ng-template>OUTER<ng-template>INNER</ng-template></ng-template>' +
'</needs-content-child-template-ref>',
standalone: false,
})
class NeedsContentChildTemplateRefApp {}
@Component({
selector: 'needs-view-children-read',
template: '<div #q text="va"></div><div #w text="vb"></div>',
standalone: false,
})
class NeedsViewChildrenWithRead {
@ViewChildren('q,w', {read: TextDirective}) textDirChildren!: QueryList<TextDirective>;
@ViewChildren('nonExisting', {read: TextDirective}) nonExistingVar!: QueryList<TextDirective>;
}
@Component({
selector: 'needs-view-child-read',
template: '<div #q text="va"></div>',
standalone: false,
})
class NeedsViewChildWithRead {
@ViewChild('q', {read: TextDirective}) textDirChild!: TextDirective;
@ViewChild('nonExisting', {read: TextDirective}) nonExistingVar!: TextDirective;
}
@Component({
selector: 'needs-viewcontainer-read',
template: '<div #q></div>',
standalone: false,
})
class NeedsViewContainerWithRead {
@ViewChild('q', {read: ViewContainerRef}) vc!: ViewContainerRef;
@ViewChild('nonExisting', {read: ViewContainerRef}) nonExistingVar!: ViewContainerRef;
@ContentChild(TemplateRef, {static: true}) template!: TemplateRef<Object>;
createView() {
this.vc.createEmbeddedView(this.template);
}
}
@Component({
selector: 'has-null-query-condition',
template: '<div></div>',
standalone: false,
})
class HasNullQueryCondition {
@ContentChildren(null!) errorTrigger: any;
}
@Component({
selector: 'my-comp',
template: '',
standalone: false,
})
class MyComp0 {
shouldShow: boolean = false;
list: string[] = ['1d', '2d', '3d'];
}
@Component({
selector: 'my-comp',
template: '',
standalone: false,
})
class MyCompBroken0 {}
@Component({
selector: 'manual-projecting',
template: '<div #vc></div>',
standalone: false,
})
class ManualProjecting {
@ContentChild(TemplateRef, {static: true}) template!: TemplateRef<any>;
@ViewChild('vc', {read: ViewContainerRef}) vc!: ViewContainerRef;
@ContentChildren(TextDirective) query!: QueryList<TextDirective>;
create() {
this.vc.createEmbeddedView(this.template);
}
destroy() {
this.vc.clear();
}
} | {
"end_byte": 40241,
"start_byte": 34438,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/query_integration_spec.ts"
} |
angular/packages/core/test/linker/security_integration_spec.ts_0_748 | /**
* @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, HostBinding, Input, NO_ERRORS_SCHEMA} from '@angular/core';
import {ComponentFixture, getTestBed, TestBed} from '@angular/core/testing';
import {DomSanitizer} from '@angular/platform-browser/src/security/dom_sanitization_service';
@Component({
selector: 'my-comp',
template: '',
standalone: false,
})
class SecuredComponent {
ctxProp: any = 'some value';
}
@Directive({
selector: '[onPrefixedProp]',
standalone: false,
})
class OnPrefixDir {
@Input() onPrefixedProp: any;
@Input() onclick: any;
} | {
"end_byte": 748,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/security_integration_spec.ts"
} |
angular/packages/core/test/linker/security_integration_spec.ts_750_9007 | describe('security integration tests', function () {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [SecuredComponent, OnPrefixDir],
});
});
beforeEach(() => {
// Disable logging for these tests.
spyOn(console, 'log').and.callFake(() => {});
});
describe('events', () => {
// this test is similar to the previous one, but since on-prefixed attributes validation now
// happens at runtime, we need to invoke change detection to trigger elementProperty call
it('should disallow binding to attr.on*', () => {
const template = `<div [attr.onclick]="ctxProp"></div>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
expect(() => {
const cmp = TestBed.createComponent(SecuredComponent);
cmp.detectChanges();
}).toThrowError(
/Binding to event attribute 'onclick' is disallowed for security reasons, please use \(click\)=.../,
);
});
// this test is similar to the previous one, but since on-prefixed attributes validation now
// happens at runtime, we need to invoke change detection to trigger elementProperty call
it('should disallow binding to on* with NO_ERRORS_SCHEMA', () => {
const template = `<div [onclick]="ctxProp"></div>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}}).configureTestingModule({
schemas: [NO_ERRORS_SCHEMA],
});
expect(() => {
const cmp = TestBed.createComponent(SecuredComponent);
cmp.detectChanges();
}).toThrowError(
/Binding to event property 'onclick' is disallowed for security reasons, please use \(click\)=.../,
);
});
it('should disallow binding to on* unless it is consumed by a directive', () => {
const template = `<div [onPrefixedProp]="ctxProp" [onclick]="ctxProp"></div>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}}).configureTestingModule({
schemas: [NO_ERRORS_SCHEMA],
});
// should not throw for inputs starting with "on"
let cmp: ComponentFixture<SecuredComponent> = undefined!;
expect(() => (cmp = TestBed.createComponent(SecuredComponent))).not.toThrow();
// must bind to the directive not to the property of the div
const value = (cmp.componentInstance.ctxProp = {});
cmp.detectChanges();
const div = cmp.debugElement.children[0];
expect(div.injector.get(OnPrefixDir).onclick).toBe(value);
expect(div.nativeElement.onclick).not.toBe(value);
expect(div.nativeElement.hasAttribute('onclick')).toEqual(false);
});
});
describe('safe HTML values', function () {
it('should not escape values marked as trusted', () => {
const template = `<a [href]="ctxProp">Link Title</a>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
const fixture = TestBed.createComponent(SecuredComponent);
const sanitizer: DomSanitizer = getTestBed().get(DomSanitizer);
const e = fixture.debugElement.children[0].nativeElement;
const ci = fixture.componentInstance;
const trusted = sanitizer.bypassSecurityTrustUrl('javascript:alert(1)');
ci.ctxProp = trusted;
fixture.detectChanges();
expect(e.getAttribute('href')).toEqual('javascript:alert(1)');
});
it('should error when using the wrong trusted value', () => {
const template = `<a [href]="ctxProp">Link Title</a>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
const fixture = TestBed.createComponent(SecuredComponent);
const sanitizer: DomSanitizer = getTestBed().get(DomSanitizer);
const trusted = sanitizer.bypassSecurityTrustScript('javascript:alert(1)');
const ci = fixture.componentInstance;
ci.ctxProp = trusted;
expect(() => fixture.detectChanges()).toThrowError(/Required a safe URL, got a Script/);
});
it('should warn when using in string interpolation', () => {
const template = `<a href="/foo/{{ctxProp}}">Link Title</a>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
const fixture = TestBed.createComponent(SecuredComponent);
const sanitizer: DomSanitizer = getTestBed().get(DomSanitizer);
const e = fixture.debugElement.children[0].nativeElement;
const trusted = sanitizer.bypassSecurityTrustUrl('bar/baz');
const ci = fixture.componentInstance;
ci.ctxProp = trusted;
fixture.detectChanges();
expect(e.href).toMatch(/SafeValue(%20| )must(%20| )use/);
});
});
describe('sanitizing', () => {
function checkEscapeOfHrefProperty(fixture: ComponentFixture<any>) {
const e = fixture.debugElement.children[0].nativeElement;
const ci = fixture.componentInstance;
ci.ctxProp = 'hello';
fixture.detectChanges();
expect(e.getAttribute('href')).toMatch(/.*\/?hello$/);
ci.ctxProp = 'javascript:alert(1)';
fixture.detectChanges();
expect(e.getAttribute('href')).toEqual('unsafe:javascript:alert(1)');
}
it('should escape unsafe properties', () => {
const template = `<a [href]="ctxProp">Link Title</a>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
const fixture = TestBed.createComponent(SecuredComponent);
checkEscapeOfHrefProperty(fixture);
});
it('should escape unsafe attributes', () => {
const template = `<a [attr.href]="ctxProp">Link Title</a>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
const fixture = TestBed.createComponent(SecuredComponent);
checkEscapeOfHrefProperty(fixture);
});
it('should escape unsafe properties if they are used in host bindings', () => {
@Directive({
selector: '[dirHref]',
standalone: false,
})
class HrefDirective {
@HostBinding('href') @Input() dirHref: string | undefined;
}
const template = `<a [dirHref]="ctxProp">Link Title</a>`;
TestBed.configureTestingModule({declarations: [HrefDirective]});
TestBed.overrideComponent(SecuredComponent, {set: {template}});
const fixture = TestBed.createComponent(SecuredComponent);
checkEscapeOfHrefProperty(fixture);
});
it('should escape unsafe attributes if they are used in host bindings', () => {
@Directive({
selector: '[dirHref]',
standalone: false,
})
class HrefDirective {
@HostBinding('attr.href') @Input() dirHref: string | undefined;
}
const template = `<a [dirHref]="ctxProp">Link Title</a>`;
TestBed.configureTestingModule({declarations: [HrefDirective]});
TestBed.overrideComponent(SecuredComponent, {set: {template}});
const fixture = TestBed.createComponent(SecuredComponent);
checkEscapeOfHrefProperty(fixture);
});
it('should escape unsafe SVG attributes', () => {
const template = `<svg:circle [xlink:href]="ctxProp">Text</svg:circle>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
const spy = spyOn(console, 'error');
const fixture = TestBed.createComponent(SecuredComponent);
fixture.detectChanges();
expect(spy.calls.mostRecent().args[0]).toMatch(/Can't bind to 'xlink:href'/);
});
it('should escape unsafe HTML values', () => {
const template = `<div [innerHTML]="ctxProp">Text</div>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
const fixture = TestBed.createComponent(SecuredComponent);
const e = fixture.debugElement.children[0].nativeElement;
const ci = fixture.componentInstance;
// Make sure binding harmless values works.
ci.ctxProp = 'some <p>text</p>';
fixture.detectChanges();
expect(e.innerHTML).toEqual('some <p>text</p>');
ci.ctxProp = 'ha <script>evil()</script>';
fixture.detectChanges();
expect(e.innerHTML).toEqual('ha ');
ci.ctxProp = 'also <img src="x" onerror="evil()"> evil';
fixture.detectChanges();
expect(e.innerHTML).toEqual('also <img src="x"> evil');
ci.ctxProp = 'also <iframe srcdoc="evil"></iframe> evil';
fixture.detectChanges();
expect(e.innerHTML).toEqual('also evil');
});
}); | {
"end_byte": 9007,
"start_byte": 750,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/security_integration_spec.ts"
} |
angular/packages/core/test/linker/security_integration_spec.ts_9011_10270 | describe('translation', () => {
it('should throw error on security-sensitive attributes with constant values', () => {
const template = `<iframe srcdoc="foo" i18n-srcdoc></iframe>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
expect(() => TestBed.createComponent(SecuredComponent)).toThrowError(
/Translating attribute 'srcdoc' is disallowed for security reasons./,
);
});
it('should throw error on security-sensitive attributes with interpolated values', () => {
const template = `<object i18n-data data="foo{{bar}}baz"></object>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
expect(() => TestBed.createComponent(SecuredComponent)).toThrowError(
/Translating attribute 'data' is disallowed for security reasons./,
);
});
it('should throw error on security-sensitive attributes with bound values', () => {
const template = `<div [innerHTML]="foo" i18n-innerHTML></div>`;
TestBed.overrideComponent(SecuredComponent, {set: {template}});
expect(() => TestBed.createComponent(SecuredComponent)).toThrowError(
/Translating attribute 'innerHTML' is disallowed for security reasons./,
);
});
});
}); | {
"end_byte": 10270,
"start_byte": 9011,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/security_integration_spec.ts"
} |
angular/packages/core/test/linker/change_detection_integration_spec.ts_0_3982 | /**
* @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 {ResourceLoader} from '@angular/compiler';
import {
AfterContentChecked,
AfterContentInit,
AfterViewChecked,
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
DebugElement,
Directive,
DoCheck,
EventEmitter,
HostBinding,
Injectable,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
Pipe,
PipeTransform,
Provider,
RendererFactory2,
RendererType2,
SimpleChange,
SimpleChanges,
TemplateRef,
Type,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import {ComponentFixture, fakeAsync, TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser/src/dom/debug/by';
import {isTextNode} from '@angular/platform-browser/testing/src/browser_util';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {MockResourceLoader} from './resource_loader_mock';
const TEST_COMPILER_PROVIDERS: Provider[] = [
{provide: ResourceLoader, useClass: MockResourceLoader, deps: []},
];
(function () {
let renderLog: RenderLog;
let directiveLog: DirectiveLog;
function createCompFixture<T>(template: string): ComponentFixture<TestComponent>;
function createCompFixture<T>(template: string, compType: Type<T>): ComponentFixture<T>;
function createCompFixture<T>(
template: string,
compType: Type<T> = <any>TestComponent,
): ComponentFixture<T> {
TestBed.overrideComponent(compType, {set: new Component({template})});
initHelpers();
return TestBed.createComponent(compType);
}
function initHelpers(): void {
renderLog = TestBed.inject(RenderLog);
directiveLog = TestBed.inject(DirectiveLog);
patchLoggingRenderer2(TestBed.inject(RendererFactory2), renderLog);
}
function queryDirs(el: DebugElement, dirType: Type<any>): any {
const nodes = el.queryAllNodes(By.directive(dirType));
return nodes.map((node) => node.injector.get(dirType));
}
function _bindSimpleProp<T>(bindAttr: string): ComponentFixture<TestComponent>;
function _bindSimpleProp<T>(bindAttr: string, compType: Type<T>): ComponentFixture<T>;
function _bindSimpleProp<T>(
bindAttr: string,
compType: Type<T> = <any>TestComponent,
): ComponentFixture<T> {
const template = `<div ${bindAttr}></div>`;
return createCompFixture(template, compType);
}
function _bindSimpleValue(expression: any): ComponentFixture<TestComponent>;
function _bindSimpleValue<T>(expression: any, compType: Type<T>): ComponentFixture<T>;
function _bindSimpleValue<T>(
expression: any,
compType: Type<T> = <any>TestComponent,
): ComponentFixture<T> {
return _bindSimpleProp(`[id]='${expression}'`, compType);
}
function _bindAndCheckSimpleValue(
expression: any,
compType: Type<any> = TestComponent,
): string[] {
const ctx = _bindSimpleValue(expression, compType);
ctx.detectChanges(false);
return renderLog.log;
}
describe(`ChangeDetection`, () => {
beforeEach(() => {
TestBed.configureCompiler({providers: TEST_COMPILER_PROVIDERS});
TestBed.configureTestingModule({
declarations: [
TestData,
TestDirective,
TestComponent,
AnotherComponent,
TestLocals,
CompWithRef,
WrapCompWithRef,
EmitterDirective,
PushComp,
OnDestroyDirective,
OrderCheckDirective2,
OrderCheckDirective0,
OrderCheckDirective1,
Gh9882,
Uninitialized,
Person,
PersonHolder,
PersonHolderHolder,
CountingPipe,
CountingImpurePipe,
MultiArgPipe,
PipeWithOnDestroy,
IdentityPipe,
],
providers: [RenderLog, DirectiveLog],
});
}); | {
"end_byte": 3982,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/change_detection_integration_spec.ts"
} |
angular/packages/core/test/linker/change_detection_integration_spec.ts_3988_12818 | describe('expressions', () => {
it('should support literals', fakeAsync(() => {
expect(_bindAndCheckSimpleValue(10)).toEqual(['id=10']);
}));
it('should strip quotes from literals', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('"str"')).toEqual(['id=str']);
}));
it('should support newlines in literals', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('"a\n\nb"')).toEqual(['id=a\n\nb']);
}));
it('should support + operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('10 + 2')).toEqual(['id=12']);
}));
it('should support - operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('10 - 2')).toEqual(['id=8']);
}));
it('should support * operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('10 * 2')).toEqual(['id=20']);
}));
it('should support / operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('10 / 2')).toEqual([`id=5`]);
}));
it('should support % operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('11 % 2')).toEqual(['id=1']);
}));
it('should support == operations on identical', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 == 1')).toEqual(['id=true']);
}));
it('should support != operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 != 1')).toEqual(['id=false']);
}));
it('should support == operations on coerceible', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 == true')).toEqual([`id=true`]);
}));
it('should support === operations on identical', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 === 1')).toEqual(['id=true']);
}));
it('should support !== operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 !== 1')).toEqual(['id=false']);
}));
it('should support === operations on coerceible', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 === true')).toEqual(['id=false']);
}));
it('should support true < operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 < 2')).toEqual(['id=true']);
}));
it('should support false < operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('2 < 1')).toEqual(['id=false']);
}));
it('should support false > operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 > 2')).toEqual(['id=false']);
}));
it('should support true > operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('2 > 1')).toEqual(['id=true']);
}));
it('should support true <= operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 <= 2')).toEqual(['id=true']);
}));
it('should support equal <= operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('2 <= 2')).toEqual(['id=true']);
}));
it('should support false <= operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('2 <= 1')).toEqual(['id=false']);
}));
it('should support true >= operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('2 >= 1')).toEqual(['id=true']);
}));
it('should support equal >= operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('2 >= 2')).toEqual(['id=true']);
}));
it('should support false >= operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 >= 2')).toEqual(['id=false']);
}));
it('should support true && operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('true && true')).toEqual(['id=true']);
}));
it('should support false && operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('true && false')).toEqual(['id=false']);
}));
it('should support true || operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('true || false')).toEqual(['id=true']);
}));
it('should support false || operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('false || false')).toEqual(['id=false']);
}));
it('should support negate', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('!true')).toEqual(['id=false']);
}));
it('should support double negate', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('!!true')).toEqual(['id=true']);
}));
it('should support true conditionals', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 < 2 ? 1 : 2')).toEqual(['id=1']);
}));
it('should support false conditionals', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 > 2 ? 1 : 2')).toEqual(['id=2']);
}));
it('should support keyed access to a list item', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('["foo", "bar"][0]')).toEqual(['id=foo']);
}));
it('should support keyed access to a map item', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('{"foo": "bar"}["foo"]')).toEqual(['id=bar']);
}));
it('should report all changes on the first run including uninitialized values', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('value', Uninitialized)).toEqual(['id=null']);
}));
it('should report all changes on the first run including null values', fakeAsync(() => {
const ctx = _bindSimpleValue('a', TestData);
ctx.componentInstance.a = null;
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=null']);
}));
it('should support simple chained property access', fakeAsync(() => {
const ctx = _bindSimpleValue('address.city', Person);
ctx.componentInstance.name = 'Victor';
ctx.componentInstance.address = new Address('Grenoble');
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=Grenoble']);
}));
describe('safe navigation operator', () => {
it('should support reading properties of nulls', fakeAsync(() => {
const ctx = _bindSimpleValue('address?.city', Person);
ctx.componentInstance.address = null!;
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=null']);
}));
it('should support calling methods on nulls', fakeAsync(() => {
const ctx = _bindSimpleValue('address?.toString()', Person);
ctx.componentInstance.address = null!;
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=null']);
}));
it('should support reading properties on non nulls', fakeAsync(() => {
const ctx = _bindSimpleValue('address?.city', Person);
ctx.componentInstance.address = new Address('MTV');
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=MTV']);
}));
it('should support calling methods on non nulls', fakeAsync(() => {
const ctx = _bindSimpleValue('address?.toString()', Person);
ctx.componentInstance.address = new Address('MTV');
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=MTV']);
}));
it('should support short-circuting safe navigation', fakeAsync(() => {
const ctx = _bindSimpleValue('value?.address.city', PersonHolder);
ctx.componentInstance.value = null!;
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=null']);
}));
it('should support nested short-circuting safe navigation', fakeAsync(() => {
const ctx = _bindSimpleValue('value.value?.address.city', PersonHolderHolder);
ctx.componentInstance.value = new PersonHolder();
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=null']);
}));
it('should support chained short-circuting safe navigation', fakeAsync(() => {
const ctx = _bindSimpleValue('value?.value?.address.city', PersonHolderHolder);
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=null']);
}));
it('should support short-circuting array index operations', fakeAsync(() => {
const ctx = _bindSimpleValue('value?.phones[0]', PersonHolder);
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=null']);
}));
it('should still throw if right-side would throw', fakeAsync(() => {
expect(() => {
const ctx = _bindSimpleValue('value?.address.city', PersonHolder);
const person = new Person();
person.address = null!;
ctx.componentInstance.value = person;
ctx.detectChanges(false);
}).toThrow();
}));
}); | {
"end_byte": 12818,
"start_byte": 3988,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/change_detection_integration_spec.ts"
} |
angular/packages/core/test/linker/change_detection_integration_spec.ts_12826_18159 | it('should support method calls', fakeAsync(() => {
const ctx = _bindSimpleValue('sayHi("Jim")', Person);
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=Hi, Jim']);
}));
it('should support function calls', fakeAsync(() => {
const ctx = _bindSimpleValue('a()(99)', TestData);
ctx.componentInstance.a = () => (a: any) => a;
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=99']);
}));
it('should support chained method calls', fakeAsync(() => {
const ctx = _bindSimpleValue('address.toString()', Person);
ctx.componentInstance.address = new Address('MTV');
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=MTV']);
}));
it('should support NaN', fakeAsync(() => {
const ctx = _bindSimpleValue('age', Person);
ctx.componentInstance.age = NaN;
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=NaN']);
renderLog.clear();
ctx.detectChanges(false);
expect(renderLog.log).toEqual([]);
}));
it('should do simple watching', fakeAsync(() => {
const ctx = _bindSimpleValue('name', Person);
ctx.componentInstance.name = 'misko';
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=misko']);
renderLog.clear();
ctx.detectChanges(false);
expect(renderLog.log).toEqual([]);
renderLog.clear();
ctx.componentInstance.name = 'Misko';
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=Misko']);
}));
it('should support literal array made of literals', fakeAsync(() => {
const ctx = _bindSimpleValue('[1, 2]');
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([[1, 2]]);
}));
it('should support empty literal array', fakeAsync(() => {
const ctx = _bindSimpleValue('[]');
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([[]]);
}));
it('should support literal array made of expressions', fakeAsync(() => {
const ctx = _bindSimpleValue('[1, a]', TestData);
ctx.componentInstance.a = 2;
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([[1, 2]]);
}));
it('should not recreate literal arrays unless their content changed', fakeAsync(() => {
const ctx = _bindSimpleValue('[1, a]', TestData);
ctx.componentInstance.a = 2;
ctx.detectChanges(false);
ctx.detectChanges(false);
ctx.componentInstance.a = 3;
ctx.detectChanges(false);
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([
[1, 2],
[1, 3],
]);
}));
it('should support literal maps made of literals', fakeAsync(() => {
const ctx = _bindSimpleValue('{z: 1}');
ctx.detectChanges(false);
expect(renderLog.loggedValues[0]['z']).toEqual(1);
}));
it('should support empty literal map', fakeAsync(() => {
const ctx = _bindSimpleValue('{}');
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([{}]);
}));
it('should support literal maps made of expressions', fakeAsync(() => {
const ctx = _bindSimpleValue('{z: a}');
ctx.componentInstance.a = 1;
ctx.detectChanges(false);
expect(renderLog.loggedValues[0]['z']).toEqual(1);
}));
it('should not recreate literal maps unless their content changed', fakeAsync(() => {
const ctx = _bindSimpleValue('{z: a}');
ctx.componentInstance.a = 1;
ctx.detectChanges(false);
ctx.detectChanges(false);
ctx.componentInstance.a = 2;
ctx.detectChanges(false);
ctx.detectChanges(false);
expect(renderLog.loggedValues.length).toBe(2);
expect(renderLog.loggedValues[0]['z']).toEqual(1);
expect(renderLog.loggedValues[1]['z']).toEqual(2);
}));
it('should ignore empty bindings', fakeAsync(() => {
const ctx = _bindSimpleProp('[id]', TestData);
ctx.componentInstance.a = 'value';
ctx.detectChanges(false);
expect(renderLog.log).toEqual([]);
}));
it('should support interpolation', fakeAsync(() => {
const ctx = _bindSimpleProp('id="B{{a}}A"', TestData);
ctx.componentInstance.a = 'value';
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=BvalueA']);
}));
it('should output empty strings for null values in interpolation', fakeAsync(() => {
const ctx = _bindSimpleProp('id="B{{a}}A"', TestData);
ctx.componentInstance.a = null;
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=BA']);
}));
it('should escape values in literals that indicate interpolation', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('"$"')).toEqual(['id=$']);
}));
it('should read locals', fakeAsync(() => {
const ctx = createCompFixture(
'<ng-template testLocals let-local="someLocal">{{local}}</ng-template>',
);
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['{{someLocalValue}}']);
})); | {
"end_byte": 18159,
"start_byte": 12826,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/change_detection_integration_spec.ts"
} |
angular/packages/core/test/linker/change_detection_integration_spec.ts_18167_25821 | describe('pipes', () => {
it('should use the return value of the pipe', fakeAsync(() => {
const ctx = _bindSimpleValue('name | countingPipe', Person);
ctx.componentInstance.name = 'bob';
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['bob state:0']);
}));
it('should support arguments in pipes', fakeAsync(() => {
const ctx = _bindSimpleValue('name | multiArgPipe:"one":address.city', Person);
ctx.componentInstance.name = 'value';
ctx.componentInstance.address = new Address('two');
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['value one two default']);
}));
it('should associate pipes right-to-left', fakeAsync(() => {
const ctx = _bindSimpleValue('name | multiArgPipe:"a":"b" | multiArgPipe:0:1', Person);
ctx.componentInstance.name = 'value';
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['value a b default 0 1 default']);
}));
it('should support calling pure pipes with different number of arguments', fakeAsync(() => {
const ctx = _bindSimpleValue('name | multiArgPipe:"a":"b" | multiArgPipe:0:1:2', Person);
ctx.componentInstance.name = 'value';
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['value a b default 0 1 2']);
}));
it('should do nothing when no change', fakeAsync(() => {
const ctx = _bindSimpleValue('"Megatron" | identityPipe', Person);
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['id=Megatron']);
renderLog.clear();
ctx.detectChanges(false);
expect(renderLog.log).toEqual([]);
}));
it('should call pure pipes only if the arguments change', fakeAsync(() => {
const ctx = _bindSimpleValue('name | countingPipe', Person);
// change from undefined -> null
ctx.componentInstance.name = null!;
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['null state:0']);
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['null state:0']);
// change from null -> some value
ctx.componentInstance.name = 'bob';
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['null state:0', 'bob state:1']);
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['null state:0', 'bob state:1']);
// change from some value -> some other value
ctx.componentInstance.name = 'bart';
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['null state:0', 'bob state:1', 'bart state:2']);
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['null state:0', 'bob state:1', 'bart state:2']);
}));
it('should call pure pipes that are used multiple times only when the arguments change', fakeAsync(() => {
const ctx = createCompFixture(
`<div [id]="name | countingPipe"></div><div [id]="age | countingPipe"></div>` +
'<div *ngFor="let x of [1,2]" [id]="address.city | countingPipe"></div>',
Person,
);
ctx.componentInstance.name = 'a';
ctx.componentInstance.age = 10;
ctx.componentInstance.address = new Address('mtv');
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([
'a state:0',
'10 state:0',
'mtv state:0',
'mtv state:0',
]);
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([
'a state:0',
'10 state:0',
'mtv state:0',
'mtv state:0',
]);
ctx.componentInstance.age = 11;
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([
'a state:0',
'10 state:0',
'mtv state:0',
'mtv state:0',
'11 state:1',
]);
}));
it('should call impure pipes on each change detection run', fakeAsync(() => {
const ctx = _bindSimpleValue('name | countingImpurePipe', Person);
ctx.componentInstance.name = 'bob';
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['bob state:0']);
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['bob state:0', 'bob state:1']);
}));
});
describe('event expressions', () => {
it('should support field assignments', fakeAsync(() => {
const ctx = _bindSimpleProp('(event)="b=a=$event"');
const childEl = ctx.debugElement.children[0];
const evt = 'EVENT';
childEl.triggerEventHandler('event', evt);
expect(ctx.componentInstance.a).toEqual(evt);
expect(ctx.componentInstance.b).toEqual(evt);
}));
it('should support keyed assignments', fakeAsync(() => {
const ctx = _bindSimpleProp('(event)="a[0]=$event"');
const childEl = ctx.debugElement.children[0];
ctx.componentInstance.a = ['OLD'];
const evt = 'EVENT';
childEl.triggerEventHandler('event', evt);
expect(ctx.componentInstance.a).toEqual([evt]);
}));
it('should support chains', fakeAsync(() => {
const ctx = _bindSimpleProp('(event)="a=a+1; a=a+1;"');
const childEl = ctx.debugElement.children[0];
ctx.componentInstance.a = 0;
childEl.triggerEventHandler('event', 'EVENT');
expect(ctx.componentInstance.a).toEqual(2);
}));
it('should support empty literals', fakeAsync(() => {
const ctx = _bindSimpleProp('(event)="a=[{},[]]"');
const childEl = ctx.debugElement.children[0];
childEl.triggerEventHandler('event', 'EVENT');
expect(ctx.componentInstance.a).toEqual([{}, []]);
}));
xit('should throw when trying to assign to a local', fakeAsync(() => {
expect(() => {
_bindSimpleProp('(event)="$event=1"');
}).toThrowError(
new RegExp(
'Cannot assign value (.*) to template variable (.*). Template variables are read-only.',
),
);
}));
it('should support short-circuiting', fakeAsync(() => {
const ctx = _bindSimpleProp('(event)="true ? a = a + 1 : a = a + 1"');
const childEl = ctx.debugElement.children[0];
ctx.componentInstance.a = 0;
childEl.triggerEventHandler('event', 'EVENT');
expect(ctx.componentInstance.a).toEqual(1);
}));
});
});
describe('RendererFactory', () => {
it('should call the begin and end methods on the renderer factory when change detection is called', fakeAsync(() => {
const ctx = createCompFixture('<div testDirective [a]="42"></div>');
const rf = TestBed.inject(RendererFactory2);
// TODO: @JiaLiPassion, need to wait @types/jasmine to fix the
// optional method infer issue.
// https://github.com/DefinitelyTyped/DefinitelyTyped/issues/43486
spyOn(rf as any, 'begin');
spyOn(rf as any, 'end');
expect(rf.begin).not.toHaveBeenCalled();
expect(rf.end).not.toHaveBeenCalled();
ctx.detectChanges(false);
expect(rf.begin).toHaveBeenCalled();
expect(rf.end).toHaveBeenCalled();
}));
}); | {
"end_byte": 25821,
"start_byte": 18167,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/change_detection_integration_spec.ts"
} |
angular/packages/core/test/linker/change_detection_integration_spec.ts_25827_27481 | describe('change notification', () => {
describe('updating directives', () => {
it('should happen without invoking the renderer', fakeAsync(() => {
const ctx = createCompFixture('<div testDirective [a]="42"></div>');
ctx.detectChanges(false);
expect(renderLog.log).toEqual([]);
expect(queryDirs(ctx.debugElement, TestDirective)[0].a).toEqual(42);
}));
});
describe('reading directives', () => {
it('should read directive properties', fakeAsync(() => {
const ctx = createCompFixture(
'<div testDirective [a]="42" ref-dir="testDirective" [id]="dir.a"></div>',
);
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([42]);
}));
});
describe('ngOnChanges', () => {
it('should notify the directive when a group of records changes', fakeAsync(() => {
const ctx = createCompFixture(
'<div [testDirective]="\'aName\'" [a]="1" [b]="2"></div><div [testDirective]="\'bName\'" [a]="4"></div>',
);
ctx.detectChanges(false);
const dirs = <TestDirective[]>queryDirs(ctx.debugElement, TestDirective);
expect(dirs[0].changes).toEqual({
'a': new SimpleChange(undefined, 1, true),
'b': new SimpleChange(undefined, 2, true),
'name': new SimpleChange(undefined, 'aName', true),
});
expect(dirs[1].changes).toEqual({
'a': new SimpleChange(undefined, 4, true),
'name': new SimpleChange(undefined, 'bName', true),
});
}));
});
}); | {
"end_byte": 27481,
"start_byte": 25827,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/change_detection_integration_spec.ts"
} |
angular/packages/core/test/linker/change_detection_integration_spec.ts_27487_35638 | describe('lifecycle', () => {
function createCompWithContentAndViewChild(): ComponentFixture<any> {
TestBed.overrideComponent(AnotherComponent, {
set: new Component({
selector: 'other-cmp',
template: '<div testDirective="viewChild"></div>',
}),
});
return createCompFixture(
'<div testDirective="parent"><div *ngIf="true" testDirective="contentChild"></div><other-cmp></other-cmp></div>',
TestComponent,
);
}
describe('ngOnInit', () => {
it('should be called after ngOnChanges', fakeAsync(() => {
const ctx = createCompFixture('<div testDirective="dir"></div>');
expect(directiveLog.filter(['ngOnInit', 'ngOnChanges'])).toEqual([]);
ctx.detectChanges(false);
expect(directiveLog.filter(['ngOnInit', 'ngOnChanges'])).toEqual([
'dir.ngOnChanges',
'dir.ngOnInit',
]);
directiveLog.clear();
ctx.detectChanges(false);
expect(directiveLog.filter(['ngOnInit'])).toEqual([]);
}));
it('should only be called only once', fakeAsync(() => {
const ctx = createCompFixture('<div testDirective="dir"></div>');
ctx.detectChanges(false);
expect(directiveLog.filter(['ngOnInit'])).toEqual(['dir.ngOnInit']);
// reset directives
directiveLog.clear();
// Verify that checking should not call them.
ctx.checkNoChanges();
expect(directiveLog.filter(['ngOnInit'])).toEqual([]);
// re-verify that changes should not call them
ctx.detectChanges(false);
expect(directiveLog.filter(['ngOnInit'])).toEqual([]);
}));
it('should not call ngOnInit again if it throws', fakeAsync(() => {
const ctx = createCompFixture('<div testDirective="dir" throwOn="ngOnInit"></div>');
let errored = false;
// First pass fails, but ngOnInit should be called.
try {
ctx.detectChanges(false);
} catch (e) {
expect((e as Error).message).toBe('Boom!');
errored = true;
}
expect(errored).toBe(true);
expect(directiveLog.filter(['ngOnInit'])).toEqual(['dir.ngOnInit']);
directiveLog.clear();
// Second change detection also fails, but this time ngOnInit should not be called.
try {
ctx.detectChanges(false);
} catch (e) {
expect((e as Error).message).toBe('Boom!');
throw new Error('Second detectChanges() should not have called ngOnInit.');
}
expect(directiveLog.filter(['ngOnInit'])).toEqual([]);
}));
});
describe('ngDoCheck', () => {
it('should be called after ngOnInit', fakeAsync(() => {
const ctx = createCompFixture('<div testDirective="dir"></div>');
ctx.detectChanges(false);
expect(directiveLog.filter(['ngDoCheck', 'ngOnInit'])).toEqual([
'dir.ngOnInit',
'dir.ngDoCheck',
]);
}));
it('should be called on every detectChanges run, except for checkNoChanges', fakeAsync(() => {
const ctx = createCompFixture('<div testDirective="dir"></div>');
ctx.detectChanges(false);
expect(directiveLog.filter(['ngDoCheck'])).toEqual(['dir.ngDoCheck']);
// reset directives
directiveLog.clear();
// Verify that checking should not call them.
ctx.checkNoChanges();
expect(directiveLog.filter(['ngDoCheck'])).toEqual([]);
// re-verify that changes are still detected
ctx.detectChanges(false);
expect(directiveLog.filter(['ngDoCheck'])).toEqual(['dir.ngDoCheck']);
}));
});
describe('ngAfterContentInit', () => {
it('should be called after processing the content children but before the view children', fakeAsync(() => {
const ctx = createCompWithContentAndViewChild();
ctx.detectChanges(false);
expect(directiveLog.filter(['ngDoCheck', 'ngAfterContentInit'])).toEqual([
'parent.ngDoCheck',
'contentChild.ngDoCheck',
'contentChild.ngAfterContentInit',
'parent.ngAfterContentInit',
'viewChild.ngDoCheck',
'viewChild.ngAfterContentInit',
]);
}));
it('should only be called only once', fakeAsync(() => {
const ctx = createCompFixture('<div testDirective="dir"></div>');
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterContentInit'])).toEqual(['dir.ngAfterContentInit']);
// reset directives
directiveLog.clear();
// Verify that checking should not call them.
ctx.checkNoChanges();
expect(directiveLog.filter(['ngAfterContentInit'])).toEqual([]);
// re-verify that changes should not call them
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterContentInit'])).toEqual([]);
}));
it('should not call ngAfterContentInit again if it throws', fakeAsync(() => {
const ctx = createCompFixture(
'<div testDirective="dir" throwOn="ngAfterContentInit"></div>',
);
let errored = false;
// First pass fails, but ngAfterContentInit should be called.
try {
ctx.detectChanges(false);
} catch (e) {
errored = true;
}
expect(errored).toBe(true);
expect(directiveLog.filter(['ngAfterContentInit'])).toEqual(['dir.ngAfterContentInit']);
directiveLog.clear();
// Second change detection also fails, but this time ngAfterContentInit should not be
// called.
try {
ctx.detectChanges(false);
} catch (e) {
throw new Error('Second detectChanges() should not have run detection.');
}
expect(directiveLog.filter(['ngAfterContentInit'])).toEqual([]);
}));
});
describe('ngAfterContentChecked', () => {
it('should be called after the content children but before the view children', fakeAsync(() => {
const ctx = createCompWithContentAndViewChild();
ctx.detectChanges(false);
expect(directiveLog.filter(['ngDoCheck', 'ngAfterContentChecked'])).toEqual([
'parent.ngDoCheck',
'contentChild.ngDoCheck',
'contentChild.ngAfterContentChecked',
'parent.ngAfterContentChecked',
'viewChild.ngDoCheck',
'viewChild.ngAfterContentChecked',
]);
}));
it('should be called on every detectChanges run, except for checkNoChanges', fakeAsync(() => {
const ctx = createCompFixture('<div testDirective="dir"></div>');
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterContentChecked'])).toEqual([
'dir.ngAfterContentChecked',
]);
// reset directives
directiveLog.clear();
// Verify that checking should not call them.
ctx.checkNoChanges();
expect(directiveLog.filter(['ngAfterContentChecked'])).toEqual([]);
// re-verify that changes are still detected
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterContentChecked'])).toEqual([
'dir.ngAfterContentChecked',
]);
}));
it('should be called in reverse order so the child is always notified before the parent', fakeAsync(() => {
const ctx = createCompFixture(
'<div testDirective="parent"><div testDirective="child"></div></div><div testDirective="sibling"></div>',
);
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterContentChecked'])).toEqual([
'child.ngAfterContentChecked',
'parent.ngAfterContentChecked',
'sibling.ngAfterContentChecked',
]);
}));
}); | {
"end_byte": 35638,
"start_byte": 27487,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/change_detection_integration_spec.ts"
} |
angular/packages/core/test/linker/change_detection_integration_spec.ts_35646_42791 | describe('ngAfterViewInit', () => {
it('should be called after processing the view children', fakeAsync(() => {
const ctx = createCompWithContentAndViewChild();
ctx.detectChanges(false);
expect(directiveLog.filter(['ngDoCheck', 'ngAfterViewInit'])).toEqual([
'parent.ngDoCheck',
'contentChild.ngDoCheck',
'contentChild.ngAfterViewInit',
'viewChild.ngDoCheck',
'viewChild.ngAfterViewInit',
'parent.ngAfterViewInit',
]);
}));
it('should only be called only once', fakeAsync(() => {
const ctx = createCompFixture('<div testDirective="dir"></div>');
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterViewInit'])).toEqual(['dir.ngAfterViewInit']);
// reset directives
directiveLog.clear();
// Verify that checking should not call them.
ctx.checkNoChanges();
expect(directiveLog.filter(['ngAfterViewInit'])).toEqual([]);
// re-verify that changes should not call them
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterViewInit'])).toEqual([]);
}));
it('should not call ngAfterViewInit again if it throws', fakeAsync(() => {
const ctx = createCompFixture(
'<div testDirective="dir" throwOn="ngAfterViewInit"></div>',
);
let errored = false;
// First pass fails, but ngAfterViewInit should be called.
try {
ctx.detectChanges(false);
} catch (e) {
errored = true;
}
expect(errored).toBe(true);
expect(directiveLog.filter(['ngAfterViewInit'])).toEqual(['dir.ngAfterViewInit']);
directiveLog.clear();
// Second change detection also fails, but this time ngAfterViewInit should not be
// called.
try {
ctx.detectChanges(false);
} catch (e) {
throw new Error('Second detectChanges() should not have run detection.');
}
expect(directiveLog.filter(['ngAfterViewInit'])).toEqual([]);
}));
});
describe('ngAfterViewChecked', () => {
it('should be called after processing the view children', fakeAsync(() => {
const ctx = createCompWithContentAndViewChild();
ctx.detectChanges(false);
expect(directiveLog.filter(['ngDoCheck', 'ngAfterViewChecked'])).toEqual([
'parent.ngDoCheck',
'contentChild.ngDoCheck',
'contentChild.ngAfterViewChecked',
'viewChild.ngDoCheck',
'viewChild.ngAfterViewChecked',
'parent.ngAfterViewChecked',
]);
}));
it('should be called on every detectChanges run, except for checkNoChanges', fakeAsync(() => {
const ctx = createCompFixture('<div testDirective="dir"></div>');
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterViewChecked'])).toEqual(['dir.ngAfterViewChecked']);
// reset directives
directiveLog.clear();
// Verify that checking should not call them.
ctx.checkNoChanges();
expect(directiveLog.filter(['ngAfterViewChecked'])).toEqual([]);
// re-verify that changes are still detected
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterViewChecked'])).toEqual(['dir.ngAfterViewChecked']);
}));
it('should be called in reverse order so the child is always notified before the parent', fakeAsync(() => {
const ctx = createCompFixture(
'<div testDirective="parent"><div testDirective="child"></div></div><div testDirective="sibling"></div>',
);
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterViewChecked'])).toEqual([
'child.ngAfterViewChecked',
'parent.ngAfterViewChecked',
'sibling.ngAfterViewChecked',
]);
}));
});
describe('ngOnDestroy', () => {
it('should be called on view destruction', fakeAsync(() => {
const ctx = createCompFixture('<div testDirective="dir"></div>');
ctx.detectChanges(false);
ctx.destroy();
expect(directiveLog.filter(['ngOnDestroy'])).toEqual(['dir.ngOnDestroy']);
}));
it('should be called after processing the content and view children', fakeAsync(() => {
TestBed.overrideComponent(AnotherComponent, {
set: new Component({
selector: 'other-cmp',
template: '<div testDirective="viewChild"></div>',
}),
});
const ctx = createCompFixture(
'<div testDirective="parent"><div *ngFor="let x of [0,1]" testDirective="contentChild{{x}}"></div>' +
'<other-cmp></other-cmp></div>',
TestComponent,
);
ctx.detectChanges(false);
ctx.destroy();
expect(directiveLog.filter(['ngOnDestroy'])).toEqual([
'contentChild0.ngOnDestroy',
'contentChild1.ngOnDestroy',
'viewChild.ngOnDestroy',
'parent.ngOnDestroy',
]);
}));
it('should be called in reverse order so the child is always notified before the parent', fakeAsync(() => {
const ctx = createCompFixture(
'<div testDirective="parent"><div testDirective="child"></div></div><div testDirective="sibling"></div>',
);
ctx.detectChanges(false);
ctx.destroy();
expect(directiveLog.filter(['ngOnDestroy'])).toEqual([
'child.ngOnDestroy',
'parent.ngOnDestroy',
'sibling.ngOnDestroy',
]);
}));
it('should deliver synchronous events to parent', fakeAsync(() => {
const ctx = createCompFixture('<div (destroy)="a=$event" onDestroyDirective></div>');
ctx.detectChanges(false);
ctx.destroy();
expect(ctx.componentInstance.a).toEqual('destroyed');
}));
it('should call ngOnDestroy on pipes', fakeAsync(() => {
const ctx = createCompFixture('{{true | pipeWithOnDestroy }}');
ctx.detectChanges(false);
ctx.destroy();
expect(directiveLog.filter(['ngOnDestroy'])).toEqual(['pipeWithOnDestroy.ngOnDestroy']);
}));
it('should call ngOnDestroy on an injectable class', fakeAsync(() => {
TestBed.overrideDirective(TestDirective, {set: {providers: [InjectableWithLifecycle]}});
const ctx = createCompFixture('<div testDirective="dir"></div>', TestComponent);
ctx.debugElement.children[0].injector.get(InjectableWithLifecycle);
ctx.detectChanges(false);
ctx.destroy();
// We don't care about the exact order in this test.
expect(directiveLog.filter(['ngOnDestroy']).sort()).toEqual([
'dir.ngOnDestroy',
'injectable.ngOnDestroy',
]);
}));
});
}); | {
"end_byte": 42791,
"start_byte": 35646,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/change_detection_integration_spec.ts"
} |
angular/packages/core/test/linker/change_detection_integration_spec.ts_42797_47993 | describe('enforce no new changes', () => {
it('should throw when a record gets changed after it has been checked', fakeAsync(() => {
@Directive({
selector: '[changed]',
standalone: false,
})
class ChangingDirective {
@Input() changed: any;
}
TestBed.configureTestingModule({declarations: [ChangingDirective]});
const ctx = createCompFixture('<div [id]="a" [changed]="b"></div>', TestData);
ctx.componentInstance.b = 1;
const errMsgRegExp = /Previous value: 'undefined'\. Current value: '1'/g;
expect(() => ctx.checkNoChanges()).toThrowError(errMsgRegExp);
}));
it('should throw when a record gets changed after the first change detection pass', fakeAsync(() => {
@Directive({
selector: '[changed]',
standalone: false,
})
class ChangingDirective {
@Input() changed: any;
}
TestBed.configureTestingModule({declarations: [ChangingDirective]});
const ctx = createCompFixture('<div [id]="a" [changed]="b"></div>', TestData);
ctx.componentInstance.b = 1;
ctx.detectChanges();
ctx.componentInstance.b = 2;
const errMsgRegExp = /Previous value: '1'\. Current value: '2'/g;
expect(() => ctx.checkNoChanges()).toThrowError(errMsgRegExp);
}));
it('should allow view to be created in a cd hook', () => {
const ctx = createCompFixture('<div *gh9882>{{ a }}</div>', TestData);
ctx.componentInstance.a = 1;
ctx.detectChanges();
expect(ctx.nativeElement.innerText).toEqual('1');
});
it('should not throw when two arrays are structurally the same', fakeAsync(() => {
const ctx = _bindSimpleValue('a', TestData);
ctx.componentInstance.a = ['value'];
ctx.detectChanges(false);
ctx.componentInstance.a = ['value'];
expect(() => ctx.checkNoChanges()).not.toThrow();
}));
it('should not break the next run', fakeAsync(() => {
const ctx = _bindSimpleValue('a', TestData);
ctx.componentInstance.a = 'value';
expect(() => ctx.checkNoChanges()).toThrow();
ctx.detectChanges();
expect(renderLog.loggedValues).toEqual(['value']);
}));
it('should not break the next run (view engine and ivy)', fakeAsync(() => {
const ctx = _bindSimpleValue('a', TestData);
ctx.detectChanges();
renderLog.clear();
ctx.componentInstance.a = 'value';
expect(() => ctx.checkNoChanges()).toThrow();
ctx.detectChanges();
expect(renderLog.loggedValues).toEqual(['value']);
}));
});
describe('mode', () => {
it('Detached', fakeAsync(() => {
const ctx = createCompFixture('<comp-with-ref></comp-with-ref>');
const cmp: CompWithRef = queryDirs(ctx.debugElement, CompWithRef)[0];
cmp.value = 'hello';
cmp.changeDetectorRef.detach();
ctx.detectChanges();
expect(renderLog.log).toEqual([]);
}));
it('Detached should disable OnPush', fakeAsync(() => {
const ctx = createCompFixture('<push-cmp [value]="value"></push-cmp>');
ctx.componentInstance.value = 0;
ctx.detectChanges();
renderLog.clear();
const cmp: CompWithRef = queryDirs(ctx.debugElement, PushComp)[0];
cmp.changeDetectorRef.detach();
ctx.componentInstance.value = 1;
ctx.detectChanges();
expect(renderLog.log).toEqual([]);
}));
it('Detached view can be checked locally', fakeAsync(() => {
const ctx = createCompFixture('<wrap-comp-with-ref></wrap-comp-with-ref>');
const cmp: CompWithRef = queryDirs(ctx.debugElement, CompWithRef)[0];
cmp.value = 'hello';
cmp.changeDetectorRef.detach();
expect(renderLog.log).toEqual([]);
ctx.detectChanges();
expect(renderLog.log).toEqual([]);
cmp.changeDetectorRef.detectChanges();
expect(renderLog.log).toEqual(['{{hello}}']);
}));
it('Reattaches', fakeAsync(() => {
const ctx = createCompFixture('<comp-with-ref></comp-with-ref>');
const cmp: CompWithRef = queryDirs(ctx.debugElement, CompWithRef)[0];
cmp.value = 'hello';
cmp.changeDetectorRef.detach();
ctx.detectChanges();
expect(renderLog.log).toEqual([]);
cmp.changeDetectorRef.reattach();
ctx.detectChanges();
expect(renderLog.log).toEqual(['{{hello}}']);
}));
it('Reattaches in the original cd mode', fakeAsync(() => {
const ctx = createCompFixture('<push-cmp></push-cmp>');
const cmp: PushComp = queryDirs(ctx.debugElement, PushComp)[0];
cmp.changeDetectorRef.detach();
cmp.changeDetectorRef.reattach();
// renderCount should NOT be incremented with each CD as CD mode
// should be resetted to
// on-push
ctx.detectChanges();
expect(cmp.renderCount).toBeGreaterThan(0);
const count = cmp.renderCount;
ctx.detectChanges();
expect(cmp.renderCount).toBe(count);
}));
}); | {
"end_byte": 47993,
"start_byte": 42797,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/change_detection_integration_spec.ts"
} |
angular/packages/core/test/linker/change_detection_integration_spec.ts_47999_54304 | describe('nested view recursion', () => {
it('should recurse into nested components even if there are no bindings in the component view', () => {
@Component({
selector: 'nested',
template: '{{name}}',
standalone: false,
})
class Nested {
name = 'Tom';
}
TestBed.configureTestingModule({declarations: [Nested]});
const ctx = createCompFixture('<nested></nested>');
ctx.detectChanges();
expect(renderLog.loggedValues).toEqual(['Tom']);
});
it('should recurse into nested view containers even if there are no bindings in the component view', () => {
@Component({
template: '<ng-template #vc>{{name}}</ng-template>',
standalone: false,
})
class Comp {
name = 'Tom';
@ViewChild('vc', {read: ViewContainerRef, static: true}) vc!: ViewContainerRef;
@ViewChild(TemplateRef, {static: true}) template!: TemplateRef<any>;
}
TestBed.configureTestingModule({declarations: [Comp]});
initHelpers();
const ctx = TestBed.createComponent(Comp);
ctx.detectChanges();
expect(renderLog.loggedValues).toEqual([]);
ctx.componentInstance.vc.createEmbeddedView(ctx.componentInstance.template);
ctx.detectChanges();
expect(renderLog.loggedValues).toEqual(['Tom']);
});
describe('projected views', () => {
let log: string[];
@Directive({
selector: '[i]',
standalone: false,
})
class DummyDirective {
@Input() i: any;
}
@Component({
selector: 'main-cmp',
template: `<span [i]="log('start')"></span><outer-cmp><ng-template><span [i]="log('tpl')"></span></ng-template></outer-cmp>`,
standalone: false,
})
class MainComp {
constructor(public cdRef: ChangeDetectorRef) {}
log(id: string) {
log.push(`main-${id}`);
}
}
@Component({
selector: 'outer-cmp',
template: `<span [i]="log('start')"></span><inner-cmp [outerTpl]="tpl"><ng-template><span [i]="log('tpl')"></span></ng-template></inner-cmp>`,
standalone: false,
})
class OuterComp {
@ContentChild(TemplateRef, {static: true}) tpl!: TemplateRef<any>;
constructor(public cdRef: ChangeDetectorRef) {}
log(id: string) {
log.push(`outer-${id}`);
}
}
@Component({
selector: 'inner-cmp',
template: `<span [i]="log('start')"></span>><ng-container [ngTemplateOutlet]="outerTpl"></ng-container><ng-container [ngTemplateOutlet]="tpl"></ng-container>`,
standalone: false,
})
class InnerComp {
@ContentChild(TemplateRef, {static: true}) tpl!: TemplateRef<any>;
@Input() outerTpl: TemplateRef<any> | undefined;
constructor(public cdRef: ChangeDetectorRef) {}
log(id: string) {
log.push(`inner-${id}`);
}
}
let ctx: ComponentFixture<MainComp>;
let mainComp: MainComp;
let outerComp: OuterComp;
let innerComp: InnerComp;
beforeEach(() => {
log = [];
ctx = TestBed.configureTestingModule({
declarations: [MainComp, OuterComp, InnerComp, DummyDirective],
}).createComponent(MainComp);
mainComp = ctx.componentInstance;
outerComp = ctx.debugElement.query(By.directive(OuterComp)).injector.get(OuterComp);
innerComp = ctx.debugElement.query(By.directive(InnerComp)).injector.get(InnerComp);
});
it('should dirty check projected views in regular order', () => {
ctx.detectChanges(false);
expect(log).toEqual([
'main-start',
'outer-start',
'inner-start',
'main-tpl',
'outer-tpl',
]);
log = [];
ctx.detectChanges(false);
expect(log).toEqual([
'main-start',
'outer-start',
'inner-start',
'main-tpl',
'outer-tpl',
]);
});
it('should not dirty check projected views if neither the declaration nor the insertion place is dirty checked', () => {
ctx.detectChanges(false);
log = [];
mainComp.cdRef.detach();
ctx.detectChanges(false);
expect(log).toEqual([]);
});
it('should dirty check projected views if the insertion place is dirty checked', () => {
ctx.detectChanges(false);
log = [];
innerComp.cdRef.detectChanges();
expect(log).toEqual(['inner-start', 'main-tpl', 'outer-tpl']);
});
it('should not dirty check views that are inserted into a detached tree, even if the declaration place is dirty checked', () => {
ctx.detectChanges(false);
log = [];
innerComp.cdRef.detach();
mainComp.cdRef.detectChanges();
expect(log).toEqual(['main-start', 'outer-start']);
log = [];
outerComp.cdRef.detectChanges();
expect(log).toEqual(['outer-start']);
log = [];
outerComp.cdRef.detach();
mainComp.cdRef.detectChanges();
expect(log).toEqual(['main-start']);
});
});
});
describe('class binding', () => {
it('should coordinate class attribute and class host binding', () => {
@Component({
template: `<div class="{{initClasses}}" someDir></div>`,
standalone: false,
})
class Comp {
initClasses = 'init';
}
@Directive({
selector: '[someDir]',
standalone: false,
})
class SomeDir {
@HostBinding('class.foo') fooClass = true;
}
const ctx = TestBed.configureTestingModule({declarations: [Comp, SomeDir]}).createComponent(
Comp,
);
ctx.detectChanges();
const divEl = ctx.debugElement.children[0];
expect(divEl.nativeElement).toHaveCssClass('init');
expect(divEl.nativeElement).toHaveCssClass('foo');
});
}); | {
"end_byte": 54304,
"start_byte": 47999,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/change_detection_integration_spec.ts"
} |
angular/packages/core/test/linker/change_detection_integration_spec.ts_54310_63343 | describe('lifecycle asserts', () => {
let logged: string[];
function log(value: string) {
logged.push(value);
}
function clearLog() {
logged = [];
}
function expectOnceAndOnlyOnce(log: string) {
expect(logged.indexOf(log) >= 0).toBeTruthy(
`'${log}' not logged. Log was ${JSON.stringify(logged)}`,
);
expect(logged.lastIndexOf(log) === logged.indexOf(log)).toBeTruthy(
`'${log}' logged more than once. Log was ${JSON.stringify(logged)}`,
);
}
beforeEach(() => {
clearLog();
});
enum LifetimeMethods {
None = 0,
ngOnInit = 1 << 0,
ngOnChanges = 1 << 1,
ngAfterViewInit = 1 << 2,
ngAfterContentInit = 1 << 3,
ngDoCheck = 1 << 4,
InitMethods = ngOnInit | ngAfterViewInit | ngAfterContentInit,
InitMethodsAndChanges = InitMethods | ngOnChanges,
All = InitMethodsAndChanges | ngDoCheck,
}
function forEachMethod(methods: LifetimeMethods, cb: (method: LifetimeMethods) => void) {
if (methods & LifetimeMethods.ngOnInit) cb(LifetimeMethods.ngOnInit);
if (methods & LifetimeMethods.ngOnChanges) cb(LifetimeMethods.ngOnChanges);
if (methods & LifetimeMethods.ngAfterContentInit) cb(LifetimeMethods.ngAfterContentInit);
if (methods & LifetimeMethods.ngAfterViewInit) cb(LifetimeMethods.ngAfterViewInit);
if (methods & LifetimeMethods.ngDoCheck) cb(LifetimeMethods.ngDoCheck);
}
interface Options {
childRecursion: LifetimeMethods;
childThrows: LifetimeMethods;
}
describe('calling init', () => {
function initialize(options: Options) {
@Component({
selector: 'my-child',
template: '',
standalone: false,
})
class MyChild {
private thrown = LifetimeMethods.None;
@Input() inp: boolean | undefined;
@Output() outp = new EventEmitter<any>();
constructor() {}
ngDoCheck() {
this.check(LifetimeMethods.ngDoCheck);
}
ngOnInit() {
this.check(LifetimeMethods.ngOnInit);
}
ngOnChanges() {
this.check(LifetimeMethods.ngOnChanges);
}
ngAfterViewInit() {
this.check(LifetimeMethods.ngAfterViewInit);
}
ngAfterContentInit() {
this.check(LifetimeMethods.ngAfterContentInit);
}
private check(method: LifetimeMethods) {
log(`MyChild::${LifetimeMethods[method]}()`);
if ((options.childRecursion & method) !== 0) {
if (logged.length < 20) {
this.outp.emit(null);
} else {
fail(`Unexpected MyChild::${LifetimeMethods[method]} recursion`);
}
}
if ((options.childThrows & method) !== 0) {
if ((this.thrown & method) === 0) {
this.thrown |= method;
log(`<THROW from MyChild::${LifetimeMethods[method]}>()`);
throw new Error(`Throw from MyChild::${LifetimeMethods[method]}`);
}
}
}
}
@Component({
selector: 'my-component',
template: `<my-child [inp]='true' (outp)='onOutp()'></my-child>`,
standalone: false,
})
class MyComponent {
constructor(private changeDetectionRef: ChangeDetectorRef) {}
ngDoCheck() {
this.check(LifetimeMethods.ngDoCheck);
}
ngOnInit() {
this.check(LifetimeMethods.ngOnInit);
}
ngAfterViewInit() {
this.check(LifetimeMethods.ngAfterViewInit);
}
ngAfterContentInit() {
this.check(LifetimeMethods.ngAfterContentInit);
}
onOutp() {
log('<RECURSION START>');
this.changeDetectionRef.detectChanges();
log('<RECURSION DONE>');
}
private check(method: LifetimeMethods) {
log(`MyComponent::${LifetimeMethods[method]}()`);
}
}
TestBed.configureTestingModule({declarations: [MyChild, MyComponent]});
return createCompFixture(`<my-component></my-component>`);
}
function ensureOneInit(options: Options) {
const ctx = initialize(options);
const throws = options.childThrows != LifetimeMethods.None;
if (throws) {
log(`<CYCLE 0 START>`);
expect(() => {
// Expect child to throw.
ctx.detectChanges();
}).toThrow();
log(`<CYCLE 0 END>`);
log(`<CYCLE 1 START>`);
}
ctx.detectChanges();
if (throws) log(`<CYCLE 1 DONE>`);
expectOnceAndOnlyOnce('MyComponent::ngOnInit()');
expectOnceAndOnlyOnce('MyChild::ngOnInit()');
expectOnceAndOnlyOnce('MyComponent::ngAfterViewInit()');
expectOnceAndOnlyOnce('MyComponent::ngAfterContentInit()');
expectOnceAndOnlyOnce('MyChild::ngAfterViewInit()');
expectOnceAndOnlyOnce('MyChild::ngAfterContentInit()');
}
forEachMethod(LifetimeMethods.InitMethodsAndChanges, (method) => {
it(`should ensure that init hooks are called once an only once with recursion in ${LifetimeMethods[method]} `, () => {
// Ensure all the init methods are called once.
ensureOneInit({childRecursion: method, childThrows: LifetimeMethods.None});
});
});
forEachMethod(LifetimeMethods.All, (method) => {
it(`should ensure that init hooks are called once an only once with a throw in ${LifetimeMethods[method]} `, () => {
// Ensure all the init methods are called once.
// the first cycle throws but the next cycle should complete the inits.
ensureOneInit({childRecursion: LifetimeMethods.None, childThrows: method});
});
});
});
});
});
})();
@Injectable()
class RenderLog {
log: string[] = [];
loggedValues: any[] = [];
setElementProperty(el: any, propName: string, propValue: any) {
this.log.push(`${propName}=${propValue}`);
this.loggedValues.push(propValue);
}
setText(node: any, value: string) {
this.log.push(`{{${value}}}`);
this.loggedValues.push(value);
}
clear() {
this.log = [];
this.loggedValues = [];
}
}
class DirectiveLogEntry {
constructor(
public directiveName: string,
public method: string,
) {}
}
function patchLoggingRenderer2(rendererFactory: RendererFactory2, log: RenderLog) {
if ((<any>rendererFactory).__patchedForLogging) {
return;
}
(<any>rendererFactory).__patchedForLogging = true;
const origCreateRenderer = rendererFactory.createRenderer;
rendererFactory.createRenderer = function (element: any, type: RendererType2 | null) {
const renderer = origCreateRenderer.call(this, element, type);
if ((<any>renderer).__patchedForLogging) {
return renderer;
}
(<any>renderer).__patchedForLogging = true;
const origSetProperty = renderer.setProperty;
const origSetValue = renderer.setValue;
renderer.setProperty = function (el: any, name: string, value: any): void {
log.setElementProperty(el, name, value);
origSetProperty.call(renderer, el, name, value);
};
renderer.setValue = function (node: any, value: string): void {
if (isTextNode(node)) {
log.setText(node, value);
}
origSetValue.call(renderer, node, value);
};
return renderer;
};
}
@Injectable()
class DirectiveLog {
entries: DirectiveLogEntry[] = [];
add(directiveName: string, method: string) {
this.entries.push(new DirectiveLogEntry(directiveName, method));
}
clear() {
this.entries = [];
}
filter(methods: string[]): string[] {
return this.entries
.filter((entry) => methods.indexOf(entry.method) !== -1)
.map((entry) => `${entry.directiveName}.${entry.method}`);
}
}
@Pipe({
name: 'countingPipe',
standalone: false,
})
class CountingPipe implements PipeTransform {
state: number = 0;
transform(value: any) {
return `${value} state:${this.state++}`;
}
}
@Pipe({
name: 'countingImpurePipe',
pure: false,
standalone: false,
})
class CountingImpurePipe implements PipeTransform {
state: number = 0;
transform(value: any) {
return `${value} state:${this.state++}`;
}
}
@Pipe({
name: 'pipeWithOnDestroy',
standalone: false,
})
class PipeWithOnDestroy implements PipeTransform, OnDestroy {
constructor(private directiveLog: DirectiveLog) {}
ngOnDestroy() {
this.directiveLog.add('pipeWithOnDestroy', 'ngOnDestroy');
}
transform(value: any): any {
return null;
}
} | {
"end_byte": 63343,
"start_byte": 54310,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/change_detection_integration_spec.ts"
} |
angular/packages/core/test/linker/change_detection_integration_spec.ts_63345_70576 | @Pipe({
name: 'identityPipe',
standalone: false,
})
class IdentityPipe implements PipeTransform {
transform(value: any) {
return value;
}
}
@Pipe({
name: 'multiArgPipe',
standalone: false,
})
class MultiArgPipe implements PipeTransform {
transform(value: any, arg1: any, arg2: any, arg3 = 'default') {
return `${value} ${arg1} ${arg2} ${arg3}`;
}
}
@Component({
selector: 'test-cmp',
template: 'empty',
standalone: false,
})
class TestComponent {
value: any;
a: any;
b: any;
}
@Component({
selector: 'other-cmp',
template: 'empty',
standalone: false,
})
class AnotherComponent {}
@Component({
selector: 'comp-with-ref',
template: '<div (event)="noop()" emitterDirective></div>{{value}}',
host: {'event': 'noop()'},
standalone: false,
})
class CompWithRef {
@Input() public value: any;
constructor(public changeDetectorRef: ChangeDetectorRef) {}
noop() {}
}
@Component({
selector: 'wrap-comp-with-ref',
template: '<comp-with-ref></comp-with-ref>',
standalone: false,
})
class WrapCompWithRef {
constructor(public changeDetectorRef: ChangeDetectorRef) {}
}
@Component({
selector: 'push-cmp',
template: '<div (event)="noop()" emitterDirective></div>{{value}}{{renderIncrement}}',
host: {'(event)': 'noop()'},
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
class PushComp {
@Input() public value: any;
public renderCount: any = 0;
get renderIncrement() {
this.renderCount++;
return '';
}
constructor(public changeDetectorRef: ChangeDetectorRef) {}
noop() {}
}
@Directive({
selector: '[emitterDirective]',
standalone: false,
})
class EmitterDirective {
@Output('event') emitter = new EventEmitter<string>();
}
@Directive({
selector: '[gh9882]',
standalone: false,
})
class Gh9882 implements AfterContentInit {
constructor(
private _viewContainer: ViewContainerRef,
private _templateRef: TemplateRef<Object>,
) {}
ngAfterContentInit(): any {
this._viewContainer.createEmbeddedView(this._templateRef);
}
}
@Directive({
selector: '[testDirective]',
exportAs: 'testDirective',
standalone: false,
})
class TestDirective
implements
OnInit,
DoCheck,
OnChanges,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked,
OnDestroy
{
@Input() a: any;
@Input() b: any;
changes: SimpleChanges | undefined;
event: any;
eventEmitter: EventEmitter<string> = new EventEmitter<string>();
@Input('testDirective') name: string = '';
@Input() throwOn: string | undefined;
constructor(public log: DirectiveLog) {}
onEvent(event: any) {
this.event = event;
}
ngDoCheck() {
this.log.add(this.name, 'ngDoCheck');
}
ngOnInit() {
this.log.add(this.name, 'ngOnInit');
if (this.throwOn == 'ngOnInit') {
throw new Error('Boom!');
}
}
ngOnChanges(changes: SimpleChanges) {
this.log.add(this.name, 'ngOnChanges');
this.changes = changes;
if (this.throwOn == 'ngOnChanges') {
throw new Error('Boom!');
}
}
ngAfterContentInit() {
this.log.add(this.name, 'ngAfterContentInit');
if (this.throwOn == 'ngAfterContentInit') {
throw new Error('Boom!');
}
}
ngAfterContentChecked() {
this.log.add(this.name, 'ngAfterContentChecked');
if (this.throwOn == 'ngAfterContentChecked') {
throw new Error('Boom!');
}
}
ngAfterViewInit() {
this.log.add(this.name, 'ngAfterViewInit');
if (this.throwOn == 'ngAfterViewInit') {
throw new Error('Boom!');
}
}
ngAfterViewChecked() {
this.log.add(this.name, 'ngAfterViewChecked');
if (this.throwOn == 'ngAfterViewChecked') {
throw new Error('Boom!');
}
}
ngOnDestroy() {
this.log.add(this.name, 'ngOnDestroy');
if (this.throwOn == 'ngOnDestroy') {
throw new Error('Boom!');
}
}
}
@Injectable()
class InjectableWithLifecycle {
name = 'injectable';
constructor(public log: DirectiveLog) {}
ngOnDestroy() {
this.log.add(this.name, 'ngOnDestroy');
}
}
@Directive({
selector: '[onDestroyDirective]',
standalone: false,
})
class OnDestroyDirective implements OnDestroy {
@Output('destroy') emitter = new EventEmitter<string>(false);
ngOnDestroy() {
this.emitter.emit('destroyed');
}
}
@Directive({
selector: '[orderCheck0]',
standalone: false,
})
class OrderCheckDirective0 {
private _name: string | undefined;
@Input('orderCheck0')
set name(value: string) {
this._name = value;
this.log.add(this._name, 'set');
}
constructor(public log: DirectiveLog) {}
}
@Directive({
selector: '[orderCheck1]',
standalone: false,
})
class OrderCheckDirective1 {
private _name: string | undefined;
@Input('orderCheck1')
set name(value: string) {
this._name = value;
this.log.add(this._name, 'set');
}
constructor(
public log: DirectiveLog,
_check0: OrderCheckDirective0,
) {}
}
@Directive({
selector: '[orderCheck2]',
standalone: false,
})
class OrderCheckDirective2 {
private _name: string | undefined;
@Input('orderCheck2')
set name(value: string) {
this._name = value;
this.log.add(this._name, 'set');
}
constructor(
public log: DirectiveLog,
_check1: OrderCheckDirective1,
) {}
}
class TestLocalsContext {
constructor(public someLocal: string) {}
}
@Directive({
selector: '[testLocals]',
standalone: false,
})
class TestLocals {
constructor(templateRef: TemplateRef<TestLocalsContext>, vcRef: ViewContainerRef) {
vcRef.createEmbeddedView(templateRef, new TestLocalsContext('someLocalValue'));
}
}
@Component({
selector: 'root',
template: 'empty',
standalone: false,
})
class Person {
age: number | undefined;
name: string | undefined;
address: Address | null = null;
phones: number[] | undefined;
init(name: string, address: Address | null = null) {
this.name = name;
this.address = address;
}
sayHi(m: any): string {
return `Hi, ${m}`;
}
passThrough(val: any): any {
return val;
}
toString(): string {
const address = this.address == null ? '' : ' address=' + this.address.toString();
return 'name=' + this.name + address;
}
}
class Address {
cityGetterCalls: number = 0;
zipCodeGetterCalls: number = 0;
constructor(
public _city: string,
public _zipcode: any = null,
) {}
get city() {
this.cityGetterCalls++;
return this._city;
}
get zipcode() {
this.zipCodeGetterCalls++;
return this._zipcode;
}
set city(v) {
this._city = v;
}
set zipcode(v) {
this._zipcode = v;
}
toString(): string {
return this.city || '-';
}
}
@Component({
selector: 'root',
template: 'empty',
standalone: false,
})
class Uninitialized {
value: any = null;
}
@Component({
selector: 'root',
template: 'empty',
standalone: false,
})
class TestData {
a: any;
b: any;
}
class Holder<T> {
value: T | undefined;
}
@Component({
selector: 'root',
template: 'empty',
standalone: false,
})
class PersonHolder extends Holder<Person> {}
@Component({
selector: 'root',
template: 'empty',
standalone: false,
})
class PersonHolderHolder extends Holder<Holder<Person>> {} | {
"end_byte": 70576,
"start_byte": 63345,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/change_detection_integration_spec.ts"
} |
angular/packages/core/test/linker/ng_container_integration_spec.ts_0_3732 | /**
* @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
*/
// Make the `$localize()` global function available to the compiled templates, and the direct calls
// below. This would normally be done inside the application `polyfills.ts` file.
import '@angular/localize/init';
import {
AfterContentInit,
AfterViewInit,
Component,
ContentChildren,
Directive,
Input,
QueryList,
ViewChildren,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers';
describe('<ng-container>', function () {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MyComp, NeedsContentChildren, NeedsViewChildren, TextDirective, Simple],
});
});
it('should support the "i18n" attribute', () => {
const template = '<ng-container i18n>foo</ng-container>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const el = fixture.nativeElement;
expect(el).toHaveText('foo');
});
it('should work with static content projection', () => {
const template = `<simple><ng-container><p>1</p><p>2</p></ng-container></simple>`;
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const el = fixture.nativeElement;
expect(el).toHaveText('SIMPLE(12)');
});
it('should support injecting the container from children', () => {
const template = `<ng-container [text]="'container'"><p></p></ng-container>`;
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const dir = fixture.debugElement.children[0].injector.get(TextDirective);
expect(dir).toBeInstanceOf(TextDirective);
expect(dir.text).toEqual('container');
});
it('should contain all child directives in a <ng-container> (view dom)', () => {
const template = '<needs-view-children #q></needs-view-children>';
TestBed.overrideComponent(MyComp, {set: {template}});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const q = fixture.debugElement.children[0].references['q'];
fixture.detectChanges();
expect(q.textDirChildren.length).toEqual(1);
expect(q.numberOfChildrenAfterViewInit).toEqual(1);
});
});
@Directive({
selector: '[text]',
standalone: false,
})
class TextDirective {
@Input() public text: string | null = null;
}
@Component({
selector: 'needs-content-children',
template: '',
standalone: false,
})
class NeedsContentChildren implements AfterContentInit {
@ContentChildren(TextDirective) textDirChildren!: QueryList<TextDirective>;
numberOfChildrenAfterContentInit: number | undefined;
ngAfterContentInit() {
this.numberOfChildrenAfterContentInit = this.textDirChildren.length;
}
}
@Component({
selector: 'needs-view-children',
template: '<div text></div>',
standalone: false,
})
class NeedsViewChildren implements AfterViewInit {
@ViewChildren(TextDirective) textDirChildren!: QueryList<TextDirective>;
numberOfChildrenAfterViewInit: number | undefined;
ngAfterViewInit() {
this.numberOfChildrenAfterViewInit = this.textDirChildren.length;
}
}
@Component({
selector: 'simple',
template: 'SIMPLE(<ng-content></ng-content>)',
standalone: false,
})
class Simple {}
@Component({
selector: 'my-comp',
template: '',
standalone: false,
})
class MyComp {
ctxBoolProp: boolean = false;
}
| {
"end_byte": 3732,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/ng_container_integration_spec.ts"
} |
angular/packages/core/test/linker/source_map_integration_node_only_spec.ts_0_929 | /**
* @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 {ResourceLoader, SourceMap} from '@angular/compiler';
import {CompilerFacadeImpl} from '@angular/compiler/src/jit_compiler_facade';
import {JitEvaluator} from '@angular/compiler/src/output/output_jit';
import {escapeRegExp} from '@angular/compiler/src/util';
import {Attribute, Component, Directive, ErrorHandler} from '@angular/core';
import {CompilerFacade, ExportedCompilerFacade} from '@angular/core/src/compiler/compiler_facade';
import {resolveComponentResources} from '@angular/core/src/metadata/resource_loading';
import {fakeAsync, TestBed, tick} from '@angular/core/testing';
import {MockResourceLoader} from './resource_loader_mock';
import {extractSourceMap, originalPositionFor} from './source_map_util'; | {
"end_byte": 929,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/source_map_integration_node_only_spec.ts"
} |
angular/packages/core/test/linker/source_map_integration_node_only_spec.ts_931_9809 | describe('jit source mapping', () => {
let resourceLoader: MockResourceLoader;
let jitEvaluator: MockJitEvaluator;
beforeEach(() => {
resourceLoader = new MockResourceLoader();
jitEvaluator = new MockJitEvaluator();
TestBed.configureCompiler({
providers: [
{
provide: ResourceLoader,
useValue: resourceLoader,
},
{
provide: JitEvaluator,
useValue: jitEvaluator,
},
],
});
});
describe('generated filenames and stack traces', () => {
beforeEach(() => overrideCompilerFacade());
afterEach(() => restoreCompilerFacade());
describe('inline templates', () => {
const ngUrl = 'ng:///MyComp/template.html';
function templateDecorator(template: string) {
return {template};
}
declareTests({ngUrl, templateDecorator});
});
describe('external templates', () => {
const templateUrl = 'http://localhost:1234/some/url.html';
const ngUrl = templateUrl;
function templateDecorator(template: string) {
resourceLoader.expect(templateUrl, template);
return {templateUrl};
}
declareTests({ngUrl, templateDecorator});
});
function declareTests({ngUrl, templateDecorator}: TestConfig) {
const generatedUrl = 'ng:///MyComp.js';
it('should use the right source url in html parse errors', async () => {
const template = '<div>\n </error>';
@Component({
...templateDecorator(template),
standalone: false,
})
class MyComp {}
await expectAsync(resolveCompileAndCreateComponent(MyComp, template)).toBeRejectedWithError(
new RegExp(`${escapeRegExp(ngUrl)}@1:2`),
);
});
it('should create a sourceMap for templates', async () => {
const template = `Hello World!`;
@Component({
...templateDecorator(template),
standalone: false,
})
class MyComp {}
await resolveCompileAndCreateComponent(MyComp, template);
const sourceMap = jitEvaluator.getSourceMap(generatedUrl);
expect(sourceMap.sources).toEqual([generatedUrl, ngUrl]);
expect(sourceMap.sourcesContent).toEqual([' ', template]);
});
xit('should report source location for di errors', async () => {
const template = `<div>\n <div someDir></div></div>`;
@Component({
...templateDecorator(template),
standalone: false,
})
class MyComp {}
@Directive({
selector: '[someDir]',
standalone: false,
})
class SomeDir {
constructor() {
throw new Error('Test');
}
}
TestBed.configureTestingModule({declarations: [SomeDir]});
let error: any;
try {
await resolveCompileAndCreateComponent(MyComp, template);
} catch (e) {
error = e;
}
// The error should be logged from the element
expect(await jitEvaluator.getSourcePositionForStack(error.stack, generatedUrl)).toEqual({
line: 2,
column: 4,
source: ngUrl,
});
});
xit('should report di errors with multiple elements and directives', async () => {
const template = `<div someDir></div>|<div someDir="throw"></div>`;
@Component({
...templateDecorator(template),
standalone: false,
})
class MyComp {}
@Directive({
selector: '[someDir]',
standalone: false,
})
class SomeDir {
constructor(@Attribute('someDir') someDir: string) {
if (someDir === 'throw') {
throw new Error('Test');
}
}
}
TestBed.configureTestingModule({declarations: [SomeDir]});
let error: any;
try {
await resolveCompileAndCreateComponent(MyComp, template);
} catch (e) {
error = e;
}
// The error should be logged from the 2nd-element
expect(await jitEvaluator.getSourcePositionForStack(error.stack, generatedUrl)).toEqual({
line: 1,
column: 20,
source: ngUrl,
});
});
it('should report source location for binding errors', async () => {
const template = `<div>\n <span [title]="createError()"></span></div>`;
@Component({
...templateDecorator(template),
standalone: false,
})
class MyComp {
createError() {
throw new Error('Test');
}
}
const comp = await resolveCompileAndCreateComponent(MyComp, template);
let error: any;
try {
comp.detectChanges();
} catch (e) {
error = e;
}
// the stack should point to the binding
expect(await jitEvaluator.getSourcePositionForStack(error.stack, generatedUrl)).toEqual({
line: 2,
column: 12,
source: ngUrl,
});
});
it('should report source location for event errors', async () => {
const template = `<div>\n <span (click)="createError()"></span></div>`;
@Component({
...templateDecorator(template),
standalone: false,
})
class MyComp {
createError() {
throw new Error('Test');
}
}
const comp = await resolveCompileAndCreateComponent(MyComp, template);
let error: any;
const errorHandler = TestBed.inject(ErrorHandler);
spyOn(errorHandler, 'handleError').and.callFake((e: any) => (error = e));
try {
comp.debugElement.children[0].children[0].triggerEventHandler('click', 'EVENT');
} catch (e) {
error = e;
}
expect(error).toBeTruthy();
// the stack should point to the binding
expect(await jitEvaluator.getSourcePositionForStack(error.stack, generatedUrl)).toEqual({
line: 2,
column: 21,
source: ngUrl,
});
});
}
});
async function compileAndCreateComponent(comType: any) {
TestBed.configureTestingModule({declarations: [comType]});
await TestBed.compileComponents();
if (resourceLoader.hasPendingRequests()) {
resourceLoader.flush();
}
return TestBed.createComponent(comType);
}
function createResolver(contents: string) {
return (_url: string) => Promise.resolve(contents);
}
async function resolveCompileAndCreateComponent(comType: any, template: string) {
await resolveComponentResources(createResolver(template));
return await compileAndCreateComponent(comType);
}
let ɵcompilerFacade: CompilerFacade;
function overrideCompilerFacade() {
const ng: ExportedCompilerFacade = (global as any).ng;
if (ng) {
ɵcompilerFacade = ng.ɵcompilerFacade;
ng.ɵcompilerFacade = new CompilerFacadeImpl(jitEvaluator);
}
}
function restoreCompilerFacade() {
if (ɵcompilerFacade) {
const ng: ExportedCompilerFacade = (global as any).ng;
ng.ɵcompilerFacade = ɵcompilerFacade;
}
}
interface TestConfig {
ngUrl: string;
templateDecorator: (template: string) => {
[key: string]: any;
};
}
interface SourcePos {
source: string | null;
line: number | null;
column: number | null;
}
/**
* A helper class that captures the sources that have been JIT compiled.
*/
class MockJitEvaluator extends JitEvaluator {
sources: string[] = [];
override executeFunction(fn: Function, args: any[]) {
// Capture the source that has been generated.
this.sources.push(fn.toString());
// Then execute it anyway.
return super.executeFunction(fn, args);
}
/**
* Get the source-map for a specified JIT compiled file.
* @param genFile the URL of the file whose source-map we want.
*/
getSourceMap(genFile: string): SourceMap {
return this.sources
.map((source) => extractSourceMap(source))
.find((map) => !!(map && map.file === genFile))!;
}
async getSourcePositionForStack(stack: string, genFile: string): Promise<SourcePos> {
const urlRegexp = new RegExp(`(${escapeRegExp(genFile)}):(\\d+):(\\d+)`);
const pos = stack
.split('\n')
.map((line) => urlRegexp.exec(line))
.filter((match) => !!match)
.map((match) => ({
file: match![1],
line: parseInt(match![2], 10),
column: parseInt(match![3], 10),
}))
.shift();
if (!pos) {
throw new Error(`${genFile} was not mentioned in this stack:\n${stack}`);
}
const sourceMap = this.getSourceMap(pos.file);
return await originalPositionFor(sourceMap, pos);
}
}
});
| {
"end_byte": 9809,
"start_byte": 931,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/source_map_integration_node_only_spec.ts"
} |
angular/packages/core/test/linker/ng_module_integration_spec.ts_0_2192 | /**
* @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 {
Compiler,
Component,
CUSTOM_ELEMENTS_SCHEMA,
Directive,
forwardRef,
getModuleFactory,
getNgModuleById,
HostBinding,
Inject,
Injectable,
InjectionToken,
Injector,
Input,
NgModule,
NgModuleRef,
Optional,
Pipe,
Provider,
Self,
Type,
} from '@angular/core';
import {ɵɵdefineInjectable} from '@angular/core/src/di/interface/defs';
import {NgModuleType} from '@angular/core/src/render3';
import {getNgModuleDef} from '@angular/core/src/render3/def_getters';
import {ComponentFixture, inject, TestBed} from '@angular/core/testing';
import {InternalNgModuleRef, NgModuleFactory} from '../../src/linker/ng_module_factory';
import {
clearModulesForTest,
setAllowDuplicateNgModuleIdsForTest,
} from '../../src/linker/ng_module_registration';
import {stringify} from '../../src/util/stringify';
class Engine {}
class TurboEngine extends Engine {}
const CARS = new InjectionToken<Car[]>('Cars');
@Injectable()
class Car {
constructor(public engine: Engine) {}
}
@Injectable()
class CarWithOptionalEngine {
constructor(@Optional() public engine: Engine) {}
}
@Injectable()
class SportsCar extends Car {
constructor(engine: Engine) {
super(engine);
}
}
@Injectable()
class CarWithInject {
constructor(@Inject(TurboEngine) public engine: Engine) {}
}
@Injectable()
class CyclicEngine {
constructor(car: Car) {}
}
class NoAnnotations {
constructor(secretDependency: any) {}
}
@Component({
selector: 'comp',
template: '',
standalone: false,
})
class SomeComp {}
@Directive({
selector: '[someDir]',
standalone: false,
})
class SomeDirective {
@HostBinding('title') @Input() someDir: string | undefined;
}
@Pipe({
name: 'somePipe',
standalone: false,
})
class SomePipe {
transform(value: string): any {
return `transformed ${value}`;
}
}
@Component({
selector: 'comp',
template: `<div [someDir]="'someValue' | somePipe"></div>`,
standalone: false,
})
class CompUsingModuleDirectiveAndPipe {}
| {
"end_byte": 2192,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/ng_module_integration_spec.ts"
} |
angular/packages/core/test/linker/ng_module_integration_spec.ts_2194_10803 | scribe('NgModule', () => {
let compiler: Compiler;
let injector: Injector;
beforeEach(inject([Compiler, Injector], (_compiler: Compiler, _injector: Injector) => {
compiler = _compiler;
injector = _injector;
}));
function createModuleFactory<T>(moduleType: Type<T>): NgModuleFactory<T> {
return compiler.compileModuleSync(moduleType);
}
function createModule<T>(moduleType: Type<T>, parentInjector?: Injector | null): NgModuleRef<T> {
// Read the `ngModuleDef` to cause it to be compiled and any errors thrown.
getNgModuleDef(moduleType);
return createModuleFactory(moduleType).create(parentInjector || null);
}
function createComp<T>(compType: Type<T>, moduleType: Type<any>): ComponentFixture<T> {
const componentDef = (compType as any).ɵcmp;
if (componentDef) {
// Since we avoid Components/Directives/Pipes recompiling in case there are no overrides, we
// may face a problem where previously compiled defs available to a given
// Component/Directive are cached in TView and may become stale (in case any of these defs
// gets recompiled). In order to avoid this problem, we force fresh TView to be created.
componentDef.TView = null;
}
createModule(moduleType, injector);
return TestBed.createComponent(compType);
}
describe('errors', () => {
it('should error when exporting a directive that was neither declared nor imported', () => {
@NgModule({exports: [SomeDirective]})
class SomeModule {}
expect(() => createModule(SomeModule)).toThrowError(
`Can't export directive ${stringify(SomeDirective)} from ${stringify(
SomeModule,
)} as it was neither declared nor imported!`,
);
});
it('should error when exporting a pipe that was neither declared nor imported', () => {
@NgModule({exports: [SomePipe]})
class SomeModule {}
expect(() => createModule(SomeModule)).toThrowError(
`Can't export pipe ${stringify(SomePipe)} from ${stringify(
SomeModule,
)} as it was neither declared nor imported!`,
);
});
it('should error if a directive is declared in more than 1 module', () => {
@NgModule({declarations: [SomeDirective]})
class Module1 {}
@NgModule({declarations: [SomeDirective]})
class Module2 {}
createModule(Module1);
expect(() => createModule(Module2)).toThrowError(
`Type ${stringify(SomeDirective)} is part of the declarations of 2 modules: ${stringify(
Module1,
)} and ${stringify(Module2)}! ` +
`Please consider moving ${stringify(
SomeDirective,
)} to a higher module that imports ${stringify(Module1)} and ${stringify(Module2)}. ` +
`You can also create a new NgModule that exports and includes ${stringify(
SomeDirective,
)} then import that NgModule in ${stringify(Module1)} and ${stringify(Module2)}.`,
);
});
it('should error if a directive is declared in more than 1 module also if the module declaring it is imported', () => {
@NgModule({declarations: [SomeDirective], exports: [SomeDirective]})
class Module1 {}
@NgModule({declarations: [SomeDirective], imports: [Module1]})
class Module2 {}
expect(() => createModule(Module2)).toThrowError(
`Type ${stringify(SomeDirective)} is part of the declarations of 2 modules: ${stringify(
Module1,
)} and ${stringify(Module2)}! ` +
`Please consider moving ${stringify(
SomeDirective,
)} to a higher module that imports ${stringify(Module1)} and ${stringify(Module2)}. ` +
`You can also create a new NgModule that exports and includes ${stringify(
SomeDirective,
)} then import that NgModule in ${stringify(Module1)} and ${stringify(Module2)}.`,
);
});
it('should error if a pipe is declared in more than 1 module', () => {
@NgModule({declarations: [SomePipe]})
class Module1 {}
@NgModule({declarations: [SomePipe]})
class Module2 {}
createModule(Module1);
expect(() => createModule(Module2)).toThrowError(
`Type ${stringify(SomePipe)} is part of the declarations of 2 modules: ${stringify(
Module1,
)} and ${stringify(Module2)}! ` +
`Please consider moving ${stringify(
SomePipe,
)} to a higher module that imports ${stringify(Module1)} and ${stringify(Module2)}. ` +
`You can also create a new NgModule that exports and includes ${stringify(
SomePipe,
)} then import that NgModule in ${stringify(Module1)} and ${stringify(Module2)}.`,
);
});
it('should error if a pipe is declared in more than 1 module also if the module declaring it is imported', () => {
@NgModule({declarations: [SomePipe], exports: [SomePipe]})
class Module1 {}
@NgModule({declarations: [SomePipe], imports: [Module1]})
class Module2 {}
expect(() => createModule(Module2)).toThrowError(
`Type ${stringify(SomePipe)} is part of the declarations of 2 modules: ${stringify(
Module1,
)} and ${stringify(Module2)}! ` +
`Please consider moving ${stringify(
SomePipe,
)} to a higher module that imports ${stringify(Module1)} and ${stringify(Module2)}. ` +
`You can also create a new NgModule that exports and includes ${stringify(
SomePipe,
)} then import that NgModule in ${stringify(Module1)} and ${stringify(Module2)}.`,
);
});
});
describe('schemas', () => {
it('should error on unknown bound properties on custom elements by default', () => {
@Component({
template: '<div [someUnknownProp]="true"></div>',
standalone: false,
})
class ComponentUsingInvalidProperty {}
@NgModule({declarations: [ComponentUsingInvalidProperty]})
class SomeModule {}
const spy = spyOn(console, 'error');
const fixture = createComp(ComponentUsingInvalidProperty, SomeModule);
fixture.detectChanges();
expect(spy.calls.mostRecent().args[0]).toMatch(/Can't bind to 'someUnknownProp'/);
});
it('should not error on unknown bound properties on custom elements when using the CUSTOM_ELEMENTS_SCHEMA', () => {
@Component({
template: '<some-element [someUnknownProp]="true"></some-element>',
standalone: false,
})
class ComponentUsingInvalidProperty {}
@NgModule({
schemas: [CUSTOM_ELEMENTS_SCHEMA],
declarations: [ComponentUsingInvalidProperty],
})
class SomeModule {}
expect(() => {
const fixture = createComp(ComponentUsingInvalidProperty, SomeModule);
fixture.detectChanges();
}).not.toThrow();
});
});
describe('id', () => {
const token = 'myid';
afterEach(() => clearModulesForTest());
it('should register loaded modules', () => {
@NgModule({id: token})
class SomeModule {}
createModule(SomeModule);
const moduleType = getNgModuleById(token);
expect(moduleType).toBeTruthy();
expect(moduleType).toBe(SomeModule as NgModuleType);
const factory = getModuleFactory(token);
expect(factory).toBeTruthy();
expect(factory.moduleType).toBe(SomeModule);
});
it('should throw when registering a duplicate module', () => {
// TestBed disables the error that's being tested here, so temporarily re-enable it.
setAllowDuplicateNgModuleIdsForTest(false);
@NgModule({id: token})
class SomeModule {}
createModule(SomeModule);
expect(() => {
@NgModule({id: token})
class SomeOtherModule {}
createModule(SomeOtherModule);
}).toThrowError(/Duplicate module registered/);
// Re-disable the error.
setAllowDuplicateNgModuleIdsForTest(true);
});
it('should register a module even if not importing the .ngfactory file or calling create()', () => {
@NgModule({id: 'child'})
class ChildModule {}
@NgModule({
id: 'test',
imports: [ChildModule],
})
class Module {}
// Verify that we can retrieve NgModule factory by id.
expect(getModuleFactory('child')).toBeInstanceOf(NgModuleFactory);
// Verify that we can also retrieve NgModule class by id.
const moduleType = getNgModuleById('child');
expect(moduleType).toBeTruthy();
expect(moduleType).toBe(ChildModule as NgModuleType);
});
});
| {
"end_byte": 10803,
"start_byte": 2194,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/ng_module_integration_spec.ts"
} |
angular/packages/core/test/linker/ng_module_integration_spec.ts_10807_16585 | cribe('bootstrap components', () => {
it('should create ComponentFactories', () => {
@NgModule({declarations: [SomeComp], bootstrap: [SomeComp]})
class SomeModule {}
const ngModule = createModule(SomeModule);
expect(
ngModule.componentFactoryResolver.resolveComponentFactory(SomeComp).componentType,
).toBe(SomeComp);
});
it('should store the ComponentFactories in the NgModuleInjector', () => {
@NgModule({declarations: [SomeComp], bootstrap: [SomeComp]})
class SomeModule {}
const ngModule = <InternalNgModuleRef<any>>createModule(SomeModule);
expect(ngModule._bootstrapComponents.length).toBe(1);
expect(ngModule._bootstrapComponents[0]).toBe(SomeComp);
});
});
describe('directives and pipes', () => {
describe('declarations', () => {
it('should be supported in root modules', () => {
@NgModule({declarations: [CompUsingModuleDirectiveAndPipe, SomeDirective, SomePipe]})
class SomeModule {}
const compFixture = createComp(CompUsingModuleDirectiveAndPipe, SomeModule);
compFixture.detectChanges();
expect(compFixture.debugElement.children[0].properties['title']).toBe(
'transformed someValue',
);
});
it('should be supported in imported modules', () => {
@NgModule({declarations: [CompUsingModuleDirectiveAndPipe, SomeDirective, SomePipe]})
class SomeImportedModule {}
@NgModule({imports: [SomeImportedModule]})
class SomeModule {}
const compFixture = createComp(CompUsingModuleDirectiveAndPipe, SomeModule);
compFixture.detectChanges();
expect(compFixture.debugElement.children[0].properties['title']).toBe(
'transformed someValue',
);
});
it('should be supported in nested components', () => {
@Component({
selector: 'parent',
template: '<comp></comp>',
standalone: false,
})
class ParentCompUsingModuleDirectiveAndPipe {}
@NgModule({
declarations: [
ParentCompUsingModuleDirectiveAndPipe,
CompUsingModuleDirectiveAndPipe,
SomeDirective,
SomePipe,
],
})
class SomeModule {}
const compFixture = createComp(ParentCompUsingModuleDirectiveAndPipe, SomeModule);
compFixture.detectChanges();
expect(compFixture.debugElement.children[0].children[0].properties['title']).toBe(
'transformed someValue',
);
});
});
describe('import/export', () => {
it('should support exported directives and pipes', () => {
@NgModule({declarations: [SomeDirective, SomePipe], exports: [SomeDirective, SomePipe]})
class SomeImportedModule {}
@NgModule({declarations: [CompUsingModuleDirectiveAndPipe], imports: [SomeImportedModule]})
class SomeModule {}
const compFixture = createComp(CompUsingModuleDirectiveAndPipe, SomeModule);
compFixture.detectChanges();
expect(compFixture.debugElement.children[0].properties['title']).toBe(
'transformed someValue',
);
});
it('should support exported directives and pipes if the module is wrapped into an `ModuleWithProviders`', () => {
@NgModule({declarations: [SomeDirective, SomePipe], exports: [SomeDirective, SomePipe]})
class SomeImportedModule {}
@NgModule({
declarations: [CompUsingModuleDirectiveAndPipe],
imports: [{ngModule: SomeImportedModule}],
})
class SomeModule {}
const compFixture = createComp(CompUsingModuleDirectiveAndPipe, SomeModule);
compFixture.detectChanges();
expect(compFixture.debugElement.children[0].properties['title']).toBe(
'transformed someValue',
);
});
it('should support reexported modules', () => {
@NgModule({declarations: [SomeDirective, SomePipe], exports: [SomeDirective, SomePipe]})
class SomeReexportedModule {}
@NgModule({exports: [SomeReexportedModule]})
class SomeImportedModule {}
@NgModule({declarations: [CompUsingModuleDirectiveAndPipe], imports: [SomeImportedModule]})
class SomeModule {}
const compFixture = createComp(CompUsingModuleDirectiveAndPipe, SomeModule);
compFixture.detectChanges();
expect(compFixture.debugElement.children[0].properties['title']).toBe(
'transformed someValue',
);
});
it('should support exporting individual directives of an imported module', () => {
@NgModule({declarations: [SomeDirective, SomePipe], exports: [SomeDirective, SomePipe]})
class SomeReexportedModule {}
@NgModule({imports: [SomeReexportedModule], exports: [SomeDirective, SomePipe]})
class SomeImportedModule {}
@NgModule({declarations: [CompUsingModuleDirectiveAndPipe], imports: [SomeImportedModule]})
class SomeModule {}
const compFixture = createComp(CompUsingModuleDirectiveAndPipe, SomeModule);
compFixture.detectChanges();
expect(compFixture.debugElement.children[0].properties['title']).toBe(
'transformed someValue',
);
});
it('should not use non exported pipes of an imported module', () => {
@NgModule({
declarations: [SomePipe],
})
class SomeImportedModule {}
@NgModule({declarations: [CompUsingModuleDirectiveAndPipe], imports: [SomeImportedModule]})
class SomeModule {}
expect(() => createComp(CompUsingModuleDirectiveAndPipe, SomeModule)).toThrowError(
/The pipe 'somePipe' could not be found/,
);
});
});
});
| {
"end_byte": 16585,
"start_byte": 10807,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/ng_module_integration_spec.ts"
} |
angular/packages/core/test/linker/ng_module_integration_spec.ts_16589_24872 | cribe('providers', function () {
let moduleType: any = null;
function createInjector(providers: Provider[], parent?: Injector | null): Injector {
@NgModule({providers: providers})
class SomeModule {}
moduleType = SomeModule;
return createModule(SomeModule, parent).injector;
}
it('should provide the module', () => {
expect(createInjector([]).get(moduleType)).toBeInstanceOf(moduleType);
});
it('should instantiate a class without dependencies', () => {
const injector = createInjector([Engine]);
const engine = injector.get(Engine);
expect(engine).toBeInstanceOf(Engine);
});
it('should resolve dependencies based on type information', () => {
const injector = createInjector([Engine, Car]);
const car = injector.get(Car);
expect(car).toBeInstanceOf(Car);
expect(car.engine).toBeInstanceOf(Engine);
});
it('should resolve dependencies based on @Inject annotation', () => {
const injector = createInjector([TurboEngine, Engine, CarWithInject]);
const car = injector.get(CarWithInject);
expect(car).toBeInstanceOf(CarWithInject);
expect(car.engine).toBeInstanceOf(TurboEngine);
});
it('should throw when no type and not @Inject (class case)', () => {
expect(() => createInjector([NoAnnotations])).toThrowError(
"NG0204: Can't resolve all parameters for NoAnnotations: (?).",
);
});
it('should cache instances', () => {
const injector = createInjector([Engine]);
const e1 = injector.get(Engine);
const e2 = injector.get(Engine);
expect(e1).toBe(e2);
});
it('should provide to a value', () => {
const injector = createInjector([{provide: Engine, useValue: 'fake engine'}]);
const engine = injector.get(Engine);
expect(engine).toEqual('fake engine');
});
it('should provide to a factory', () => {
function sportsCarFactory(e: Engine) {
return new SportsCar(e);
}
const injector = createInjector([
Engine,
{provide: Car, useFactory: sportsCarFactory, deps: [Engine]},
]);
const car = injector.get(Car);
expect(car).toBeInstanceOf(SportsCar);
expect(car.engine).toBeInstanceOf(Engine);
});
it('should supporting provider to null', () => {
const injector = createInjector([{provide: Engine, useValue: null}]);
const engine = injector.get(Engine);
expect(engine).toBeNull();
});
it('should provide to an alias', () => {
const injector = createInjector([
Engine,
{provide: SportsCar, useClass: SportsCar},
{provide: Car, useExisting: SportsCar},
]);
const car = injector.get(Car);
const sportsCar = injector.get(SportsCar);
expect(car).toBeInstanceOf(SportsCar);
expect(car).toBe(sportsCar);
});
it('should support multiProviders', () => {
const injector = createInjector([
Engine,
{provide: CARS, useClass: SportsCar, multi: true},
{provide: CARS, useClass: CarWithOptionalEngine, multi: true},
]);
const cars = injector.get(CARS);
expect(cars.length).toEqual(2);
expect(cars[0]).toBeInstanceOf(SportsCar);
expect(cars[1]).toBeInstanceOf(CarWithOptionalEngine);
});
it('should support multiProviders that are created using useExisting', () => {
const injector = createInjector([
Engine,
SportsCar,
{provide: CARS, useExisting: SportsCar, multi: true},
]);
const cars = injector.get(CARS);
expect(cars.length).toEqual(1);
expect(cars[0]).toBe(injector.get(SportsCar));
});
it('should throw when the aliased provider does not exist', () => {
const injector = createInjector([{provide: 'car', useExisting: SportsCar}]);
const errorMsg =
`R3InjectorError(SomeModule)[car -> ${stringify(SportsCar)}]: \n ` +
`NullInjectorError: No provider for ${stringify(SportsCar)}!`;
expect(() => injector.get('car')).toThrowError(errorMsg);
});
it('should handle forwardRef in useExisting', () => {
const injector = createInjector([
{provide: 'originalEngine', useClass: forwardRef(() => Engine)},
{provide: 'aliasedEngine', useExisting: <any>forwardRef(() => 'originalEngine')},
]);
expect(injector.get('aliasedEngine')).toBeInstanceOf(Engine);
});
it('should support overriding factory dependencies', () => {
const injector = createInjector([
Engine,
{provide: Car, useFactory: (e: Engine) => new SportsCar(e), deps: [Engine]},
]);
const car = injector.get(Car);
expect(car).toBeInstanceOf(SportsCar);
expect(car.engine).toBeInstanceOf(Engine);
});
it('should support optional dependencies', () => {
const injector = createInjector([CarWithOptionalEngine]);
const car = injector.get(CarWithOptionalEngine);
expect(car.engine).toBeNull();
});
it('should flatten passed-in providers', () => {
const injector = createInjector([[[Engine, Car]]]);
const car = injector.get(Car);
expect(car).toBeInstanceOf(Car);
});
it('should use the last provider when there are multiple providers for same token', () => {
const injector = createInjector([
{provide: Engine, useClass: Engine},
{provide: Engine, useClass: TurboEngine},
]);
expect(injector.get(Engine)).toBeInstanceOf(TurboEngine);
});
it('should use non-type tokens', () => {
const injector = createInjector([{provide: 'token', useValue: 'value'}]);
expect(injector.get('token')).toEqual('value');
});
it('should throw when given invalid providers', () => {
expect(() => createInjector(<any>['blah'])).toThrowError(
`Invalid provider for the NgModule 'SomeModule' - only instances of Provider and Type are allowed, got: [?blah?]`,
);
});
it('should throw when given blank providers', () => {
expect(() => createInjector(<any>[null, {provide: 'token', useValue: 'value'}])).toThrowError(
`Invalid provider for the NgModule 'SomeModule' - only instances of Provider and Type are allowed, got: [?null?, ...]`,
);
});
it('should provide itself', () => {
const parent = createInjector([]);
const child = createInjector([], parent);
expect(child.get(Injector)).toBe(child);
});
it('should provide undefined', () => {
let factoryCounter = 0;
const injector = createInjector([
{
provide: 'token',
useFactory: () => {
factoryCounter++;
return undefined;
},
},
]);
expect(injector.get('token')).toBeUndefined();
expect(injector.get('token')).toBeUndefined();
expect(factoryCounter).toBe(1);
});
describe('injecting lazy providers into an eager provider via Injector.get', () => {
it('should inject providers that were declared before it', () => {
@NgModule({
providers: [
{provide: 'lazy', useFactory: () => 'lazyValue'},
{
provide: 'eager',
useFactory: (i: Injector) => `eagerValue: ${i.get('lazy')}`,
deps: [Injector],
},
],
})
class MyModule {
// NgModule is eager, which makes all of its deps eager
constructor(@Inject('eager') eager: any) {}
}
expect(createModule(MyModule).injector.get('eager')).toBe('eagerValue: lazyValue');
});
it('should inject providers that were declared after it', () => {
@NgModule({
providers: [
{
provide: 'eager',
useFactory: (i: Injector) => `eagerValue: ${i.get('lazy')}`,
deps: [Injector],
},
{provide: 'lazy', useFactory: () => 'lazyValue'},
],
})
class MyModule {
// NgModule is eager, which makes all of its deps eager
constructor(@Inject('eager') eager: any) {}
}
expect(createModule(MyModule).injector.get('eager')).toBe('eagerValue: lazyValue');
});
});
| {
"end_byte": 24872,
"start_byte": 16589,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/ng_module_integration_spec.ts"
} |
angular/packages/core/test/linker/ng_module_integration_spec.ts_24878_32190 | cribe('injecting eager providers into an eager provider via Injector.get', () => {
it('should inject providers that were declared before it', () => {
@NgModule({
providers: [
{provide: 'eager1', useFactory: () => 'v1'},
{
provide: 'eager2',
useFactory: (i: Injector) => `v2: ${i.get('eager1')}`,
deps: [Injector],
},
],
})
class MyModule {
// NgModule is eager, which makes all of its deps eager
constructor(@Inject('eager1') eager1: any, @Inject('eager2') eager2: any) {}
}
expect(createModule(MyModule).injector.get('eager2')).toBe('v2: v1');
});
it('should inject providers that were declared after it', () => {
@NgModule({
providers: [
{
provide: 'eager1',
useFactory: (i: Injector) => `v1: ${i.get('eager2')}`,
deps: [Injector],
},
{provide: 'eager2', useFactory: () => 'v2'},
],
})
class MyModule {
// NgModule is eager, which makes all of its deps eager
constructor(@Inject('eager1') eager1: any, @Inject('eager2') eager2: any) {}
}
expect(createModule(MyModule).injector.get('eager1')).toBe('v1: v2');
});
it('eager providers should get initialized only once', () => {
@Injectable()
class MyService1 {
public innerService: MyService2;
constructor(injector: Injector) {
// Create MyService2 before it's initialized by TestModule.
this.innerService = injector.get(MyService2);
}
}
@Injectable()
class MyService2 {
constructor() {}
}
@NgModule({
providers: [MyService1, MyService2],
})
class TestModule {
constructor(
public service1: MyService1,
public service2: MyService2,
) {}
}
const moduleRef = createModule(TestModule, injector);
const module = moduleRef.instance;
// MyService2 should not get initialized twice.
expect(module.service1.innerService).toBe(module.service2);
});
});
it('should throw when no provider defined', () => {
const injector = createInjector([]);
const errorMsg =
`R3InjectorError(SomeModule)[NonExisting]: \n ` +
'NullInjectorError: No provider for NonExisting!';
expect(() => injector.get('NonExisting')).toThrowError(errorMsg);
});
it('should throw when trying to instantiate a cyclic dependency', () => {
expect(() =>
createInjector([Car, {provide: Engine, useClass: CyclicEngine}]).get(Car),
).toThrowError(/NG0200: Circular dependency in DI detected for Car/g);
});
it('should support null values', () => {
const injector = createInjector([{provide: 'null', useValue: null}]);
expect(injector.get('null')).toBe(null);
});
describe('child', () => {
it('should load instances from parent injector', () => {
const parent = createInjector([Engine]);
const child = createInjector([], parent);
const engineFromParent = parent.get(Engine);
const engineFromChild = child.get(Engine);
expect(engineFromChild).toBe(engineFromParent);
});
it('should not use the child providers when resolving the dependencies of a parent provider', () => {
const parent = createInjector([Car, Engine]);
const child = createInjector([{provide: Engine, useClass: TurboEngine}], parent);
const carFromChild = child.get(Car);
expect(carFromChild.engine).toBeInstanceOf(Engine);
});
it('should create new instance in a child injector', () => {
const parent = createInjector([Engine]);
const child = createInjector([{provide: Engine, useClass: TurboEngine}], parent);
const engineFromParent = parent.get(Engine);
const engineFromChild = child.get(Engine);
expect(engineFromParent).not.toBe(engineFromChild);
expect(engineFromChild).toBeInstanceOf(TurboEngine);
});
});
describe('dependency resolution', () => {
describe('@Self()', () => {
it('should return a dependency from self', () => {
const inj = createInjector([
Engine,
{provide: Car, useFactory: (e: Engine) => new Car(e), deps: [[Engine, new Self()]]},
]);
expect(inj.get(Car)).toBeInstanceOf(Car);
});
});
describe('default', () => {
it('should not skip self', () => {
const parent = createInjector([Engine]);
const child = createInjector(
[
{provide: Engine, useClass: TurboEngine},
{provide: Car, useFactory: (e: Engine) => new Car(e), deps: [Engine]},
],
parent,
);
expect(child.get(Car).engine).toBeInstanceOf(TurboEngine);
});
});
});
describe('lifecycle', () => {
it('should instantiate modules eagerly', () => {
let created = false;
@NgModule()
class ImportedModule {
constructor() {
created = true;
}
}
@NgModule({imports: [ImportedModule]})
class SomeModule {}
createModule(SomeModule);
expect(created).toBe(true);
});
it('should instantiate providers that are not used by a module lazily', () => {
let created = false;
createInjector([
{
provide: 'someToken',
useFactory: () => {
created = true;
return true;
},
},
]);
expect(created).toBe(false);
});
it('should support ngOnDestroy on any provider', () => {
let destroyed = false;
class SomeInjectable {
ngOnDestroy() {
destroyed = true;
}
}
@NgModule({providers: [SomeInjectable]})
class SomeModule {
// Inject SomeInjectable to make it eager...
constructor(i: SomeInjectable) {}
}
const moduleRef = createModule(SomeModule);
expect(destroyed).toBe(false);
moduleRef.destroy();
expect(destroyed).toBe(true);
});
it('should support ngOnDestroy for lazy providers', () => {
let created = false;
let destroyed = false;
class SomeInjectable {
constructor() {
created = true;
}
ngOnDestroy() {
destroyed = true;
}
}
@NgModule({providers: [SomeInjectable]})
class SomeModule {}
let moduleRef = createModule(SomeModule);
expect(created).toBe(false);
expect(destroyed).toBe(false);
// no error if the provider was not yet created
moduleRef.destroy();
expect(created).toBe(false);
expect(destroyed).toBe(false);
moduleRef = createModule(SomeModule);
moduleRef.injector.get(SomeInjectable);
expect(created).toBe(true);
moduleRef.destroy();
expect(destroyed).toBe(true);
});
});
| {
"end_byte": 32190,
"start_byte": 24878,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/ng_module_integration_spec.ts"
} |
angular/packages/core/test/linker/ng_module_integration_spec.ts_32196_40300 | cribe('imported and exported modules', () => {
it('should add the providers of imported modules', () => {
@NgModule({providers: [{provide: 'token1', useValue: 'imported'}]})
class ImportedModule {}
@NgModule({imports: [ImportedModule]})
class SomeModule {}
const injector = createModule(SomeModule).injector;
expect(injector.get(SomeModule)).toBeInstanceOf(SomeModule);
expect(injector.get(ImportedModule)).toBeInstanceOf(ImportedModule);
expect(injector.get('token1')).toBe('imported');
});
it('should add the providers of imported ModuleWithProviders', () => {
@NgModule()
class ImportedModule {}
@NgModule({
imports: [
{ngModule: ImportedModule, providers: [{provide: 'token1', useValue: 'imported'}]},
],
})
class SomeModule {}
const injector = createModule(SomeModule).injector;
expect(injector.get(SomeModule)).toBeInstanceOf(SomeModule);
expect(injector.get(ImportedModule)).toBeInstanceOf(ImportedModule);
expect(injector.get('token1')).toBe('imported');
});
it('should overwrite the providers of imported modules', () => {
@NgModule({providers: [{provide: 'token1', useValue: 'imported'}]})
class ImportedModule {}
@NgModule({providers: [{provide: 'token1', useValue: 'direct'}], imports: [ImportedModule]})
class SomeModule {}
const injector = createModule(SomeModule).injector;
expect(injector.get('token1')).toBe('direct');
});
it('should overwrite the providers of imported ModuleWithProviders', () => {
@NgModule()
class ImportedModule {}
@NgModule({
providers: [{provide: 'token1', useValue: 'direct'}],
imports: [
{ngModule: ImportedModule, providers: [{provide: 'token1', useValue: 'imported'}]},
],
})
class SomeModule {}
const injector = createModule(SomeModule).injector;
expect(injector.get('token1')).toBe('direct');
});
it('should overwrite the providers of imported modules on the second import level', () => {
@NgModule({providers: [{provide: 'token1', useValue: 'imported'}]})
class ImportedModuleLevel2 {}
@NgModule({
providers: [{provide: 'token1', useValue: 'direct'}],
imports: [ImportedModuleLevel2],
})
class ImportedModuleLevel1 {}
@NgModule({imports: [ImportedModuleLevel1]})
class SomeModule {}
const injector = createModule(SomeModule).injector;
expect(injector.get('token1')).toBe('direct');
});
it('should add the providers of exported modules', () => {
@NgModule({providers: [{provide: 'token1', useValue: 'exported'}]})
class ExportedValue {}
@NgModule({exports: [ExportedValue]})
class SomeModule {}
const injector = createModule(SomeModule).injector;
expect(injector.get(SomeModule)).toBeInstanceOf(SomeModule);
expect(injector.get(ExportedValue)).toBeInstanceOf(ExportedValue);
expect(injector.get('token1')).toBe('exported');
});
it('should overwrite the providers of exported modules', () => {
@NgModule({providers: [{provide: 'token1', useValue: 'exported'}]})
class ExportedModule {}
@NgModule({providers: [{provide: 'token1', useValue: 'direct'}], exports: [ExportedModule]})
class SomeModule {}
const injector = createModule(SomeModule).injector;
expect(injector.get('token1')).toBe('direct');
});
it('should overwrite the providers of imported modules by following imported modules', () => {
@NgModule({providers: [{provide: 'token1', useValue: 'imported1'}]})
class ImportedModule1 {}
@NgModule({providers: [{provide: 'token1', useValue: 'imported2'}]})
class ImportedModule2 {}
@NgModule({imports: [ImportedModule1, ImportedModule2]})
class SomeModule {}
const injector = createModule(SomeModule).injector;
expect(injector.get('token1')).toBe('imported2');
});
it('should overwrite the providers of exported modules by following exported modules', () => {
@NgModule({providers: [{provide: 'token1', useValue: 'exported1'}]})
class ExportedModule1 {}
@NgModule({providers: [{provide: 'token1', useValue: 'exported2'}]})
class ExportedModule2 {}
@NgModule({exports: [ExportedModule1, ExportedModule2]})
class SomeModule {}
const injector = createModule(SomeModule).injector;
expect(injector.get('token1')).toBe('exported2');
});
it('should overwrite the providers of imported modules by exported modules', () => {
@NgModule({providers: [{provide: 'token1', useValue: 'imported'}]})
class ImportedModule {}
@NgModule({providers: [{provide: 'token1', useValue: 'exported'}]})
class ExportedModule {}
@NgModule({imports: [ImportedModule], exports: [ExportedModule]})
class SomeModule {}
const injector = createModule(SomeModule).injector;
expect(injector.get('token1')).toBe('exported');
});
it('should not overwrite the providers if a module was already used on the same level', () => {
@NgModule({providers: [{provide: 'token1', useValue: 'imported1'}]})
class ImportedModule1 {}
@NgModule({providers: [{provide: 'token1', useValue: 'imported2'}]})
class ImportedModule2 {}
@NgModule({imports: [ImportedModule1, ImportedModule2, ImportedModule1]})
class SomeModule {}
const injector = createModule(SomeModule).injector;
expect(injector.get('token1')).toBe('imported2');
});
it('should not overwrite the providers if a module was already used on a child level', () => {
@NgModule({providers: [{provide: 'token1', useValue: 'imported1'}]})
class ImportedModule1 {}
@NgModule({imports: [ImportedModule1]})
class ImportedModule3 {}
@NgModule({providers: [{provide: 'token1', useValue: 'imported2'}]})
class ImportedModule2 {}
@NgModule({imports: [ImportedModule3, ImportedModule2, ImportedModule1]})
class SomeModule {}
const injector = createModule(SomeModule).injector;
expect(injector.get('token1')).toBe('imported2');
});
it('should throw when given invalid providers in an imported ModuleWithProviders', () => {
@NgModule()
class ImportedModule1 {}
@NgModule({imports: [{ngModule: ImportedModule1, providers: [<any>'broken']}]})
class SomeModule {}
expect(() => createModule(SomeModule).injector).toThrowError(
`Invalid provider for the NgModule 'ImportedModule1' - only instances of Provider and Type are allowed, got: [?broken?]`,
);
});
});
describe('tree shakable providers', () => {
it('definition should not persist across NgModuleRef instances', () => {
@NgModule()
class SomeModule {}
class Bar {
static ɵprov = ɵɵdefineInjectable({
token: Bar,
factory: () => new Bar(),
providedIn: SomeModule,
});
}
const factory = createModuleFactory(SomeModule);
const ngModuleRef1 = factory.create(null);
// Inject a tree shakeable provider token.
ngModuleRef1.injector.get(Bar);
// Tree Shakeable provider definition should be available.
const providerDef1 = (ngModuleRef1 as any)._r3Injector.records.get(Bar);
expect(providerDef1).not.toBeUndefined();
// Instantiate the same module. The tree shakeable provider definition should not be
// present.
const ngModuleRef2 = factory.create(null);
const providerDef2 = (ngModuleRef2 as any)._r3Injector.records.get(Bar);
expect(providerDef2).toBeUndefined();
});
});
});
});
| {
"end_byte": 40300,
"start_byte": 32196,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/ng_module_integration_spec.ts"
} |
angular/packages/core/test/linker/source_map_util.ts_0_1429 | /**
* @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 {SourceMap} from '@angular/compiler';
import {SourceMapConsumer} from 'source-map';
export interface SourceLocation {
line: number | null;
column: number | null;
source: string | null;
}
export async function originalPositionFor(
sourceMap: SourceMap,
genPosition: {line: number; column: number},
): Promise<SourceLocation> {
// Note: The `SourceMap` type from the compiler is different to `RawSourceMap`
// from the `source-map` package, but the method we rely on works as expected.
const smc = await new SourceMapConsumer(sourceMap as any);
// Note: We don't return the original object as it also contains a `name` property
// which is always null and we don't want to include that in our assertions...
const {line, column, source} = smc.originalPositionFor(genPosition);
return {line, column, source};
}
export function extractSourceMap(source: string): SourceMap | null {
let idx = source.lastIndexOf('\n//#');
if (idx == -1) return null;
const smComment = source.slice(idx).split('\n', 2)[1].trim();
const smB64 = smComment.split('sourceMappingURL=data:application/json;base64,')[1];
return smB64 ? (JSON.parse(Buffer.from(smB64, 'base64').toString()) as SourceMap) : null;
}
| {
"end_byte": 1429,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/source_map_util.ts"
} |
angular/packages/core/test/linker/inheritance_integration_spec.ts_0_3146 | /**
* @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, HostBinding} from '@angular/core';
import {TestBed} from '@angular/core/testing';
@Directive({
selector: '[directiveA]',
standalone: false,
})
class DirectiveA {}
@Directive({
selector: '[directiveB]',
standalone: false,
})
class DirectiveB {
@HostBinding('title') title = 'DirectiveB Title';
}
@Component({
selector: 'component-a',
template: 'ComponentA Template',
standalone: false,
})
class ComponentA {}
@Component({
selector: 'component-extends-directive',
template: 'ComponentExtendsDirective Template',
standalone: false,
})
class ComponentExtendsDirective extends DirectiveA {}
class ComponentWithNoAnnotation extends ComponentA {}
@Directive({
selector: '[directiveExtendsComponent]',
standalone: false,
})
class DirectiveExtendsComponent extends ComponentA {
@HostBinding('title') title = 'DirectiveExtendsComponent Title';
}
class DirectiveWithNoAnnotation extends DirectiveB {}
@Component({
selector: 'my-app',
template: '...',
standalone: false,
})
class App {}
describe('Inheritance logic', () => {
it('should handle Components that extend Directives', () => {
TestBed.configureTestingModule({declarations: [ComponentExtendsDirective, App]});
const template = '<component-extends-directive></component-extends-directive>';
TestBed.overrideComponent(App, {set: {template}});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.nativeElement.firstChild.innerHTML).toBe('ComponentExtendsDirective Template');
});
it('should handle classes with no annotations that extend Components', () => {
TestBed.configureTestingModule({declarations: [ComponentWithNoAnnotation, App]});
const template = '<component-a></component-a>';
TestBed.overrideComponent(App, {set: {template}});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.nativeElement.firstChild.innerHTML).toBe('ComponentA Template');
});
it('should handle classes with no annotations that extend Directives', () => {
TestBed.configureTestingModule({declarations: [DirectiveWithNoAnnotation, App]});
const template = '<div directiveB></div>';
TestBed.overrideComponent(App, {set: {template}});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.nativeElement.firstChild.title).toBe('DirectiveB Title');
});
it('should throw in case a Directive tries to extend a Component', () => {
TestBed.configureTestingModule({declarations: [DirectiveExtendsComponent, App]});
const template = '<div directiveExtendsComponent>Some content</div>';
TestBed.overrideComponent(App, {set: {template}});
expect(() => TestBed.createComponent(App)).toThrowError(
'NG0903: Directives cannot inherit Components. Directive DirectiveExtendsComponent is attempting to extend component ComponentA',
);
});
});
| {
"end_byte": 3146,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/inheritance_integration_spec.ts"
} |
angular/packages/core/test/linker/query_list_spec.ts_0_6024 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ɵgetDOM as getDOM} from '@angular/common';
import {QueryList} from '@angular/core/src/linker/query_list';
import {iterateListLike} from '@angular/core/src/util/iterable';
import {fakeAsync, tick} from '@angular/core/testing';
describe('QueryList', () => {
let queryList: QueryList<string>;
let log: string;
beforeEach(() => {
queryList = new QueryList<string>();
log = '';
});
function logAppend(item: string) {
log += (log.length == 0 ? '' : ', ') + item;
}
describe('dirty and reset', () => {
it('should initially be dirty and empty', () => {
expect(queryList.dirty).toBeTruthy();
expect(queryList.length).toBe(0);
});
it('should be not dirty after reset', () => {
expect(queryList.dirty).toBeTruthy();
queryList.reset(['one', 'two']);
expect(queryList.dirty).toBeFalsy();
expect(queryList.length).toBe(2);
});
});
it('should support resetting and iterating over the new objects', () => {
queryList.reset(['one']);
queryList.reset(['two']);
iterateListLike(queryList, logAppend);
expect(log).toEqual('two');
});
it('should support length', () => {
queryList.reset(['one', 'two']);
expect(queryList.length).toEqual(2);
});
it('should support get', () => {
queryList.reset(['one', 'two']);
expect(queryList.get(1)).toEqual('two');
});
it('should support map', () => {
queryList.reset(['one', 'two']);
expect(queryList.map((x) => x)).toEqual(['one', 'two']);
});
it('should support map with index', () => {
queryList.reset(['one', 'two']);
expect(queryList.map((x, i) => `${x}_${i}`)).toEqual(['one_0', 'two_1']);
});
it('should support forEach', () => {
queryList.reset(['one', 'two']);
let join = '';
queryList.forEach((x) => (join = join + x));
expect(join).toEqual('onetwo');
});
it('should support forEach with index', () => {
queryList.reset(['one', 'two']);
let join = '';
queryList.forEach((x, i) => (join = join + x + i));
expect(join).toEqual('one0two1');
});
it('should support filter', () => {
queryList.reset(['one', 'two']);
expect(queryList.filter((x: string) => x == 'one')).toEqual(['one']);
});
it('should support filter with index', () => {
queryList.reset(['one', 'two']);
expect(queryList.filter((x: string, i: number) => i == 0)).toEqual(['one']);
});
it('should support find', () => {
queryList.reset(['one', 'two']);
expect(queryList.find((x: string) => x == 'two')).toEqual('two');
});
it('should support find with index', () => {
queryList.reset(['one', 'two']);
expect(queryList.find((x: string, i: number) => i == 1)).toEqual('two');
});
it('should support reduce', () => {
queryList.reset(['one', 'two']);
expect(queryList.reduce((a: string, x: string) => a + x, 'start:')).toEqual('start:onetwo');
});
it('should support reduce with index', () => {
queryList.reset(['one', 'two']);
expect(queryList.reduce((a: string, x: string, i: number) => a + x + i, 'start:')).toEqual(
'start:one0two1',
);
});
it('should support toArray', () => {
queryList.reset(['one', 'two']);
expect(queryList.reduce((a: string, x: string) => a + x, 'start:')).toEqual('start:onetwo');
});
it('should support toArray', () => {
queryList.reset(['one', 'two']);
expect(queryList.toArray()).toEqual(['one', 'two']);
});
it('should support toString', () => {
queryList.reset(['one', 'two']);
const listString = queryList.toString();
expect(listString.indexOf('one') != -1).toBeTruthy();
expect(listString.indexOf('two') != -1).toBeTruthy();
});
it('should support first and last', () => {
queryList.reset(['one', 'two', 'three']);
expect(queryList.first).toEqual('one');
expect(queryList.last).toEqual('three');
});
it('should support some', () => {
queryList.reset(['one', 'two', 'three']);
expect(queryList.some((item) => item === 'one')).toEqual(true);
expect(queryList.some((item) => item === 'four')).toEqual(false);
});
it('should support guards on filter', () => {
const qList = new QueryList<'foo' | 'bar'>();
qList.reset(['foo']);
const foos: Array<'foo'> = queryList.filter((item): item is 'foo' => item === 'foo');
expect(qList.length).toEqual(1);
});
it('should be iterable', () => {
const data = ['one', 'two', 'three'];
queryList.reset([...data]);
// The type here is load-bearing: it asserts that queryList is considered assignable to
// Iterable<string> in TypeScript. This is important for template type-checking of *ngFor
// when looping over query results.
const queryListAsIterable: Iterable<string> = queryList;
// For loops use the iteration protocol.
for (const value of queryListAsIterable) {
expect(value).toBe(data.shift()!);
}
expect(data.length).toBe(0);
});
if (getDOM().supportsDOMEvents) {
describe('simple observable interface', () => {
it('should fire callbacks on change', fakeAsync(() => {
let fires = 0;
queryList.changes.subscribe({
next: (_) => {
fires += 1;
},
});
queryList.notifyOnChanges();
tick();
expect(fires).toEqual(1);
queryList.notifyOnChanges();
tick();
expect(fires).toEqual(2);
}));
it('should provides query list as an argument', fakeAsync(() => {
let recorded!: QueryList<string>;
queryList.changes.subscribe({
next: (v: QueryList<string>) => {
recorded = v;
},
});
queryList.reset(['one']);
queryList.notifyOnChanges();
tick();
expect(recorded).toBe(queryList);
}));
});
}
});
| {
"end_byte": 6024,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/query_list_spec.ts"
} |
angular/packages/core/test/testability/testability_spec.ts_0_7132 | /**
* @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 {EventEmitter} from '@angular/core';
import {Injectable} from '@angular/core/src/di';
import {
GetTestability,
PendingMacrotask,
Testability,
TestabilityRegistry,
} from '@angular/core/src/testability/testability';
import {NgZone} from '@angular/core/src/zone/ng_zone';
import {fakeAsync, tick, waitForAsync} from '@angular/core/testing';
import {setTestabilityGetter} from '../../src/testability/testability';
// Schedules a microtasks (using queueMicrotask)
function microTask(fn: Function): void {
queueMicrotask(() => {
// We do double dispatch so that we can wait for queueMicrotask in the Testability when
// NgZone becomes stable.
queueMicrotask(() => fn());
});
}
class NoopGetTestability implements GetTestability {
addToWindow(registry: TestabilityRegistry): void {}
findTestabilityInTree(
registry: TestabilityRegistry,
elem: any,
findInAncestors: boolean,
): Testability | null {
return null;
}
}
@Injectable()
class MockNgZone extends NgZone {
/** @internal */
override onUnstable: EventEmitter<any>;
/** @internal */
override onStable: EventEmitter<any>;
constructor() {
super({enableLongStackTrace: false});
this.onUnstable = new EventEmitter(false);
this.onStable = new EventEmitter(false);
}
unstable(): void {
this.onUnstable.emit(null);
}
stable(): void {
this.onStable.emit(null);
}
}
describe('Testability', () => {
let testability: Testability;
let execute: any;
let execute2: any;
let updateCallback: any;
let ngZone: MockNgZone;
beforeEach(waitForAsync(() => {
ngZone = new MockNgZone();
testability = new Testability(ngZone, new TestabilityRegistry(), new NoopGetTestability());
execute = jasmine.createSpy('execute');
execute2 = jasmine.createSpy('execute');
updateCallback = jasmine.createSpy('execute');
}));
afterEach(() => {
// Instantiating the Testability (via `new Testability` above) has a side
// effect of defining the testability getter globally to a specified value.
// This call resets that reference after each test to make sure it does not
// get leaked between tests. In real scenarios this is not a problem, since
// the `Testability` is created via DI and uses the same testability getter
// (injected into a constructor) across all instances.
setTestabilityGetter(null! as GetTestability);
});
describe('NgZone callback logic', () => {
describe('whenStable with timeout', () => {
it('should fire if Angular is already stable', waitForAsync(() => {
testability.whenStable(execute, 200);
microTask(() => {
expect(execute).toHaveBeenCalled();
});
}));
it('should fire when macroTasks are cancelled', fakeAsync(() => {
const id = ngZone.run(() => setTimeout(() => {}, 1000));
testability.whenStable(execute, 500);
tick(200);
ngZone.run(() => clearTimeout(id));
// fakeAsync doesn't trigger NgZones whenStable
ngZone.stable();
tick(1);
expect(execute).toHaveBeenCalled();
}));
it('calls the done callback when angular is stable', fakeAsync(() => {
let timeout1Done = false;
ngZone.run(() => setTimeout(() => (timeout1Done = true), 500));
testability.whenStable(execute, 1000);
tick(600);
ngZone.stable();
tick();
expect(timeout1Done).toEqual(true);
expect(execute).toHaveBeenCalled();
// Should cancel the done timeout.
tick(500);
ngZone.stable();
tick();
expect(execute.calls.count()).toEqual(1);
}));
it('calls update when macro tasks change', fakeAsync(() => {
let timeout1Done = false;
let timeout2Done = false;
ngZone.run(() => setTimeout(() => (timeout1Done = true), 500));
tick();
testability.whenStable(execute, 1000, updateCallback);
tick(100);
ngZone.run(() => setTimeout(() => (timeout2Done = true), 300));
expect(updateCallback.calls.count()).toEqual(1);
tick(600);
expect(timeout1Done).toEqual(true);
expect(timeout2Done).toEqual(true);
expect(updateCallback.calls.count()).toEqual(3);
expect(execute).toHaveBeenCalled();
const update1 = updateCallback.calls.all()[0].args[0] as PendingMacrotask[];
expect(update1[0].data!.delay).toEqual(500);
const update2 = updateCallback.calls.all()[1].args[0] as PendingMacrotask[];
expect(update2[0].data!.delay).toEqual(500);
expect(update2[1].data!.delay).toEqual(300);
}));
it('cancels the done callback if the update callback returns true', fakeAsync(() => {
let timeoutDone = false;
ngZone.unstable();
execute2.and.returnValue(true);
testability.whenStable(execute, 1000, execute2);
tick(100);
ngZone.run(() => setTimeout(() => (timeoutDone = true), 500));
ngZone.stable();
expect(execute2).toHaveBeenCalled();
tick(500);
ngZone.stable();
tick();
expect(execute).not.toHaveBeenCalled();
}));
});
it('should fire whenstable callback if event is already finished', fakeAsync(() => {
ngZone.unstable();
ngZone.stable();
testability.whenStable(execute);
tick();
expect(execute).toHaveBeenCalled();
}));
it('should not fire whenstable callbacks synchronously if event is already finished', () => {
ngZone.unstable();
ngZone.stable();
testability.whenStable(execute);
expect(execute).not.toHaveBeenCalled();
});
it('should fire whenstable callback when event finishes', fakeAsync(() => {
ngZone.unstable();
testability.whenStable(execute);
tick();
expect(execute).not.toHaveBeenCalled();
ngZone.stable();
tick();
expect(execute).toHaveBeenCalled();
}));
it('should not fire whenstable callbacks synchronously when event finishes', () => {
ngZone.unstable();
testability.whenStable(execute);
ngZone.stable();
expect(execute).not.toHaveBeenCalled();
});
it('should fire whenstable callback with didWork if event is already finished', fakeAsync(() => {
ngZone.unstable();
ngZone.stable();
testability.whenStable(execute);
tick();
expect(execute).toHaveBeenCalled();
testability.whenStable(execute2);
tick();
expect(execute2).toHaveBeenCalled();
}));
it('should fire whenstable callback with didwork when event finishes', fakeAsync(() => {
ngZone.unstable();
testability.whenStable(execute);
tick();
ngZone.stable();
tick();
expect(execute).toHaveBeenCalled();
testability.whenStable(execute2);
tick();
expect(execute2).toHaveBeenCalled();
}));
});
}); | {
"end_byte": 7132,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/testability/testability_spec.ts"
} |
angular/packages/core/test/testability/testability_spec.ts_7134_9494 | describe('TestabilityRegistry', () => {
let testability1: Testability;
let testability2: Testability;
let registry: TestabilityRegistry;
let ngZone: MockNgZone;
beforeEach(waitForAsync(() => {
ngZone = new MockNgZone();
registry = new TestabilityRegistry();
testability1 = new Testability(ngZone, registry, new NoopGetTestability());
testability2 = new Testability(ngZone, registry, new NoopGetTestability());
}));
afterEach(() => {
// Instantiating the Testability (via `new Testability` above) has a side
// effect of defining the testability getter globally to a specified value.
// This call resets that reference after each test to make sure it does not
// get leaked between tests. In real scenarios this is not a problem, since
// the `Testability` is created via DI and uses the same testability getter
// (injected into a constructor) across all instances.
setTestabilityGetter(null! as GetTestability);
});
describe('unregister testability', () => {
it('should remove the testability when unregistering an existing testability', () => {
registry.registerApplication('testability1', testability1);
registry.registerApplication('testability2', testability2);
registry.unregisterApplication('testability2');
expect(registry.getAllTestabilities().length).toEqual(1);
expect(registry.getTestability('testability1')).toEqual(testability1);
});
it('should remain the same when unregistering a non-existing testability', () => {
expect(registry.getAllTestabilities().length).toEqual(0);
registry.registerApplication('testability1', testability1);
registry.registerApplication('testability2', testability2);
registry.unregisterApplication('testability3');
expect(registry.getAllTestabilities().length).toEqual(2);
expect(registry.getTestability('testability1')).toEqual(testability1);
expect(registry.getTestability('testability2')).toEqual(testability2);
});
it('should remove all the testability when unregistering all testabilities', () => {
registry.registerApplication('testability1', testability1);
registry.registerApplication('testability2', testability2);
registry.unregisterAllApplications();
expect(registry.getAllTestabilities().length).toEqual(0);
});
});
}); | {
"end_byte": 9494,
"start_byte": 7134,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/testability/testability_spec.ts"
} |
angular/packages/core/test/signals/effect_util.ts_0_892 | /**
* @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 {createWatch, Watch, WatchCleanupFn} from '@angular/core/primitives/signals';
let queue = new Set<Watch>();
/**
* A wrapper around `Watch` that emulates the `effect` API and allows for more streamlined testing.
*/
export function testingEffect(
effectFn: (onCleanup: (cleanupFn: WatchCleanupFn) => void) => void,
): () => void {
const w = createWatch(effectFn, queue.add.bind(queue), true);
// Effects start dirty.
w.notify();
return () => {
queue.delete(w);
w.destroy();
};
}
export function flushEffects(): void {
for (const watch of queue) {
queue.delete(watch);
watch.run();
}
}
export function resetEffects(): void {
queue.clear();
}
| {
"end_byte": 892,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/signals/effect_util.ts"
} |
angular/packages/core/test/signals/glitch_free_spec.ts_0_1161 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {computed, signal} from '@angular/core';
describe('glitch-free computations', () => {
it('should recompute only once for diamond dependency graph', () => {
let fullRecompute = 0;
const name = signal('John Doe');
const first = computed(() => name().split(' ')[0]);
const last = computed(() => name().split(' ')[1]);
const full = computed(() => {
fullRecompute++;
return `${first()}/${last()}`;
});
expect(full()).toEqual('John/Doe');
expect(fullRecompute).toEqual(1);
name.set('Bob Fisher');
expect(full()).toEqual('Bob/Fisher');
expect(fullRecompute).toEqual(2);
});
it('should recompute only once', () => {
const a = signal('a');
const b = computed(() => a() + 'b');
let cRecompute = 0;
const c = computed(() => {
return `${a()}|${b()}|${++cRecompute}`;
});
expect(c()).toEqual('a|ab|1');
a.set('A');
expect(c()).toEqual('A|Ab|2');
});
});
| {
"end_byte": 1161,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/signals/glitch_free_spec.ts"
} |
angular/packages/core/test/signals/signal_spec.ts_0_6656 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {computed, signal} from '@angular/core';
import {ReactiveNode, setPostSignalSetFn, SIGNAL} from '@angular/core/primitives/signals';
describe('signals', () => {
it('should be a getter which reflects the set value', () => {
const state = signal(false);
expect(state()).toBeFalse();
state.set(true);
expect(state()).toBeTrue();
});
it('should accept update function to set new value based on the previous one', () => {
const counter = signal(0);
expect(counter()).toEqual(0);
counter.update((c) => c + 1);
expect(counter()).toEqual(1);
});
it('should not update signal when new value is equal to the previous one', () => {
const state = signal('aaa', {equal: (a, b) => a.length === b.length});
expect(state()).toEqual('aaa');
// set to a "different" value that is "equal" to the previous one
// there should be no change in the signal's value as the new value is determined to be equal
// to the previous one
state.set('bbb');
expect(state()).toEqual('aaa');
state.update((_) => 'ccc');
expect(state()).toEqual('aaa');
// setting a "non-equal" value
state.set('d');
expect(state()).toEqual('d');
});
it('should not propagate change when the new signal value is equal to the previous one', () => {
const state = signal('aaa', {equal: (a, b) => a.length === b.length});
const upper = computed(() => state().toUpperCase());
// set to a "different" value that is "equal" to the previous one
// there should be no change in the signal's value as the new value is determined to be equal
// to the previous one
state.set('bbb');
expect(upper()).toEqual('AAA');
state.update((_) => 'ccc');
expect(upper()).toEqual('AAA');
// setting a "non-equal" value
state.set('d');
expect(upper()).toEqual('D');
});
it('should consider objects as equal based on their identity with the default equality function', () => {
let stateValue: unknown = {};
const state = signal(stateValue);
let computeCount = 0;
const derived = computed(() => `${typeof state()}:${++computeCount}`);
expect(derived()).toEqual('object:1');
// reset signal value to the same object instance, expect NO change notification
state.set(stateValue);
expect(derived()).toEqual('object:1');
// reset signal value to a different object instance, expect change notification
stateValue = {};
state.set(stateValue);
expect(derived()).toEqual('object:2');
// reset signal value to a different object type, expect change notification
stateValue = [];
state.set(stateValue);
expect(derived()).toEqual('object:3');
// reset signal value to the same array instance, expect NO change notification
state.set(stateValue);
expect(derived()).toEqual('object:3');
});
it('should invoke custom equality function even if old / new references are the same', () => {
const state = {value: 0};
const stateSignal = signal(state, {equal: (a, b) => false});
let computeCount = 0;
const derived = computed(() => `${stateSignal().value}:${++computeCount}`);
// derived is re-computed initially
expect(derived()).toBe('0:1');
// setting signal with the same reference should propagate change due to the custom equality
stateSignal.set(state);
expect(derived()).toBe('0:2');
// updating signal with the same reference should propagate change as well
stateSignal.update((state) => state);
expect(derived()).toBe('0:3');
});
it('should allow converting writable signals to their readonly counterpart', () => {
const counter = signal(0);
const readOnlyCounter = counter.asReadonly();
// @ts-expect-error
expect(readOnlyCounter.set).toBeUndefined();
// @ts-expect-error
expect(readOnlyCounter.update).toBeUndefined();
const double = computed(() => readOnlyCounter() * 2);
expect(double()).toBe(0);
counter.set(2);
expect(double()).toBe(4);
});
it('should have a toString implementation', () => {
const state = signal(false);
expect(state + '').toBe('[Signal: false]');
});
it('should set debugName when a debugName is provided', () => {
const node = signal(false, {debugName: 'falseSignal'})[SIGNAL] as ReactiveNode;
expect(node.debugName).toBe('falseSignal');
});
describe('optimizations', () => {
it('should not repeatedly poll status of a non-live node if no signals have changed', () => {
const unrelated = signal(0);
const source = signal(1);
let computations = 0;
const derived = computed(() => {
computations++;
return source() * 2;
});
expect(derived()).toBe(2);
expect(computations).toBe(1);
const sourceNode = source[SIGNAL] as ReactiveNode;
// Forcibly increment the version of the source signal. This will cause a mismatch during
// polling, and will force the derived signal to recompute if polled (which we should observe
// in this test).
sourceNode.version++;
// Read the derived signal again. This should not recompute (even with the forced version
// update) as no signals have been set since the last read.
expect(derived()).toBe(2);
expect(computations).toBe(1);
// Set the `unrelated` signal, which now means that `derived` should poll if read again.
// Because of the forced version, that poll will cause a recomputation which we will observe.
unrelated.set(1);
expect(derived()).toBe(2);
expect(computations).toBe(2);
});
});
describe('post-signal-set functions', () => {
let prevPostSignalSetFn: (() => void) | null = null;
let log: number;
beforeEach(() => {
log = 0;
prevPostSignalSetFn = setPostSignalSetFn(() => log++);
});
afterEach(() => {
setPostSignalSetFn(prevPostSignalSetFn);
});
it('should call the post-signal-set fn when invoking .set()', () => {
const counter = signal(0);
counter.set(1);
expect(log).toBe(1);
});
it('should call the post-signal-set fn when invoking .update()', () => {
const counter = signal(0);
counter.update((c) => c + 2);
expect(log).toBe(1);
});
it("should not call the post-signal-set fn when the value doesn't change", () => {
const counter = signal(0);
counter.set(0);
expect(log).toBe(0);
});
});
});
| {
"end_byte": 6656,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/signals/signal_spec.ts"
} |
angular/packages/core/test/signals/watch_spec.ts_0_6528 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {computed, signal} from '@angular/core';
import {createWatch} from '@angular/core/primitives/signals';
import {flushEffects, resetEffects, testingEffect} from './effect_util';
const NOOP_FN = () => {};
describe('watchers', () => {
afterEach(() => {
resetEffects();
});
it('should create and run once, even without dependencies', () => {
let runs = 0;
testingEffect(() => {
runs++;
});
flushEffects();
expect(runs).toEqual(1);
});
it('should schedule on dependencies (signal) change', () => {
const count = signal(0);
let runLog: number[] = [];
const effectRef = testingEffect(() => {
runLog.push(count());
});
flushEffects();
expect(runLog).toEqual([0]);
count.set(1);
flushEffects();
expect(runLog).toEqual([0, 1]);
});
it('should not schedule when a previous dependency changes', () => {
const increment = (value: number) => value + 1;
const countA = signal(0);
const countB = signal(100);
const useCountA = signal(true);
const runLog: number[] = [];
testingEffect(() => {
runLog.push(useCountA() ? countA() : countB());
});
flushEffects();
expect(runLog).toEqual([0]);
countB.update(increment);
flushEffects();
// No update expected: updated the wrong signal.
expect(runLog).toEqual([0]);
countA.update(increment);
flushEffects();
expect(runLog).toEqual([0, 1]);
useCountA.set(false);
flushEffects();
expect(runLog).toEqual([0, 1, 101]);
countA.update(increment);
flushEffects();
// No update expected: updated the wrong signal.
expect(runLog).toEqual([0, 1, 101]);
});
it("should not update dependencies when dependencies don't change", () => {
const source = signal(0);
const isEven = computed(() => source() % 2 === 0);
let updateCounter = 0;
testingEffect(() => {
isEven();
updateCounter++;
});
flushEffects();
expect(updateCounter).toEqual(1);
source.set(1);
flushEffects();
expect(updateCounter).toEqual(2);
source.set(3);
flushEffects();
expect(updateCounter).toEqual(2);
source.set(4);
flushEffects();
expect(updateCounter).toEqual(3);
});
it('should allow registering cleanup function from the watch logic', () => {
const source = signal(0);
const seenCounterValues: number[] = [];
testingEffect((onCleanup) => {
seenCounterValues.push(source());
// register a cleanup function that is executed every time an effect re-runs
onCleanup(() => {
if (seenCounterValues.length === 2) {
seenCounterValues.length = 0;
}
});
});
flushEffects();
expect(seenCounterValues).toEqual([0]);
source.update((c) => c + 1);
flushEffects();
expect(seenCounterValues).toEqual([0, 1]);
source.update((c) => c + 1);
flushEffects();
// cleanup (array trim) should have run before executing effect
expect(seenCounterValues).toEqual([2]);
});
it('should forget previously registered cleanup function when effect re-runs', () => {
const source = signal(0);
const seenCounterValues: number[] = [];
testingEffect((onCleanup) => {
const value = source();
seenCounterValues.push(value);
// register a cleanup function that is executed next time an effect re-runs
if (value === 0) {
onCleanup(() => {
seenCounterValues.length = 0;
});
}
});
flushEffects();
expect(seenCounterValues).toEqual([0]);
source.set(2);
flushEffects();
// cleanup (array trim) should have run before executing effect
expect(seenCounterValues).toEqual([2]);
source.set(3);
flushEffects();
// cleanup (array trim) should _not_ be registered again
expect(seenCounterValues).toEqual([2, 3]);
});
it('should throw an error when reading a signal during the notification phase', () => {
const source = signal(0);
let ranScheduler = false;
const w = createWatch(
() => {
source();
},
() => {
ranScheduler = true;
expect(() => source()).toThrow();
},
false,
);
// Run the effect manually to initiate dependency tracking.
w.run();
// Changing the signal will attempt to schedule the effect.
source.set(1);
expect(ranScheduler).toBeTrue();
});
describe('destroy', () => {
it('should not run destroyed watchers', () => {
let watchRuns = 0;
const watchRef = createWatch(
() => {
watchRuns++;
},
NOOP_FN,
false,
);
watchRef.run();
expect(watchRuns).toBe(1);
watchRef.destroy();
watchRef.run();
expect(watchRuns).toBe(1);
});
it('should disconnect destroyed watches from the reactive graph', () => {
const counter = signal(0);
let scheduleCount = 0;
const watchRef = createWatch(
() => counter(),
() => scheduleCount++,
false,
);
// watches are _not_ scheduled by default, run it for the first time to capture
// dependencies
watchRef.run();
expect(scheduleCount).toBe(0);
watchRef.destroy();
counter.set(1);
expect(scheduleCount).toBe(0);
});
it('should not schedule destroyed watches', () => {
let scheduleCount = 0;
const watchRef = createWatch(NOOP_FN, () => scheduleCount++, false);
// watches are _not_ scheduled by default
expect(scheduleCount).toBe(0);
watchRef.notify();
expect(scheduleCount).toBe(1);
watchRef.destroy();
watchRef.notify();
expect(scheduleCount).toBe(1);
});
it('should not run cleanup functions after destroy', () => {
const counter = signal(0);
let cleanupRuns = 0;
const watchRef = createWatch(
(onCleanup) => {
counter();
onCleanup(() => cleanupRuns++);
},
NOOP_FN,
false,
);
// initial run to register cleanup function
watchRef.run();
watchRef.destroy();
// cleanup functions run on destroy
expect(cleanupRuns).toBe(1);
// subsequent destroy should be noop
watchRef.destroy();
expect(cleanupRuns).toBe(1);
});
});
});
| {
"end_byte": 6528,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/signals/watch_spec.ts"
} |
angular/packages/core/test/signals/BUILD.bazel_0_616 | load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library")
package(default_visibility = ["//visibility:private"])
ts_library(
name = "signals_lib",
testonly = True,
srcs = glob(
["**/*.ts"],
),
deps = [
"//packages/core",
"//packages/core/primitives/signals",
"//packages/core/src/util",
],
)
jasmine_node_test(
name = "signals",
bootstrap = ["//tools/testing:node_no_angular"],
deps = [
":signals_lib",
],
)
karma_web_test_suite(
name = "signals_web",
deps = [
":signals_lib",
],
)
| {
"end_byte": 616,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/signals/BUILD.bazel"
} |
angular/packages/core/test/signals/non_reactive_spec.ts_0_2725 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {computed, signal, untracked} from '@angular/core';
import {flushEffects, resetEffects, testingEffect} from './effect_util';
describe('non-reactive reads', () => {
afterEach(() => {
resetEffects();
});
it('should read the latest value from signal', () => {
const counter = signal(0);
expect(untracked(counter)).toEqual(0);
counter.set(1);
expect(untracked(counter)).toEqual(1);
});
it('should not add dependencies to computed when reading a value from a signal', () => {
const counter = signal(0);
const double = computed(() => untracked(counter) * 2);
expect(double()).toEqual(0);
counter.set(2);
expect(double()).toEqual(0);
});
it('should refresh computed value if stale and read non-reactively ', () => {
const counter = signal(0);
const double = computed(() => counter() * 2);
expect(untracked(double)).toEqual(0);
counter.set(2);
expect(untracked(double)).toEqual(4);
});
it('should not make surrounding effect depend on the signal', () => {
const s = signal(1);
const runLog: number[] = [];
testingEffect(() => {
runLog.push(untracked(s));
});
// an effect will run at least once
flushEffects();
expect(runLog).toEqual([1]);
// subsequent signal changes should not trigger effects as signal is untracked
s.set(2);
flushEffects();
expect(runLog).toEqual([1]);
});
it('should schedule on dependencies (computed) change', () => {
const count = signal(0);
const double = computed(() => count() * 2);
let runLog: number[] = [];
testingEffect(() => {
runLog.push(double());
});
flushEffects();
expect(runLog).toEqual([0]);
count.set(1);
flushEffects();
expect(runLog).toEqual([0, 2]);
});
it('should non-reactively read all signals accessed inside untrack', () => {
const first = signal('John');
const last = signal('Doe');
let runLog: string[] = [];
const effectRef = testingEffect(() => {
untracked(() => runLog.push(`${first()} ${last()}`));
});
// effects run at least once
flushEffects();
expect(runLog).toEqual(['John Doe']);
// change one of the signals - should not update as not read reactively
first.set('Patricia');
flushEffects();
expect(runLog).toEqual(['John Doe']);
// change one of the signals - should not update as not read reactively
last.set('Garcia');
flushEffects();
expect(runLog).toEqual(['John Doe']);
});
});
| {
"end_byte": 2725,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/signals/non_reactive_spec.ts"
} |
angular/packages/core/test/signals/computed_spec.ts_0_5491 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {computed, signal} from '@angular/core';
import {createWatch, ReactiveNode, SIGNAL} from '@angular/core/primitives/signals';
describe('computed', () => {
it('should create computed', () => {
const counter = signal(0);
let computedRunCount = 0;
const double = computed(() => `${counter() * 2}:${++computedRunCount}`);
expect(double()).toEqual('0:1');
counter.set(1);
expect(double()).toEqual('2:2');
expect(double()).toEqual('2:2');
counter.set(2);
expect(double()).toEqual('4:3');
expect(double()).toEqual('4:3');
});
it('should not re-compute if there are no dependencies', () => {
let tick = 0;
const c = computed(() => ++tick);
expect(c()).toEqual(1);
expect(c()).toEqual(1);
});
it('should not re-compute if the dependency is a primitive value and the value did not change', () => {
const counter = signal(0);
let computedRunCount = 0;
const double = computed(() => `${counter() * 2}:${++computedRunCount}`);
expect(double()).toEqual('0:1');
counter.set(0);
expect(double()).toEqual('0:1');
});
it('should chain computed', () => {
const name = signal('abc');
const reverse = computed(() => name().split('').reverse().join(''));
const upper = computed(() => reverse().toUpperCase());
expect(upper()).toEqual('CBA');
name.set('foo');
expect(upper()).toEqual('OOF');
});
it('should evaluate computed only when subscribing', () => {
const name = signal('John');
const age = signal(25);
const show = signal(true);
let computeCount = 0;
const displayName = computed(
() => `${show() ? `${name()} aged ${age()}` : 'anonymous'}:${++computeCount}`,
);
expect(displayName()).toEqual('John aged 25:1');
show.set(false);
expect(displayName()).toEqual('anonymous:2');
name.set('Bob');
expect(displayName()).toEqual('anonymous:2');
});
it('should detect simple dependency cycles', () => {
const a: () => unknown = computed(() => a());
expect(() => a()).toThrowError('Detected cycle in computations.');
});
it('should detect deep dependency cycles', () => {
const a: () => unknown = computed(() => b());
const b = computed(() => c());
const c = computed(() => d());
const d = computed(() => a());
expect(() => a()).toThrowError('Detected cycle in computations.');
});
it('should cache exceptions thrown until computed gets dirty again', () => {
const toggle = signal('KO');
const c = computed(() => {
const val = toggle();
if (val === 'KO') {
throw new Error('KO');
} else {
return val;
}
});
expect(() => c()).toThrowError('KO');
expect(() => c()).toThrowError('KO');
toggle.set('OK');
expect(c()).toEqual('OK');
});
it("should not update dependencies of computations when dependencies don't change", () => {
const source = signal(0);
const isEven = computed(() => source() % 2 === 0);
let updateCounter = 0;
const updateTracker = computed(() => {
isEven();
return updateCounter++;
});
updateTracker();
expect(updateCounter).toEqual(1);
source.set(1);
updateTracker();
expect(updateCounter).toEqual(2);
// Setting the counter to another odd value should not trigger `updateTracker` to update.
source.set(3);
updateTracker();
expect(updateCounter).toEqual(2);
source.set(4);
updateTracker();
expect(updateCounter).toEqual(3);
});
it('should not mark dirty computed signals that are dirty already', () => {
const source = signal('a');
const derived = computed(() => source().toUpperCase());
let watchCount = 0;
const w = createWatch(
() => {
derived();
},
() => {
watchCount++;
},
false,
);
w.run();
expect(watchCount).toEqual(0);
// change signal, mark downstream dependencies dirty
source.set('b');
expect(watchCount).toEqual(1);
// change signal again, downstream dependencies should be dirty already and not marked again
source.set('c');
expect(watchCount).toEqual(1);
// resetting dependencies back to clean
w.run();
expect(watchCount).toEqual(1);
// expecting another notification at this point
source.set('d');
expect(watchCount).toEqual(2);
});
it('should allow signal creation within computed', () => {
const doubleCounter = computed(() => {
const counter = signal(1);
return counter() * 2;
});
expect(doubleCounter()).toBe(2);
});
it('should disallow writing to signals within computed', () => {
const source = signal(0);
const illegal = computed(() => {
source.set(1);
return 0;
});
expect(illegal).toThrow();
});
it('should have a toString implementation', () => {
const counter = signal(1);
const double = computed(() => counter() * 2);
expect(double + '').toBe('[Computed: 2]');
});
it('should set debugName when a debugName is provided', () => {
const primitiveSignal = signal(0);
const node = computed(() => primitiveSignal(), {debugName: 'computedSignal'})[
SIGNAL
] as ReactiveNode;
expect(node.debugName).toBe('computedSignal');
});
});
| {
"end_byte": 5491,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/signals/computed_spec.ts"
} |
angular/packages/core/test/signals/linked_signal_spec.ts_0_8278 | /**
* @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.io/license
*/
import {isSignal, linkedSignal, signal, computed} from '@angular/core';
import {testingEffect} from './effect_util';
describe('linkedSignal', () => {
it('should conform to the writable signals contract', () => {
const firstLetter = linkedSignal({source: signal<string>('foo'), computation: (str) => str[0]});
expect(isSignal(firstLetter)).toBeTrue();
firstLetter.set('a');
expect(firstLetter()).toBe('a');
firstLetter.update((_) => 'b');
expect(firstLetter()).toBe('b');
const firstLetterReadonly = firstLetter.asReadonly();
expect(firstLetterReadonly()).toBe('b');
firstLetter.set('c');
expect(firstLetterReadonly()).toBe('c');
expect(firstLetter.toString()).toBe('[LinkedSignal: c]');
});
it('should conform to the writable signals contract - shorthand', () => {
const str = signal<string>('foo');
const firstLetter = linkedSignal(() => str()[0]);
expect(isSignal(firstLetter)).toBeTrue();
firstLetter.set('a');
expect(firstLetter()).toBe('a');
firstLetter.update((_) => 'b');
expect(firstLetter()).toBe('b');
const firstLetterReadonly = firstLetter.asReadonly();
expect(firstLetterReadonly()).toBe('b');
firstLetter.set('c');
expect(firstLetterReadonly()).toBe('c');
});
it('should update when the source changes', () => {
const options = signal(['apple', 'banana', 'fig']);
const choice = linkedSignal({
source: options,
computation: (options) => options[0],
});
expect(choice()).toBe('apple');
choice.set('fig');
expect(choice()).toBe('fig');
options.set(['orange', 'apple', 'pomegranate']);
expect(choice()).toBe('orange');
});
it('should expose previous source in the computation function', () => {
const options = signal(['apple', 'banana', 'fig']);
const choice = linkedSignal<string[], string>({
source: options,
computation: (options, previous) => {
if (previous !== undefined && options.includes(previous.value)) {
return previous.value;
} else {
return options[0];
}
},
});
expect(choice()).toBe('apple');
options.set(['orange', 'apple', 'pomegranate']);
expect(choice()).toBe('apple');
});
it('should expose previous value in the computation function', () => {
const options = signal(['apple', 'banana', 'fig']);
const choice = linkedSignal<string[], number>({
source: options,
computation: (options, previous) => {
if (previous !== undefined) {
const prevChoice = previous.source[previous.value];
const newIdx = options.indexOf(prevChoice);
return newIdx === -1 ? 0 : newIdx;
} else {
return 0;
}
},
});
expect(choice()).toBe(0);
choice.set(2); // choosing a fig
options.set(['banana', 'fig', 'apple']); // a fig moves to a new place in the updated resource
expect(choice()).toBe(1);
});
it('should expose previous value in the computation function in larger reactive graph', () => {
const options = signal(['apple', 'banana', 'fig']);
const choice = linkedSignal<string[], number>({
source: options,
computation: (options, previous) => {
if (previous !== undefined) {
const prevChoice = previous.source[previous.value];
const newIdx = options.indexOf(prevChoice);
return newIdx === -1 ? 0 : newIdx;
} else {
return 0;
}
},
});
const doubleChoice = computed(() => choice() * 2);
expect(doubleChoice()).toBe(0);
choice.set(2); // choosing a fig
options.set(['banana', 'fig', 'apple']); // a fig moves to a new place in the updated resource
expect(doubleChoice()).toBe(2);
expect(choice()).toBe(1);
});
it('should not update the value if the new choice is considered equal to the previous one', () => {
const counter = signal(0);
const choice = linkedSignal({
source: counter,
computation: (c) => c,
equal: (a, b) => true,
});
expect(choice()).toBe(0);
// updates from the "commanding signal" should follow equality rules
counter.update((c) => c + 1);
expect(choice()).toBe(0);
// the same equality rules should apply to the state signal
choice.set(10);
expect(choice()).toBe(0);
});
it('should support shorthand version', () => {
const options = signal(['apple', 'banana', 'fig']);
const choice = linkedSignal(() => options()[0]);
expect(choice()).toBe('apple');
choice.set('orange');
expect(options()).toEqual(['apple', 'banana', 'fig']);
expect(choice()).toBe('orange');
options.set(['banana', 'fig']);
expect(choice()).toBe('banana');
});
it('should have explicitly set value', () => {
const counter = signal(0);
const options = signal(['apple', 'banana', 'fig']);
const choice = linkedSignal(() => options()[0]);
expect(choice()).toBe('apple');
// state signal is updated while the "commanding" state has pending changes - we assume that the explicit state set is "more important" here
options.set(['orange', 'apple', 'pomegranate']);
choice.set('watermelon');
// unrelated state changes should not effect the test results
counter.update((c) => c + 1);
expect(choice()).toBe('watermelon');
// state signal is updated just before changes to the "commanding" state - here we default to the usual situation of the linked state triggering computation
choice.set('persimmon');
options.set(['apple', 'banana', 'fig']);
expect(choice()).toBe('apple');
// another change using the "update" code-path
options.set(['orange', 'apple', 'pomegranate']);
choice.update((f) => f.toUpperCase());
expect(choice()).toBe('ORANGE');
});
it('should have explicitly set value - live consumer', () => {
const options = signal(['apple', 'banana', 'fig']);
const choice = linkedSignal(() => options()[0]);
expect(choice()).toBe('apple');
// create an effect to mark the linkedSignal as live consumer
const watchDestroy = testingEffect(() => choice());
try {
// state signal is updated while the "commanding" state has pending changes - we assume that the explicit state set is "more important" here
const counter = signal(0);
options.set(['orange', 'apple', 'pomegranate']);
choice.set('watermelon');
// unrelated state changes should not effect the test results
counter.update((c) => c + 1);
expect(choice()).toBe('watermelon');
// state signal is updated just before changes to the "commanding" state - here we default to the usual situation of the linked state triggering computation
choice.set('persimmon');
options.set(['apple', 'banana', 'fig']);
expect(choice()).toBe('apple');
// another change using the "update" code-path
options.set(['orange', 'apple', 'pomegranate']);
choice.update((f) => f.toUpperCase());
expect(choice()).toBe('ORANGE');
} finally {
watchDestroy();
}
});
it('should capture linked signal dependencies even if the value is set before the initial read', () => {
const options = signal(['apple', 'banana', 'fig']);
const choice = linkedSignal(() => options()[0]);
choice.set('watermelon');
expect(choice()).toBe('watermelon');
options.set(['orange', 'apple', 'pomegranate']);
expect(choice()).toBe('orange');
});
it('should pull latest dependency values before state update', () => {
const options = signal(['apple', 'banana', 'fig']);
const choice = linkedSignal(() => options()[0]);
choice.update((fruit) => fruit.toUpperCase());
expect(choice()).toBe('APPLE');
});
it('should reset error state after manual state update', () => {
const choice = linkedSignal<string>(() => {
throw new Error("Can't compute");
});
expect(() => {
choice();
}).toThrowError("Can't compute");
choice.set('explicit');
expect(choice()).toBe('explicit');
});
});
| {
"end_byte": 8278,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/signals/linked_signal_spec.ts"
} |
angular/packages/core/test/signals/is_signal_spec.ts_0_990 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {computed, isSignal, signal} from '@angular/core';
describe('isSignal', () => {
it('should return true for writable signal', () => {
const writableSignal = signal('Angular');
expect(isSignal(writableSignal)).toBe(true);
});
it('should return true for readonly signal', () => {
const readonlySignal = computed(() => 10);
expect(isSignal(readonlySignal)).toBe(true);
});
it('should return false for primitive', () => {
const primitive = 0;
expect(isSignal(primitive)).toBe(false);
});
it('should return false for object', () => {
const object = {name: 'Angular'};
expect(isSignal(object)).toBe(false);
});
it('should return false for function', () => {
const fn = () => {};
expect(isSignal(fn)).toBe(false);
});
});
| {
"end_byte": 990,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/signals/is_signal_spec.ts"
} |
angular/packages/core/test/zone/async-tagging-console.spec.ts_0_4765 | /**
* @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 {AsyncStackTaggingZoneSpec} from '../../src/zone/async-stack-tagging';
describe('AsyncTaggingConsoleTest', () => {
describe('should call console async stack tagging API', () => {
const startAsyncTaskSpy = jasmine.createSpy('startAsyncTask');
const finishAsyncTaskSpy = jasmine.createSpy('finishAsyncTask');
const scheduleAsyncTaskSpy = jasmine.createSpy('scheduleAsyncTask').and.callFake(() => {
return {
run: (f: () => unknown) => {
startAsyncTaskSpy();
const retval = f();
finishAsyncTaskSpy();
return retval;
},
};
});
let asyncStackTaggingZone: Zone;
beforeEach(() => {
scheduleAsyncTaskSpy.calls.reset();
startAsyncTaskSpy.calls.reset();
finishAsyncTaskSpy.calls.reset();
asyncStackTaggingZone = Zone.current.fork(
new AsyncStackTaggingZoneSpec('test', {
createTask: scheduleAsyncTaskSpy,
}),
);
});
it('setTimeout', (done: DoneFn) => {
asyncStackTaggingZone.run(() => {
setTimeout(() => {});
});
setTimeout(() => {
expect(scheduleAsyncTaskSpy).toHaveBeenCalledWith('Zone - setTimeout');
expect(startAsyncTaskSpy.calls.count()).toBe(1);
expect(finishAsyncTaskSpy.calls.count()).toBe(1);
done();
});
});
it('clearTimeout', (done: DoneFn) => {
asyncStackTaggingZone.run(() => {
const id = setTimeout(() => {});
clearTimeout(id);
});
setTimeout(() => {
expect(scheduleAsyncTaskSpy).toHaveBeenCalledWith('Zone - setTimeout');
expect(startAsyncTaskSpy).not.toHaveBeenCalled();
expect(finishAsyncTaskSpy).not.toHaveBeenCalled();
done();
});
});
it('setInterval', (done: DoneFn) => {
asyncStackTaggingZone.run(() => {
let count = 0;
const id = setInterval(() => {
count++;
if (count === 2) {
clearInterval(id);
}
}, 10);
});
setTimeout(() => {
expect(scheduleAsyncTaskSpy).toHaveBeenCalledWith('Zone - setInterval');
expect(startAsyncTaskSpy.calls.count()).toBe(2);
expect(finishAsyncTaskSpy.calls.count()).toBe(2);
done();
}, 50);
});
it('Promise', (done: DoneFn) => {
asyncStackTaggingZone.run(() => {
Promise.resolve(1).then(() => {});
});
setTimeout(() => {
expect(scheduleAsyncTaskSpy).toHaveBeenCalledWith('Zone - Promise.then');
expect(startAsyncTaskSpy.calls.count()).toBe(1);
expect(finishAsyncTaskSpy.calls.count()).toBe(1);
done();
});
});
if (global.XMLHttpRequest) {
it('XMLHttpRequest', (done: DoneFn) => {
asyncStackTaggingZone.run(() => {
const req = new XMLHttpRequest();
req.onload = () => {
Zone.root.run(() => {
setTimeout(() => {
expect(scheduleAsyncTaskSpy.calls.all()[0].args).toEqual([
'Zone - XMLHttpRequest.addEventListener:load',
]);
expect(scheduleAsyncTaskSpy.calls.all()[1].args).toEqual([
'Zone - XMLHttpRequest.send',
]);
expect(startAsyncTaskSpy.calls.count()).toBe(2);
expect(finishAsyncTaskSpy.calls.count()).toBe(2);
done();
});
});
};
req.open('get', '/', true);
req.send();
});
});
}
// Only run test when addEventListener is patched by zone.js
if (
document &&
document.addEventListener &&
(document.addEventListener as any)[Zone.__symbol__('OriginalDelegate')]
) {
it('button click', () => {
asyncStackTaggingZone.run(() => {
const button = document.createElement('button');
const clickEvent = document.createEvent('Event');
clickEvent.initEvent('click', true, true);
document.body.appendChild(button);
const handler = () => {};
button.addEventListener('click', handler);
button.dispatchEvent(clickEvent);
button.dispatchEvent(clickEvent);
button.removeEventListener('click', handler);
expect(scheduleAsyncTaskSpy).toHaveBeenCalledWith(
'Zone - HTMLButtonElement.addEventListener:click',
);
expect(startAsyncTaskSpy.calls.count()).toBe(2);
expect(finishAsyncTaskSpy.calls.count()).toBe(2);
});
});
}
});
});
| {
"end_byte": 4765,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/zone/async-tagging-console.spec.ts"
} |
angular/packages/core/test/zone/ng_zone_spec.ts_0_7811 | /**
* @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,
EventEmitter,
NgZone,
afterRender,
provideZoneChangeDetection,
} from '@angular/core';
import {
TestBed,
fakeAsync,
flush,
flushMicrotasks,
inject,
tick,
waitForAsync,
} from '@angular/core/testing';
import {Log} from '@angular/core/testing/src/testing_internal';
import {firstValueFrom} from 'rxjs';
import {scheduleCallbackWithRafRace as scheduler} from '../../src/util/callback_scheduler';
import {global} from '../../src/util/global';
import {NoopNgZone} from '../../src/zone/ng_zone';
const resultTimer = 1000;
// Schedules a macrotask (using a timer)
function macroTask(fn: (...args: any[]) => void, timer = 1): void {
// adds longer timers for passing tests in IE and Edge
setTimeout(fn, 1);
}
let _log: Log;
let _errors: any[];
let _traces: any[];
let _zone: NgZone;
const resolvedPromise = Promise.resolve(null);
function logOnError() {
_zone.onError.subscribe({
next: (error: any) => {
// Error handler should run outside of the Angular zone.
NgZone.assertNotInAngularZone();
_errors.push(error);
_traces.push(error.stack);
},
});
}
function logOnUnstable() {
_zone.onUnstable.subscribe({next: _log.fn('onUnstable')});
}
function logOnMicrotaskEmpty() {
_zone.onMicrotaskEmpty.subscribe({next: _log.fn('onMicrotaskEmpty')});
}
function logOnStable() {
_zone.onStable.subscribe({next: _log.fn('onStable')});
}
function runNgZoneNoLog(fn: () => any) {
const length = _log.logItems.length;
try {
return _zone.run(fn);
} finally {
// delete anything which may have gotten logged.
_log.logItems.length = length;
}
}
describe('NgZone', () => {
function createZone(enableLongStackTrace: boolean) {
return new NgZone({enableLongStackTrace: enableLongStackTrace});
}
beforeEach(() => {
_log = new Log();
_errors = [];
_traces = [];
});
describe('long stack trace', () => {
beforeEach(() => {
_zone = createZone(true);
logOnUnstable();
logOnMicrotaskEmpty();
logOnStable();
logOnError();
});
commonTests();
it('should produce long stack traces', (done) => {
macroTask(() => {
let resolve: (result: any) => void;
const promise: Promise<any> = new Promise((res) => {
resolve = res;
});
_zone.run(() => {
setTimeout(() => {
setTimeout(() => {
resolve(null);
throw new Error('ccc');
}, 0);
}, 0);
});
promise.then((_) => {
expect(_traces.length).toBe(1);
expect(_traces[0].length).toBeGreaterThan(1);
done();
});
});
});
it('should produce long stack traces (when using microtasks)', (done) => {
macroTask(() => {
let resolve: (result: any) => void;
const promise: Promise<any> = new Promise((res) => {
resolve = res;
});
_zone.run(() => {
queueMicrotask(() => {
queueMicrotask(() => {
resolve(null);
throw new Error('ddd');
});
});
});
promise.then((_) => {
expect(_traces.length).toBe(1);
expect(_traces[0].length).toBeGreaterThan(1);
done();
});
});
});
});
describe('short stack trace', () => {
beforeEach(() => {
_zone = createZone(false);
logOnUnstable();
logOnMicrotaskEmpty();
logOnStable();
logOnError();
});
commonTests();
it('should disable long stack traces', (done) => {
macroTask(() => {
let resolve: (result: any) => void;
const promise: Promise<any> = new Promise((res) => {
resolve = res;
});
_zone.run(() => {
setTimeout(() => {
setTimeout(() => {
resolve(null);
throw new Error('ccc');
}, 0);
}, 0);
});
promise.then((_) => {
expect(_traces.length).toBe(1);
if (_traces[0] != null) {
// some browsers don't have stack traces.
expect(_traces[0].indexOf('---')).toEqual(-1);
}
done();
});
});
});
});
});
describe('NoopNgZone', () => {
const ngZone = new NoopNgZone();
it('should run', () => {
let runs = false;
ngZone.run(() => {
ngZone.runGuarded(() => {
ngZone.runOutsideAngular(() => {
runs = true;
});
});
});
expect(runs).toBe(true);
});
it('should run with this context and arguments', () => {
let runs = false;
let applyThisArray: any[] = [];
let applyArgsArray: any[] = [];
const testContext = {};
const testArgs = ['args'];
ngZone.run(
function (this: any, arg: any) {
applyThisArray.push(this);
applyArgsArray.push([arg]);
ngZone.runGuarded(
function (this: any, argGuarded: any) {
applyThisArray.push(this);
applyArgsArray.push([argGuarded]);
ngZone.runOutsideAngular(function (this: any, argOutsideAngular: any) {
applyThisArray.push(this);
applyArgsArray.push([argOutsideAngular]);
runs = true;
});
},
this,
[arg],
);
},
testContext,
testArgs,
);
expect(runs).toBe(true);
expect(applyThisArray.length).toBe(3);
expect(applyArgsArray.length).toBe(3);
expect(applyThisArray[0]).toBe(testContext);
expect(applyThisArray[1]).toBe(testContext);
expect(applyThisArray[2]).not.toBe(testContext);
expect(applyArgsArray[0]).toEqual(testArgs);
expect(applyArgsArray[1]).toEqual(testArgs);
expect(applyArgsArray[2]).toEqual([undefined]);
});
it('should have EventEmitter instances', () => {
expect(ngZone.onError instanceof EventEmitter).toBe(true);
expect(ngZone.onStable instanceof EventEmitter).toBe(true);
expect(ngZone.onUnstable instanceof EventEmitter).toBe(true);
expect(ngZone.onMicrotaskEmpty instanceof EventEmitter).toBe(true);
});
});
function commonTests() {
describe('hasPendingMicrotasks', () => {
it('should be false', () => {
expect(_zone.hasPendingMicrotasks).toBe(false);
});
it('should be true', () => {
runNgZoneNoLog(() => {
queueMicrotask(() => {});
});
expect(_zone.hasPendingMicrotasks).toBe(true);
});
});
describe('hasPendingTimers', () => {
it('should be false', () => {
expect(_zone.hasPendingMacrotasks).toBe(false);
});
it('should be true', () => {
runNgZoneNoLog(() => {
setTimeout(() => {}, 0);
});
expect(_zone.hasPendingMacrotasks).toBe(true);
});
});
describe('hasPendingAsyncTasks', () => {
it('should be false', () => {
expect(_zone.hasPendingMicrotasks).toBe(false);
});
it('should be true when microtask is scheduled', () => {
runNgZoneNoLog(() => {
queueMicrotask(() => {});
});
expect(_zone.hasPendingMicrotasks).toBe(true);
});
it('should be true when timer is scheduled', () => {
runNgZoneNoLog(() => {
setTimeout(() => {}, 0);
});
expect(_zone.hasPendingMacrotasks).toBe(true);
});
});
describe('isInInnerZone', () => {
it('should return whether the code executes in the inner zone', () => {
expect(NgZone.isInAngularZone()).toEqual(false);
runNgZoneNoLog(() => {
expect(NgZone.isInAngularZone()).toEqual(true);
});
});
}); | {
"end_byte": 7811,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/zone/ng_zone_spec.ts"
} |
angular/packages/core/test/zone/ng_zone_spec.ts_7815_15846 | describe('run', () => {
it('should return the body return value from run', (done) => {
macroTask(() => {
expect(_zone.run(() => 6)).toEqual(6);
});
macroTask(() => {
done();
});
});
it('should return the body return value from runTask', (done) => {
macroTask(() => {
expect(_zone.runTask(() => 6)).toEqual(6);
});
macroTask(() => {
done();
});
});
it('should call onUnstable and onMicrotaskEmpty', (done) => {
runNgZoneNoLog(() => macroTask(_log.fn('run')));
macroTask(() => {
expect(_log.result()).toEqual('onUnstable; run; onMicrotaskEmpty; onStable');
done();
});
});
it('should call onStable once at the end of event', (done) => {
// The test is set up in a way that causes the zone loop to run onMicrotaskEmpty twice
// then verified that onStable is only called once at the end
runNgZoneNoLog(() => macroTask(_log.fn('run')));
let times = 0;
_zone.onMicrotaskEmpty.subscribe({
next: () => {
times++;
_log.add(`onMicrotaskEmpty ${times}`);
if (times < 2) {
// Scheduling a microtask causes a second digest
runNgZoneNoLog(() => {
queueMicrotask(() => {});
});
}
},
});
macroTask(() => {
expect(_log.result()).toEqual(
'onUnstable; run; onMicrotaskEmpty; onMicrotaskEmpty 1; ' +
'onMicrotaskEmpty; onMicrotaskEmpty 2; onStable',
);
done();
}, resultTimer);
});
it('should call standalone onStable', (done) => {
runNgZoneNoLog(() => macroTask(_log.fn('run')));
macroTask(() => {
expect(_log.result()).toEqual('onUnstable; run; onMicrotaskEmpty; onStable');
done();
}, resultTimer);
});
xit('should run subscriber listeners in the subscription zone (outside)', (done) => {
// Each subscriber fires a microtask outside the Angular zone. The test
// then verifies that those microtasks do not cause additional digests.
let turnStart = false;
_zone.onUnstable.subscribe({
next: () => {
if (turnStart) throw 'Should not call this more than once';
_log.add('onUnstable');
queueMicrotask(() => {});
turnStart = true;
},
});
let turnDone = false;
_zone.onMicrotaskEmpty.subscribe({
next: () => {
if (turnDone) throw 'Should not call this more than once';
_log.add('onMicrotaskEmpty');
queueMicrotask(() => {});
turnDone = true;
},
});
let eventDone = false;
_zone.onStable.subscribe({
next: () => {
if (eventDone) throw 'Should not call this more than once';
_log.add('onStable');
queueMicrotask(() => {});
eventDone = true;
},
});
macroTask(() => {
_zone.run(_log.fn('run'));
});
macroTask(() => {
expect(_log.result()).toEqual('onUnstable; run; onMicrotaskEmpty; onStable');
done();
}, resultTimer);
});
it('should run subscriber listeners in the subscription zone (inside)', (done) => {
runNgZoneNoLog(() => macroTask(_log.fn('run')));
// the only practical use-case to run a callback inside the zone is
// change detection after "onMicrotaskEmpty". That's the only case tested.
let turnDone = false;
_zone.onMicrotaskEmpty.subscribe({
next: () => {
_log.add('onMyMicrotaskEmpty');
if (turnDone) return;
_zone.run(() => {
queueMicrotask(() => {});
});
turnDone = true;
},
});
macroTask(() => {
expect(_log.result()).toEqual(
'onUnstable; run; onMicrotaskEmpty; onMyMicrotaskEmpty; ' +
'onMicrotaskEmpty; onMyMicrotaskEmpty; onStable',
);
done();
}, resultTimer);
});
it('should run async tasks scheduled inside onStable outside Angular zone', (done) => {
runNgZoneNoLog(() => macroTask(_log.fn('run')));
_zone.onStable.subscribe({
next: () => {
NgZone.assertNotInAngularZone();
_log.add('onMyTaskDone');
},
});
macroTask(() => {
expect(_log.result()).toEqual('onUnstable; run; onMicrotaskEmpty; onStable; onMyTaskDone');
done();
});
});
it('should call onUnstable once before a turn and onMicrotaskEmpty once after the turn', (done) => {
runNgZoneNoLog(() => {
macroTask(() => {
_log.add('run start');
queueMicrotask(_log.fn('async'));
_log.add('run end');
});
});
macroTask(() => {
// The microtask (async) is executed after the macrotask (run)
expect(_log.result()).toEqual(
'onUnstable; run start; run end; async; onMicrotaskEmpty; onStable',
);
done();
}, resultTimer);
});
it('should not run onUnstable and onMicrotaskEmpty for nested Zone.run', (done) => {
runNgZoneNoLog(() => {
macroTask(() => {
_log.add('start run');
_zone.run(() => {
_log.add('nested run');
queueMicrotask(_log.fn('nested run microtask'));
});
_log.add('end run');
});
});
macroTask(() => {
expect(_log.result()).toEqual(
'onUnstable; start run; nested run; end run; nested run microtask; onMicrotaskEmpty; onStable',
);
done();
}, resultTimer);
});
it('should not run onUnstable and onMicrotaskEmpty for nested Zone.run invoked from onMicrotaskEmpty', (done) => {
runNgZoneNoLog(() => macroTask(_log.fn('start run')));
_zone.onMicrotaskEmpty.subscribe({
next: () => {
_log.add('onMicrotaskEmpty:started');
_zone.run(() => _log.add('nested run'));
_log.add('onMicrotaskEmpty:finished');
},
});
macroTask(() => {
expect(_log.result()).toEqual(
'onUnstable; start run; onMicrotaskEmpty; onMicrotaskEmpty:started; nested run; onMicrotaskEmpty:finished; onStable',
);
done();
}, resultTimer);
});
it('should call onUnstable and onMicrotaskEmpty before and after each top-level run', (done) => {
runNgZoneNoLog(() => macroTask(_log.fn('run1')));
runNgZoneNoLog(() => macroTask(_log.fn('run2')));
macroTask(() => {
expect(_log.result()).toEqual(
'onUnstable; run1; onMicrotaskEmpty; onStable; onUnstable; run2; onMicrotaskEmpty; onStable',
);
done();
}, resultTimer);
});
it('should call onUnstable and onMicrotaskEmpty before and after each turn', (done) => {
let aResolve: (result: string) => void;
let aPromise: Promise<string>;
let bResolve: (result: string) => void;
let bPromise: Promise<string>;
runNgZoneNoLog(() => {
macroTask(() => {
aPromise = new Promise((res) => {
aResolve = res;
});
bPromise = new Promise((res) => {
bResolve = res;
});
_log.add('run start');
aPromise.then(_log.fn('a then'));
bPromise.then(_log.fn('b then'));
});
});
runNgZoneNoLog(() => {
macroTask(() => {
aResolve('a');
bResolve('b');
});
});
macroTask(() => {
expect(_log.result()).toEqual(
'onUnstable; run start; onMicrotaskEmpty; onStable; onUnstable; a then; b then; onMicrotaskEmpty; onStable',
);
done();
}, resultTimer);
});
it('should run a function outside of the angular zone', (done) => {
macroTask(() => {
_zone.runOutsideAngular(_log.fn('run'));
});
macroTask(() => {
expect(_log.result()).toEqual('run');
done();
});
}); | {
"end_byte": 15846,
"start_byte": 7815,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/zone/ng_zone_spec.ts"
} |
angular/packages/core/test/zone/ng_zone_spec.ts_15852_23970 | it('should call onUnstable and onMicrotaskEmpty when an inner microtask is scheduled from outside angular', (done) => {
let resolve: (result: string | null) => void;
let promise: Promise<string | null>;
macroTask(() => {
NgZone.assertNotInAngularZone();
promise = new Promise<string | null>((res) => {
resolve = res;
});
});
runNgZoneNoLog(() => {
macroTask(() => {
NgZone.assertInAngularZone();
promise.then(_log.fn('executedMicrotask'));
});
});
macroTask(() => {
NgZone.assertNotInAngularZone();
_log.add('scheduling a microtask');
resolve(null);
});
macroTask(() => {
expect(_log.result()).toEqual(
// First VM turn => setup Promise then
'onUnstable; onMicrotaskEmpty; onStable; ' +
// Second VM turn (outside of angular)
'scheduling a microtask; onUnstable; ' +
// Third VM Turn => execute the microtask (inside angular)
// No onUnstable; because we don't own the task which started the turn.
'executedMicrotask; onMicrotaskEmpty; onStable',
);
done();
}, resultTimer);
});
it(
'should call onUnstable only before executing a microtask scheduled in onMicrotaskEmpty ' +
'and not onMicrotaskEmpty after executing the task',
(done) => {
runNgZoneNoLog(() => macroTask(_log.fn('run')));
let ran = false;
_zone.onMicrotaskEmpty.subscribe({
next: () => {
_log.add('onMicrotaskEmpty(begin)');
if (!ran) {
_zone.run(() => {
queueMicrotask(() => {
ran = true;
_log.add('executedMicrotask');
});
});
}
_log.add('onMicrotaskEmpty(end)');
},
});
macroTask(() => {
expect(_log.result()).toEqual(
// First VM turn => 'run' macrotask
'onUnstable; run; onMicrotaskEmpty; onMicrotaskEmpty(begin); onMicrotaskEmpty(end); ' +
// Second microtaskDrain Turn => microtask enqueued from onMicrotaskEmpty
'executedMicrotask; onMicrotaskEmpty; onMicrotaskEmpty(begin); onMicrotaskEmpty(end); onStable',
);
done();
}, resultTimer);
},
);
it(
'should call onUnstable and onMicrotaskEmpty for a queueMicrotask in onMicrotaskEmpty triggered by ' +
'a queueMicrotask in run',
(done) => {
runNgZoneNoLog(() => {
macroTask(() => {
_log.add('queueMicrotask');
queueMicrotask(_log.fn('run(executeMicrotask)'));
});
});
let ran = false;
_zone.onMicrotaskEmpty.subscribe({
next: () => {
_log.add('onMicrotaskEmpty(begin)');
if (!ran) {
_log.add('onMicrotaskEmpty(queueMicrotask)');
_zone.run(() => {
queueMicrotask(() => {
ran = true;
_log.add('onMicrotaskEmpty(executeMicrotask)');
});
});
}
_log.add('onMicrotaskEmpty(end)');
},
});
macroTask(() => {
expect(_log.result()).toEqual(
// First VM Turn => a macrotask + the microtask it enqueues
'onUnstable; queueMicrotask; run(executeMicrotask); onMicrotaskEmpty; onMicrotaskEmpty(begin); onMicrotaskEmpty(queueMicrotask); onMicrotaskEmpty(end); ' +
// Second VM Turn => the microtask enqueued from onMicrotaskEmpty
'onMicrotaskEmpty(executeMicrotask); onMicrotaskEmpty; onMicrotaskEmpty(begin); onMicrotaskEmpty(end); onStable',
);
done();
}, resultTimer);
},
);
it('should execute promises scheduled in onUnstable before promises scheduled in run', (done) => {
runNgZoneNoLog(() => {
macroTask(() => {
_log.add('run start');
resolvedPromise
.then((_) => {
_log.add('promise then');
resolvedPromise.then(_log.fn('promise foo'));
return Promise.resolve(null);
})
.then(_log.fn('promise bar'));
_log.add('run end');
});
});
let donePromiseRan = false;
let startPromiseRan = false;
_zone.onUnstable.subscribe({
next: () => {
_log.add('onUnstable(begin)');
if (!startPromiseRan) {
_log.add('onUnstable(schedulePromise)');
_zone.run(() => {
queueMicrotask(_log.fn('onUnstable(executePromise)'));
});
startPromiseRan = true;
}
_log.add('onUnstable(end)');
},
});
_zone.onMicrotaskEmpty.subscribe({
next: () => {
_log.add('onMicrotaskEmpty(begin)');
if (!donePromiseRan) {
_log.add('onMicrotaskEmpty(schedulePromise)');
_zone.run(() => {
queueMicrotask(_log.fn('onMicrotaskEmpty(executePromise)'));
});
donePromiseRan = true;
}
_log.add('onMicrotaskEmpty(end)');
},
});
macroTask(() => {
expect(_log.result()).toEqual(
// First VM turn: enqueue a microtask in onUnstable
'onUnstable; onUnstable(begin); onUnstable(schedulePromise); onUnstable(end); ' +
// First VM turn: execute the macrotask which enqueues microtasks
'run start; run end; ' +
// First VM turn: execute enqueued microtasks
'onUnstable(executePromise); promise then; promise foo; promise bar; onMicrotaskEmpty; ' +
// First VM turn: onTurnEnd, enqueue a microtask
'onMicrotaskEmpty(begin); onMicrotaskEmpty(schedulePromise); onMicrotaskEmpty(end); ' +
// Second VM turn: execute the microtask from onTurnEnd
'onMicrotaskEmpty(executePromise); onMicrotaskEmpty; onMicrotaskEmpty(begin); onMicrotaskEmpty(end); onStable',
);
done();
}, resultTimer);
});
it('should call onUnstable and onMicrotaskEmpty before and after each turn, respectively', (done) => {
let aResolve: (result: string | null) => void;
let aPromise: Promise<string | null>;
let bResolve: (result: string | null) => void;
let bPromise: Promise<string | null>;
runNgZoneNoLog(() => {
macroTask(() => {
aPromise = new Promise<string | null>((res) => {
aResolve = res;
});
bPromise = new Promise<string | null>((res) => {
bResolve = res;
});
aPromise.then(_log.fn('a then'));
bPromise.then(_log.fn('b then'));
_log.add('run start');
});
});
runNgZoneNoLog(() => {
macroTask(() => {
aResolve(null);
}, 10);
});
runNgZoneNoLog(() => {
macroTask(() => {
bResolve(null);
}, 20);
});
macroTask(() => {
expect(_log.result()).toEqual(
// First VM turn
'onUnstable; run start; onMicrotaskEmpty; onStable; ' +
// Second VM turn
'onUnstable; a then; onMicrotaskEmpty; onStable; ' +
// Third VM turn
'onUnstable; b then; onMicrotaskEmpty; onStable',
);
done();
}, resultTimer);
});
it('should call onUnstable and onMicrotaskEmpty before and after (respectively) all turns in a chain', (done) => {
runNgZoneNoLog(() => {
macroTask(() => {
_log.add('run start');
queueMicrotask(() => {
_log.add('async1');
queueMicrotask(_log.fn('async2'));
});
_log.add('run end');
});
});
macroTask(() => {
expect(_log.result()).toEqual(
'onUnstable; run start; run end; async1; async2; onMicrotaskEmpty; onStable',
);
done();
}, resultTimer);
}); | {
"end_byte": 23970,
"start_byte": 15852,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/zone/ng_zone_spec.ts"
} |
angular/packages/core/test/zone/ng_zone_spec.ts_23976_27973 | it('should call onUnstable and onMicrotaskEmpty for promises created outside of run body', (done) => {
let promise: Promise<any>;
runNgZoneNoLog(() => {
macroTask(() => {
_zone.runOutsideAngular(() => {
promise = Promise.resolve(4).then((x) => Promise.resolve(x));
});
promise.then(_log.fn('promise then'));
_log.add('zone run');
});
});
macroTask(() => {
expect(_log.result()).toEqual(
'onUnstable; zone run; onMicrotaskEmpty; onStable; ' +
'onUnstable; promise then; onMicrotaskEmpty; onStable',
);
done();
}, resultTimer);
});
});
describe('exceptions', () => {
it('should call the on error callback when it is invoked via zone.runGuarded', (done) => {
macroTask(() => {
const exception = new Error('sync');
_zone.runGuarded(() => {
throw exception;
});
expect(_errors.length).toBe(1);
expect(_errors[0]).toBe(exception);
done();
});
});
it('should not call the on error callback but rethrow when it is invoked via zone.run', (done) => {
macroTask(() => {
const exception = new Error('sync');
expect(() =>
_zone.run(() => {
throw exception;
}),
).toThrowError('sync');
expect(_errors.length).toBe(0);
done();
});
});
it('should call onError for errors from microtasks', (done) => {
const exception = new Error('async');
macroTask(() => {
_zone.run(() => {
queueMicrotask(() => {
throw exception;
});
});
});
macroTask(() => {
expect(_errors.length).toBe(1);
expect(_errors[0]).toEqual(exception);
done();
}, resultTimer);
});
});
describe('bugs', () => {
describe('#10503', () => {
let ngZone: NgZone;
beforeEach(inject([NgZone], (_ngZone: NgZone) => {
// Create a zone outside the fakeAsync.
ngZone = _ngZone;
}));
it('should fakeAsync even if the NgZone was created outside.', fakeAsync(() => {
let result: string = null!;
// try to escape the current fakeAsync zone by using NgZone which was created outside.
ngZone.run(() => {
Promise.resolve('works').then((v) => (result = v));
flushMicrotasks();
});
expect(result).toEqual('works');
}));
describe('async', () => {
let asyncResult: string;
const waitLongerThenTestFrameworkAsyncTimeout = 5;
beforeEach(() => {
asyncResult = null!;
});
it('should async even if the NgZone was created outside.', waitForAsync(() => {
// try to escape the current async zone by using NgZone which was created outside.
ngZone.run(() => {
setTimeout(() => {
Promise.resolve('works').then((v) => (asyncResult = v));
}, waitLongerThenTestFrameworkAsyncTimeout);
});
}));
afterEach(() => {
expect(asyncResult).toEqual('works');
});
});
});
it('coalescing can work with fakeAsync', fakeAsync(() => {
if (!isBrowser) {
return;
}
@Component({
standalone: true,
template: `
<div class="clickable" (click)="clicked = true"></div>
{{clicked ? 'clicked' : '' }}
`,
})
class OuterComponent {}
TestBed.configureTestingModule({
providers: [
provideZoneChangeDetection({eventCoalescing: true, scheduleInRootZone: false} as any),
],
});
const fixture = TestBed.createComponent(OuterComponent);
fixture.autoDetectChanges();
document.querySelector('.clickable')!.dispatchEvent(new MouseEvent('click'));
flush();
expect(fixture.nativeElement.innerText).toContain('clicked');
}));
}); | {
"end_byte": 27973,
"start_byte": 23976,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/zone/ng_zone_spec.ts"
} |
angular/packages/core/test/zone/ng_zone_spec.ts_27977_37450 | describe('coalescing', () => {
it('should execute callback when a view transition is waiting for the callback to complete', async () => {
if (!(document as any).startViewTransition) {
return;
}
const startTime = performance.now();
// When there is a pending view transition, `requestAnimationFrame` is blocked
// because the browser is waiting to take a screenshot. This test ensures that
// the scheduler does not block completion of the transition for too long.
// This test would fail if the scheduling function _only_ used `rAF`
// but works if there is another mechanism as well (i.e. race with setTimeout).
// https://github.com/angular/angular/issues/54544
const transition = (document as any).startViewTransition(() => {
return new Promise<void>((resolve) => {
scheduler(() => {
resolve();
});
});
});
await transition.finished;
expect(performance.now() - startTime).toBeLessThan(1000);
});
describe('shouldCoalesceRunChangeDetection = false, shouldCoalesceEventChangeDetection = false', () => {
let notCoalesceZone: NgZone;
let logs: string[] = [];
beforeEach(() => {
notCoalesceZone = new NgZone({});
logs = [];
notCoalesceZone.onMicrotaskEmpty.subscribe(() => {
logs.push('microTask empty');
});
});
it('should run sync', () => {
notCoalesceZone.run(() => {});
expect(logs).toEqual(['microTask empty']);
});
it('should emit onMicroTaskEmpty multiple times within the same event loop for multiple ngZone.run', () => {
notCoalesceZone.run(() => {});
notCoalesceZone.run(() => {});
expect(logs).toEqual(['microTask empty', 'microTask empty']);
});
it('should emit onMicroTaskEmpty multiple times within the same event loop for multiple tasks', () => {
const tasks: Task[] = [];
notCoalesceZone.run(() => {
tasks.push(
Zone.current.scheduleEventTask(
'myEvent',
() => {
logs.push('eventTask1');
},
undefined,
() => {},
),
);
tasks.push(
Zone.current.scheduleEventTask(
'myEvent',
() => {
logs.push('eventTask2');
},
undefined,
() => {},
),
);
tasks.push(
Zone.current.scheduleMacroTask(
'myMacro',
() => {
logs.push('macroTask');
},
undefined,
() => {},
),
);
});
tasks.forEach((t) => t.invoke());
expect(logs).toEqual([
'microTask empty',
'eventTask1',
'microTask empty',
'eventTask2',
'microTask empty',
'macroTask',
'microTask empty',
]);
});
});
describe('shouldCoalesceEventChangeDetection = true, shouldCoalesceRunChangeDetection = false', () => {
let nativeSetTimeout: any = global[Zone.__symbol__('setTimeout')];
let patchedImmediate: any;
let coalesceZone: NgZone;
let logs: string[] = [];
beforeEach(() => {
patchedImmediate = global.setImmediate;
global.setImmediate = global[Zone.__symbol__('setImmediate')];
coalesceZone = new NgZone({shouldCoalesceEventChangeDetection: true});
logs = [];
coalesceZone.onMicrotaskEmpty.subscribe(() => {
logs.push('microTask empty');
});
});
afterEach(() => {
global.setImmediate = patchedImmediate;
});
it('should run in requestAnimationFrame async', (done) => {
let task: Task | undefined = undefined;
coalesceZone.run(() => {
task = Zone.current.scheduleEventTask(
'myEvent',
() => {
logs.push('myEvent');
},
undefined,
() => {},
);
});
task!.invoke();
expect(logs).toEqual(['microTask empty', 'myEvent']);
scheduler(() => {
expect(logs).toEqual(['microTask empty', 'myEvent', 'microTask empty']);
done();
});
});
it('should only emit onMicroTaskEmpty once within the same event loop for multiple event tasks', (done) => {
const tasks: Task[] = [];
coalesceZone.run(() => {
tasks.push(
Zone.current.scheduleEventTask(
'myEvent',
() => {
logs.push('eventTask1');
},
undefined,
() => {},
),
);
tasks.push(
Zone.current.scheduleEventTask(
'myEvent',
() => {
logs.push('eventTask2');
},
undefined,
() => {},
),
);
});
tasks.forEach((t) => t.invoke());
expect(logs).toEqual(['microTask empty', 'eventTask1', 'eventTask2']);
scheduler(() => {
expect(logs).toEqual(['microTask empty', 'eventTask1', 'eventTask2', 'microTask empty']);
done();
});
});
it('should only emit onMicroTaskEmpty once within the same event loop for ngZone.run in onMicrotaskEmpty subscription', (done) => {
const tasks: Task[] = [];
coalesceZone.onMicrotaskEmpty.subscribe(() => {
coalesceZone.run(() => {});
});
coalesceZone.run(() => {
tasks.push(
Zone.current.scheduleEventTask(
'myEvent',
() => {
logs.push('eventTask1');
},
undefined,
() => {},
),
);
});
coalesceZone.run(() => {
tasks.push(
Zone.current.scheduleEventTask(
'myEvent',
() => {
logs.push('eventTask2');
},
undefined,
() => {},
),
);
});
tasks.forEach((t) => t.invoke());
expect(logs).toEqual(['microTask empty', 'microTask empty', 'eventTask1', 'eventTask2']);
nativeSetTimeout(() => {
expect(logs).toEqual([
'microTask empty',
'microTask empty',
'eventTask1',
'eventTask2',
'microTask empty',
]);
done();
}, 100);
});
it('should emit onMicroTaskEmpty once within the same event loop for not only event tasks, but event tasks are before other tasks', (done) => {
const tasks: Task[] = [];
coalesceZone.run(() => {
tasks.push(
Zone.current.scheduleEventTask(
'myEvent',
() => {
logs.push('eventTask1');
},
undefined,
() => {},
),
);
tasks.push(
Zone.current.scheduleEventTask(
'myEvent',
() => {
logs.push('eventTask2');
},
undefined,
() => {},
),
);
tasks.push(
Zone.current.scheduleMacroTask(
'myMacro',
() => {
logs.push('macroTask');
},
undefined,
() => {},
),
);
});
tasks.forEach((t) => t.invoke());
expect(logs).toEqual(['microTask empty', 'eventTask1', 'eventTask2', 'macroTask']);
scheduler(() => {
expect(logs).toEqual([
'microTask empty',
'eventTask1',
'eventTask2',
'macroTask',
'microTask empty',
]);
done();
});
});
it('should emit multiple onMicroTaskEmpty within the same event loop for not only event tasks, but event tasks are after other tasks', (done) => {
const tasks: Task[] = [];
coalesceZone.run(() => {
tasks.push(
Zone.current.scheduleMacroTask(
'myMacro',
() => {
logs.push('macroTask');
},
undefined,
() => {},
),
);
tasks.push(
Zone.current.scheduleEventTask(
'myEvent',
() => {
logs.push('eventTask1');
},
undefined,
() => {},
),
);
tasks.push(
Zone.current.scheduleEventTask(
'myEvent',
() => {
logs.push('eventTask2');
},
undefined,
() => {},
),
);
});
tasks.forEach((t) => t.invoke());
expect(logs).toEqual([
'microTask empty',
'macroTask',
'microTask empty',
'eventTask1',
'eventTask2',
]);
scheduler(() => {
expect(logs).toEqual([
'microTask empty',
'macroTask',
'microTask empty',
'eventTask1',
'eventTask2',
'microTask empty',
]);
done();
});
});
}); | {
"end_byte": 37450,
"start_byte": 27977,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/zone/ng_zone_spec.ts"
} |
angular/packages/core/test/zone/ng_zone_spec.ts_37456_41193 | describe('shouldCoalesceRunChangeDetection = true', () => {
let nativeSetTimeout: any = global[Zone.__symbol__('setTimeout')];
let patchedImmediate: any;
let coalesceZone: NgZone;
let logs: string[] = [];
beforeEach(() => {
patchedImmediate = global.setImmediate;
global.setImmediate = global[Zone.__symbol__('setImmediate')];
coalesceZone = new NgZone({shouldCoalesceRunChangeDetection: true});
logs = [];
coalesceZone.onMicrotaskEmpty.subscribe(() => {
logs.push('microTask empty');
});
});
afterEach(() => {
global.setImmediate = patchedImmediate;
});
it('should run in requestAnimationFrame async', (done) => {
coalesceZone.run(() => {});
expect(logs).toEqual([]);
scheduler(() => {
expect(logs).toEqual(['microTask empty']);
done();
});
});
it('should only emit onMicroTaskEmpty once within the same event loop for multiple ngZone.run', (done) => {
coalesceZone.run(() => {});
coalesceZone.run(() => {});
expect(logs).toEqual([]);
scheduler(() => {
expect(logs).toEqual(['microTask empty']);
done();
});
});
it('should only emit onMicroTaskEmpty once within the same event loop for ngZone.run in onMicrotaskEmpty subscription', (done) => {
coalesceZone.onMicrotaskEmpty.subscribe(() => {
coalesceZone.run(() => {});
});
coalesceZone.run(() => {});
coalesceZone.run(() => {});
expect(logs).toEqual([]);
nativeSetTimeout(() => {
expect(logs).toEqual(['microTask empty']);
done();
}, 100);
});
it('should only emit onMicroTaskEmpty once within the same event loop for multiple tasks', (done) => {
const tasks: Task[] = [];
coalesceZone.run(() => {
tasks.push(
Zone.current.scheduleMacroTask(
'myMacro',
() => {
logs.push('macroTask');
},
undefined,
() => {},
),
);
tasks.push(
Zone.current.scheduleEventTask(
'myEvent',
() => {
logs.push('eventTask1');
},
undefined,
() => {},
),
);
tasks.push(
Zone.current.scheduleEventTask(
'myEvent',
() => {
logs.push('eventTask2');
},
undefined,
() => {},
),
);
tasks.push(
Zone.current.scheduleMacroTask(
'myMacro',
() => {
logs.push('macroTask');
},
undefined,
() => {},
),
);
});
tasks.forEach((t) => t.invoke());
expect(logs).toEqual(['macroTask', 'eventTask1', 'eventTask2', 'macroTask']);
scheduler(() => {
expect(logs).toEqual([
'macroTask',
'eventTask1',
'eventTask2',
'macroTask',
'microTask empty',
]);
done();
});
});
it('does not throw when apply args array has `undefined`', async () => {
expect(() => {
coalesceZone.run(function (this: any, arg: any) {}, undefined, [undefined]);
}).not.toThrow();
// wait for the zone to stabilize after the task above. Needed to prevent this from leaking
// into a follow-up test
await firstValueFrom(coalesceZone.onMicrotaskEmpty);
});
});
});
} | {
"end_byte": 41193,
"start_byte": 37456,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/zone/ng_zone_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_0_1259 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
animate,
animateChild,
animation,
AnimationEvent,
AnimationMetadata,
AnimationOptions,
AUTO_STYLE,
group,
keyframes,
query,
sequence,
state,
style,
transition,
trigger,
useAnimation,
ɵPRE_STYLE as PRE_STYLE,
} from '@angular/animations';
import {AnimationDriver, NoopAnimationDriver, ɵAnimationEngine} from '@angular/animations/browser';
import {MockAnimationDriver, MockAnimationPlayer} from '@angular/animations/browser/testing';
import {
ChangeDetectorRef,
Component,
HostBinding,
HostListener,
Inject,
RendererFactory2,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import {fakeAsync, flushMicrotasks, TestBed} from '@angular/core/testing';
import {ɵDomRendererFactory2} from '@angular/platform-browser';
import {
ANIMATION_MODULE_TYPE,
BrowserAnimationsModule,
NoopAnimationsModule,
} from '@angular/platform-browser/animations';
import {hasStyle} from '@angular/platform-browser/testing/src/browser_util';
const DEFAULT_NAMESPACE_ID = 'id';
const DEFAULT_COMPONENT_ID = '1';
( | {
"end_byte": 1259,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_1261_10844 | nction () {
// these tests are only meant to be run within the DOM (for now)
if (isNode) return;
describe('animation tests', function () {
function getLog(): MockAnimationPlayer[] {
return MockAnimationDriver.log as MockAnimationPlayer[];
}
function resetLog() {
MockAnimationDriver.log = [];
}
beforeEach(() => {
resetLog();
TestBed.configureTestingModule({
providers: [{provide: AnimationDriver, useClass: MockAnimationDriver}],
imports: [BrowserAnimationsModule],
});
});
describe('animation modules', function () {
it('should hint at BrowserAnimationsModule being used', () => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
declarations: [SharedAnimationCmp],
imports: [BrowserAnimationsModule],
});
const fixture = TestBed.createComponent(SharedAnimationCmp);
expect(fixture.componentInstance.animationType).toEqual('BrowserAnimations');
});
it('should hint at NoopAnimationsModule being used', () => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
declarations: [SharedAnimationCmp],
imports: [NoopAnimationsModule],
});
const fixture = TestBed.createComponent(SharedAnimationCmp);
expect(fixture.componentInstance.animationType).toEqual('NoopAnimations');
});
it('should hint at NoopAnimationsModule being used when BrowserAnimationsModule is provided with disabled animations', () => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
declarations: [SharedAnimationCmp],
imports: [BrowserAnimationsModule.withConfig({disableAnimations: true})],
});
const fixture = TestBed.createComponent(SharedAnimationCmp);
expect(fixture.componentInstance.animationType).toEqual('NoopAnimations');
});
});
@Component({
template: '<p>template text</p>',
standalone: false,
})
class SharedAnimationCmp {
constructor(
@Inject(ANIMATION_MODULE_TYPE) public animationType: 'NoopAnimations' | 'BrowserAnimations',
) {}
}
describe('fakeAsync testing', () => {
it('should only require one flushMicrotasks call to kick off animation callbacks', fakeAsync(() => {
@Component({
selector: 'cmp',
template: `
<div [@myAnimation]="exp" (@myAnimation.start)="cb('start')" (@myAnimation.done)="cb('done')"></div>
`,
animations: [
trigger('myAnimation', [
transition('* => on, * => off', [animate(1000, style({opacity: 1}))]),
]),
],
standalone: false,
})
class Cmp {
exp: any = false;
status: string = '';
cb(status: string) {
this.status = status;
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'on';
fixture.detectChanges();
expect(cmp.status).toEqual('');
flushMicrotasks();
expect(cmp.status).toEqual('start');
let player = MockAnimationDriver.log.pop()!;
player.finish();
expect(cmp.status).toEqual('done');
cmp.status = '';
cmp.exp = 'off';
fixture.detectChanges();
expect(cmp.status).toEqual('');
player = MockAnimationDriver.log.pop()!;
player.finish();
expect(cmp.status).toEqual('');
flushMicrotasks();
expect(cmp.status).toEqual('done');
}));
it('should always run .start callbacks before .done callbacks even for noop animations', fakeAsync(() => {
@Component({
selector: 'cmp',
template: `
<div [@myAnimation]="exp" (@myAnimation.start)="cb('start')" (@myAnimation.done)="cb('done')"></div>
`,
animations: [trigger('myAnimation', [transition('* => go', [])])],
standalone: false,
})
class Cmp {
exp: any = false;
log: string[] = [];
cb(status: string) {
this.log.push(status);
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'go';
fixture.detectChanges();
expect(cmp.log).toEqual([]);
flushMicrotasks();
expect(cmp.log).toEqual(['start', 'done']);
}));
it('should emit the correct totalTime value for a noop-animation', fakeAsync(() => {
@Component({
selector: 'cmp',
template: `
<div [@myAnimation]="exp" (@myAnimation.start)="cb($event)" (@myAnimation.done)="cb($event)"></div>
`,
animations: [
trigger('myAnimation', [transition('* => go', [animate('1s', style({opacity: 0}))])]),
],
standalone: false,
})
class Cmp {
exp: any = false;
log: AnimationEvent[] = [];
cb(event: AnimationEvent) {
this.log.push(event);
}
}
TestBed.configureTestingModule({
declarations: [Cmp],
providers: [{provide: AnimationDriver, useClass: NoopAnimationDriver}],
});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'go';
fixture.detectChanges();
expect(cmp.log).toEqual([]);
flushMicrotasks();
expect(cmp.log.length).toEqual(2);
const [start, end] = cmp.log;
expect(start.totalTime).toEqual(1000);
expect(end.totalTime).toEqual(1000);
}));
});
describe('component fixture integration', () => {
describe('whenRenderingDone', () => {
it('should wait until the animations are finished until continuing', fakeAsync(() => {
@Component({
selector: 'cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [transition('* => on', [animate(1000, style({opacity: 1}))])]),
],
standalone: false,
})
class Cmp {
exp: any = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
let isDone = false;
fixture.whenRenderingDone().then(() => (isDone = true));
expect(isDone).toBe(false);
cmp.exp = 'on';
fixture.detectChanges();
engine.flush();
expect(isDone).toBe(false);
const players = engine.players;
expect(players.length).toEqual(1);
players[0].finish();
expect(isDone).toBe(false);
flushMicrotasks();
expect(isDone).toBe(true);
}));
it('should wait for a noop animation to finish before continuing', fakeAsync(() => {
@Component({
selector: 'cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [transition('* => on', [animate(1000, style({opacity: 1}))])]),
],
standalone: false,
})
class Cmp {
exp: any = false;
}
TestBed.configureTestingModule({
providers: [{provide: AnimationDriver, useClass: NoopAnimationDriver}],
declarations: [Cmp],
});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
let isDone = false;
fixture.whenRenderingDone().then(() => (isDone = true));
expect(isDone).toBe(false);
cmp.exp = 'off';
fixture.detectChanges();
engine.flush();
expect(isDone).toBe(false);
flushMicrotasks();
expect(isDone).toBe(true);
}));
it('should wait for active animations to finish even if they have already started', fakeAsync(() => {
@Component({
selector: 'cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [transition('* => on', [animate(1000, style({opacity: 1}))])]),
],
standalone: false,
})
class Cmp {
exp: any = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'on';
fixture.detectChanges();
engine.flush();
const players = engine.players;
expect(players.length).toEqual(1);
let isDone = false;
fixture.whenRenderingDone().then(() => (isDone = true));
flushMicrotasks();
expect(isDone).toBe(false);
players[0].finish();
flushMicrotasks();
expect(isDone).toBe(true);
}));
});
});
| {
"end_byte": 10844,
"start_byte": 1261,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_10850_19918 | be('animation triggers', () => {
it('should trigger a state change animation from void => state', () => {
@Component({
selector: 'if-cmp',
template: `
<div *ngIf="exp" [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition('void => *', [
style({'opacity': '0'}),
animate(500, style({'opacity': '1'})),
]),
]),
],
standalone: false,
})
class Cmp {
exp: any = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
engine.flush();
expect(getLog().length).toEqual(1);
expect(getLog().pop()!.keyframes).toEqual([
new Map<string, string | number>([
['offset', 0],
['opacity', '0'],
]),
new Map<string, string | number>([
['offset', 1],
['opacity', '1'],
]),
]);
});
// https://github.com/angular/angular/issues/32794
it('should support nested animation triggers', () => {
const REUSABLE_ANIMATION = [
trigger('myAnimation', [
transition('void => *', [
style({'opacity': '0'}),
animate(500, style({'opacity': '1'})),
]),
]),
];
@Component({
selector: 'if-cmp',
template: `
<div @myAnimation></div>
`,
animations: [REUSABLE_ANIMATION],
standalone: false,
})
class Cmp {}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
engine.flush();
expect(getLog().length).toEqual(1);
expect(getLog().pop()!.keyframes).toEqual([
new Map<string, string | number>([
['offset', 0],
['opacity', '0'],
]),
new Map<string, string | number>([
['offset', 1],
['opacity', '1'],
]),
]);
});
it('should allow a transition to use a function to determine what method to run', () => {
let valueToMatch = '';
let capturedElement: any;
const transitionFn = (fromState: string, toState: string, element: any) => {
capturedElement = element;
return toState == valueToMatch;
};
@Component({
selector: 'if-cmp',
template: '<div #element [@myAnimation]="exp"></div>',
animations: [
trigger('myAnimation', [
transition(transitionFn, [style({opacity: 0}), animate(1234, style({opacity: 1}))]),
]),
],
standalone: false,
})
class Cmp {
@ViewChild('element') element: any;
exp: any = '';
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
valueToMatch = cmp.exp = 'something';
fixture.detectChanges();
const element = cmp.element.nativeElement;
let players = getLog();
expect(players.length).toEqual(1);
let [p1] = players;
expect(p1.totalTime).toEqual(1234);
expect(capturedElement).toEqual(element);
resetLog();
valueToMatch = 'something-else';
cmp.exp = 'this-wont-match';
fixture.detectChanges();
players = getLog();
expect(players.length).toEqual(0);
});
it('should allow a transition to use a function to determine what method to run and expose any parameter values', () => {
const transitionFn = (
fromState: string,
toState: string,
element?: any,
params?: {[key: string]: any},
) => {
return params!['doMatch'] == true;
};
@Component({
selector: 'if-cmp',
template: '<div [@myAnimation]="{value:exp, params: {doMatch:doMatch}}"></div>',
animations: [
trigger('myAnimation', [
transition(transitionFn, [style({opacity: 0}), animate(3333, style({opacity: 1}))]),
]),
],
standalone: false,
})
class Cmp {
doMatch = false;
exp: any = '';
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.doMatch = true;
fixture.detectChanges();
let players = getLog();
expect(players.length).toEqual(1);
let [p1] = players;
expect(p1.totalTime).toEqual(3333);
resetLog();
cmp.doMatch = false;
cmp.exp = 'this-wont-match';
fixture.detectChanges();
players = getLog();
expect(players.length).toEqual(0);
});
it('should allow a state value to be `0`', () => {
@Component({
selector: 'if-cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition('0 => 1', [
style({height: '0px'}),
animate(1234, style({height: '100px'})),
]),
transition('* => 1', [style({width: '0px'}), animate(4567, style({width: '100px'}))]),
]),
],
standalone: false,
})
class Cmp {
exp: any = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 0;
fixture.detectChanges();
engine.flush();
resetLog();
cmp.exp = 1;
fixture.detectChanges();
engine.flush();
expect(getLog().length).toEqual(1);
const player = getLog().pop()!;
expect(player.duration).toEqual(1234);
});
it('should always cancel the previous transition if a follow-up transition is not matched', fakeAsync(() => {
@Component({
selector: 'if-cmp',
template: `
<div [@myAnimation]="exp" (@myAnimation.start)="callback($event)" (@myAnimation.done)="callback($event)"></div>
`,
animations: [
trigger('myAnimation', [
transition('a => b', [
style({'opacity': '0'}),
animate(500, style({'opacity': '1'})),
]),
]),
],
standalone: false,
})
class Cmp {
exp: any;
startEvent: any;
doneEvent: any;
callback(event: any) {
if (event.phaseName == 'done') {
this.doneEvent = event;
} else {
this.startEvent = event;
}
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'a';
fixture.detectChanges();
engine.flush();
expect(getLog().length).toEqual(0);
expect(engine.players.length).toEqual(0);
flushMicrotasks();
expect(cmp.startEvent.toState).toEqual('a');
expect(cmp.startEvent.totalTime).toEqual(0);
expect(cmp.startEvent.toState).toEqual('a');
expect(cmp.startEvent.totalTime).toEqual(0);
resetLog();
cmp.exp = 'b';
fixture.detectChanges();
engine.flush();
const players = getLog();
expect(players.length).toEqual(1);
expect(engine.players.length).toEqual(1);
flushMicrotasks();
expect(cmp.startEvent.toState).toEqual('b');
expect(cmp.startEvent.totalTime).toEqual(500);
expect(cmp.startEvent.toState).toEqual('b');
expect(cmp.startEvent.totalTime).toEqual(500);
resetLog();
let completed = false;
players[0].onDone(() => (completed = true));
cmp.exp = 'c';
fixture.detectChanges();
engine.flush();
expect(engine.players.length).toEqual(0);
expect(getLog().length).toEqual(0);
flushMicrotasks();
expect(cmp.startEvent.toState).toEqual('c');
expect(cmp.startEvent.totalTime).toEqual(0);
expect(cmp.startEvent.toState).toEqual('c');
expect(cmp.startEvent.totalTime).toEqual(0);
expect(completed).toBe(true);
}));
it | {
"end_byte": 19918,
"start_byte": 10850,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_19926_29006 | always fire inner callbacks even if no animation is fired when a view is inserted', fakeAsync(() => {
@Component({
selector: 'if-cmp',
template: `
<div *ngIf="exp">
<div @myAnimation (@myAnimation.start)="track($event)" (@myAnimation.done)="track($event)"></div>
</div>
`,
animations: [trigger('myAnimation', [])],
standalone: false,
})
class Cmp {
exp: any = false;
log: string[] = [];
track(event: any) {
this.log.push(`${event.triggerName}-${event.phaseName}`);
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
flushMicrotasks();
expect(cmp.log).toEqual([]);
cmp.exp = true;
fixture.detectChanges();
flushMicrotasks();
expect(cmp.log).toEqual(['myAnimation-start', 'myAnimation-done']);
}));
it('should only turn a view removal as into `void` state transition', () => {
@Component({
selector: 'if-cmp',
template: `
<div *ngIf="exp1" [@myAnimation]="exp2"></div>
`,
animations: [
trigger('myAnimation', [
transition('void <=> *', [
style({width: '0px'}),
animate(1000, style({width: '100px'})),
]),
transition('* => *', [
style({height: '0px'}),
animate(1000, style({height: '100px'})),
]),
]),
],
standalone: false,
})
class Cmp {
exp1: any = false;
exp2: any = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
function resetState() {
cmp.exp2 = 'something';
fixture.detectChanges();
engine.flush();
resetLog();
}
cmp.exp1 = true;
cmp.exp2 = null;
fixture.detectChanges();
engine.flush();
expect(getLog().pop()!.keyframes).toEqual([
new Map<string, string | number>([
['offset', 0],
['width', '0px'],
]),
new Map<string, string | number>([
['offset', 1],
['width', '100px'],
]),
]);
resetState();
cmp.exp2 = false;
fixture.detectChanges();
engine.flush();
expect(getLog().pop()!.keyframes).toEqual([
new Map<string, string | number>([
['offset', 0],
['height', '0px'],
]),
new Map<string, string | number>([
['offset', 1],
['height', '100px'],
]),
]);
resetState();
cmp.exp2 = 0;
fixture.detectChanges();
engine.flush();
expect(getLog().pop()!.keyframes).toEqual([
new Map<string, string | number>([
['offset', 0],
['height', '0px'],
]),
new Map<string, string | number>([
['offset', 1],
['height', '100px'],
]),
]);
resetState();
cmp.exp2 = '';
fixture.detectChanges();
engine.flush();
expect(getLog().pop()!.keyframes).toEqual([
new Map<string, string | number>([
['offset', 0],
['height', '0px'],
]),
new Map<string, string | number>([
['offset', 1],
['height', '100px'],
]),
]);
resetState();
cmp.exp2 = undefined;
fixture.detectChanges();
engine.flush();
expect(getLog().pop()!.keyframes).toEqual([
new Map<string, string | number>([
['offset', 0],
['height', '0px'],
]),
new Map<string, string | number>([
['offset', 1],
['height', '100px'],
]),
]);
resetState();
cmp.exp1 = false;
cmp.exp2 = 'abc';
fixture.detectChanges();
engine.flush();
expect(getLog().pop()!.keyframes).toEqual([
new Map<string, string | number>([
['offset', 0],
['width', '0px'],
]),
new Map<string, string | number>([
['offset', 1],
['width', '100px'],
]),
]);
});
it('should stringify boolean triggers to `1` and `0`', () => {
@Component({
selector: 'if-cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition('void => 1', [style({opacity: 0}), animate(1000, style({opacity: 1}))]),
transition('1 => 0', [style({opacity: 1}), animate(1000, style({opacity: 0}))]),
]),
],
standalone: false,
})
class Cmp {
exp: any = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
engine.flush();
expect(getLog().pop()!.keyframes).toEqual([
new Map<string, string | number>([
['offset', 0],
['opacity', '0'],
]),
new Map<string, string | number>([
['offset', 1],
['opacity', '1'],
]),
]);
cmp.exp = false;
fixture.detectChanges();
engine.flush();
expect(getLog().pop()!.keyframes).toEqual([
new Map<string, string | number>([
['offset', 0],
['opacity', '1'],
]),
new Map<string, string | number>([
['offset', 1],
['opacity', '0'],
]),
]);
});
it('should understand boolean values as `true` and `false` for transition animations', () => {
@Component({
selector: 'if-cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition('true => false', [
style({opacity: 0}),
animate(1234, style({opacity: 1})),
]),
transition('false => true', [
style({opacity: 1}),
animate(4567, style({opacity: 0})),
]),
]),
],
standalone: false,
})
class Cmp {
exp: any = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
cmp.exp = false;
fixture.detectChanges();
let players = getLog();
expect(players.length).toEqual(1);
let [player] = players;
expect(player.duration).toEqual(1234);
});
it('should understand boolean values as `true` and `false` for transition animations and apply the corresponding state() value', () => {
@Component({
selector: 'if-cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
state('true', style({color: 'red'})),
state('false', style({color: 'blue'})),
transition('true <=> false', [animate(1000, style({color: 'gold'})), animate(1000)]),
]),
],
standalone: false,
})
class Cmp {
exp: any = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = false;
fixture.detectChanges();
cmp.exp = true;
fixture.detectChanges();
let players = getLog();
expect(players.length).toEqual(1);
let [player] = players;
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['color', 'blue'],
['offset', 0],
]),
new Map<string, string | number>([
['color', 'gold'],
['offset', 0.5],
]),
new Map<string, string | number>([
['color', 'red'],
['offset', 1],
]),
]);
});
it('sho | {
"end_byte": 29006,
"start_byte": 19926,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_29014_38698 | throw an error if a trigger with the same name exists in separate components', () => {
@Component({
selector: 'cmp1',
template: '...',
animations: [trigger('trig', [])],
standalone: false,
})
class Cmp1 {}
@Component({
selector: 'cmp2',
template: '...',
animations: [trigger('trig', [])],
standalone: false,
})
class Cmp2 {}
TestBed.configureTestingModule({declarations: [Cmp1, Cmp2]});
const cmp1 = TestBed.createComponent(Cmp1);
const cmp2 = TestBed.createComponent(Cmp2);
});
describe('host bindings', () => {
it('should trigger a state change animation from state => state on the component host element', fakeAsync(() => {
@Component({
selector: 'my-cmp',
template: '...',
animations: [
trigger('myAnimation', [
transition('a => b', [
style({'opacity': '0'}),
animate(500, style({'opacity': '1'})),
]),
]),
],
standalone: false,
})
class Cmp {
@HostBinding('@myAnimation') exp = 'a';
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
engine.flush();
expect(getLog().length).toEqual(0);
cmp.exp = 'b';
fixture.detectChanges();
engine.flush();
expect(getLog().length).toEqual(1);
const data = getLog().pop()!;
expect(data.element).toEqual(fixture.elementRef.nativeElement);
expect(data.keyframes).toEqual([
new Map<string, string | number>([
['offset', 0],
['opacity', '0'],
]),
new Map<string, string | number>([
['offset', 1],
['opacity', '1'],
]),
]);
}));
it('should trigger a leave animation when the inner has ViewContainerRef injected', fakeAsync(() => {
@Component({
selector: 'parent-cmp',
template: `
<child-cmp *ngIf="exp"></child-cmp>
`,
standalone: false,
})
class ParentCmp {
public exp = true;
}
@Component({
selector: 'child-cmp',
template: '...',
animations: [
trigger('host', [
transition(':leave', [style({opacity: 1}), animate(1000, style({opacity: 0}))]),
]),
],
standalone: false,
})
class ChildCmp {
@HostBinding('@host') public hostAnimation = true;
constructor(private vcr: ViewContainerRef) {}
}
TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(ParentCmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
engine.flush();
expect(getLog().length).toEqual(0);
cmp.exp = false;
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.children.length).toBe(1);
engine.flush();
expect(getLog().length).toEqual(1);
const [player] = getLog();
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['opacity', '1'],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', '0'],
['offset', 1],
]),
]);
player.finish();
expect(fixture.debugElement.nativeElement.children.length).toBe(0);
}));
it('should trigger a leave animation when the inner components host binding updates', fakeAsync(() => {
@Component({
selector: 'parent-cmp',
template: `
<child-cmp *ngIf="exp"></child-cmp>
`,
standalone: false,
})
class ParentCmp {
public exp = true;
}
@Component({
selector: 'child-cmp',
template: '...',
animations: [
trigger('host', [
transition(':leave', [style({opacity: 1}), animate(1000, style({opacity: 0}))]),
]),
],
standalone: false,
})
class ChildCmp {
@HostBinding('@host') public hostAnimation = true;
}
TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(ParentCmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
engine.flush();
expect(getLog().length).toEqual(0);
cmp.exp = false;
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.children.length).toBe(1);
engine.flush();
expect(getLog().length).toEqual(1);
const [player] = getLog();
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['opacity', '1'],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', '0'],
['offset', 1],
]),
]);
player.finish();
expect(fixture.debugElement.nativeElement.children.length).toBe(0);
}));
it('should wait for child animations before removing parent', fakeAsync(() => {
@Component({
template: '<child-cmp *ngIf="exp" @parentTrigger></child-cmp>',
animations: [
trigger('parentTrigger', [
transition(':leave', [group([query('@*', animateChild())])]),
]),
],
standalone: false,
})
class ParentCmp {
exp = true;
}
@Component({
selector: 'child-cmp',
template: '<p @childTrigger>Hello there</p>',
animations: [
trigger('childTrigger', [
transition(':leave', [style({opacity: 1}), animate('200ms', style({opacity: 0}))]),
]),
],
standalone: false,
})
class ChildCmp {}
TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(ParentCmp);
fixture.detectChanges();
engine.flush();
expect(getLog().length).toBe(0);
fixture.componentInstance.exp = false;
fixture.detectChanges();
expect(fixture.nativeElement.children.length).toBe(1);
engine.flush();
expect(getLog().length).toBe(2);
const player = getLog()[1];
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['opacity', '1'],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', '0'],
['offset', 1],
]),
]);
player.finish();
flushMicrotasks();
expect(fixture.nativeElement.children.length).toBe(0);
}));
// animationRenderer => nonAnimationRenderer
it('should trigger a leave animation when the outer components element binding updates on the host component element', fakeAsync(() => {
@Component({
selector: 'parent-cmp',
animations: [
trigger('host', [
transition(':leave', [style({opacity: 1}), animate(1000, style({opacity: 0}))]),
]),
],
template: `
<child-cmp *ngIf="exp" @host></child-cmp>
`,
standalone: false,
})
class ParentCmp {
public exp = true;
}
@Component({
selector: 'child-cmp',
template: '...',
standalone: false,
})
class ChildCmp {}
TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(ParentCmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
engine.flush();
expect(getLog().length).toEqual(0);
cmp.exp = false;
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.children.length).toBe(1);
engine.flush();
expect(getLog().length).toEqual(1);
const [player] = getLog();
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['opacity', '1'],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', '0'],
['offset', 1],
]),
]);
player.finish();
flushMicrotasks();
expect(fixture.debugElement.nativeElement.children.length).toBe(0);
}));
it('should | {
"end_byte": 38698,
"start_byte": 29014,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_38708_48110 | leave animation when both the inner and outer components trigger on the same element', fakeAsync(() => {
@Component({
selector: 'parent-cmp',
animations: [
trigger('host', [
transition(':leave', [
style({height: '100px'}),
animate(1000, style({height: '0px'})),
]),
]),
],
template: `
<child-cmp *ngIf="exp" @host></child-cmp>
`,
standalone: false,
})
class ParentCmp {
public exp = true;
}
@Component({
selector: 'child-cmp',
template: '...',
animations: [
trigger('host', [
transition(':leave', [
style({width: '100px'}),
animate(1000, style({width: '0px'})),
]),
]),
],
standalone: false,
})
class ChildCmp {
@HostBinding('@host') public hostAnimation = true;
}
TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(ParentCmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
engine.flush();
expect(getLog().length).toEqual(0);
cmp.exp = false;
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.children.length).toBe(1);
engine.flush();
expect(getLog().length).toEqual(2);
const [p1, p2] = getLog();
expect(p1.keyframes).toEqual([
new Map<string, string | number>([
['width', '100px'],
['offset', 0],
]),
new Map<string, string | number>([
['width', '0px'],
['offset', 1],
]),
]);
expect(p2.keyframes).toEqual([
new Map<string, string | number>([
['height', '100px'],
['offset', 0],
]),
new Map<string, string | number>([
['height', '0px'],
['offset', 1],
]),
]);
p1.finish();
p2.finish();
flushMicrotasks();
expect(fixture.debugElement.nativeElement.children.length).toBe(0);
}));
it('should not throw when the host element is removed and no animation triggers', fakeAsync(() => {
@Component({
selector: 'parent-cmp',
template: `
<child-cmp *ngIf="exp"></child-cmp>
`,
standalone: false,
})
class ParentCmp {
public exp = true;
}
@Component({
selector: 'child-cmp',
template: '...',
animations: [trigger('host', [transition('a => b', [style({height: '100px'})])])],
standalone: false,
})
class ChildCmp {
@HostBinding('@host') public hostAnimation = 'a';
}
TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(ParentCmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.children.length).toBe(1);
engine.flush();
expect(getLog().length).toEqual(0);
cmp.exp = false;
fixture.detectChanges();
engine.flush();
flushMicrotasks();
expect(getLog().length).toEqual(0);
expect(fixture.debugElement.nativeElement.children.length).toBe(0);
flushMicrotasks();
expect(fixture.debugElement.nativeElement.children.length).toBe(0);
}));
it('should properly evaluate pre/auto-style values when components are inserted/removed which contain host animations', fakeAsync(() => {
@Component({
selector: 'parent-cmp',
template: `
<child-cmp *ngFor="let item of items"></child-cmp>
`,
standalone: false,
})
class ParentCmp {
items: any[] = [1, 2, 3, 4, 5];
}
@Component({
selector: 'child-cmp',
template: '... child ...',
animations: [
trigger('host', [transition(':leave', [animate(1000, style({opacity: 0}))])]),
],
standalone: false,
})
class ChildCmp {
@HostBinding('@host') public hostAnimation = 'a';
}
TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(ParentCmp);
const cmp = fixture.componentInstance;
const element = fixture.nativeElement;
fixture.detectChanges();
cmp.items = [0, 2, 4, 6]; // 1,3,5 get removed
fixture.detectChanges();
const items = element.querySelectorAll('child-cmp');
for (let i = 0; i < items.length; i++) {
const item = items[i];
expect(item.style['display']).toBeFalsy();
}
}));
});
it('should cancel and merge in mid-animation styles into the follow-up animation, but only for animation keyframes that start right away', () => {
@Component({
selector: 'ani-cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition('a => b', [
style({'opacity': '0'}),
animate(500, style({'opacity': '1'})),
]),
transition('b => c', [
group([
animate(500, style({'width': '100px'})),
animate(500, style({'height': '100px'})),
]),
animate(500, keyframes([style({'opacity': '0'}), style({'opacity': '1'})])),
]),
]),
],
standalone: false,
})
class Cmp {
exp: any = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'a';
fixture.detectChanges();
engine.flush();
expect(getLog().length).toEqual(0);
resetLog();
cmp.exp = 'b';
fixture.detectChanges();
engine.flush();
expect(getLog().length).toEqual(1);
resetLog();
cmp.exp = 'c';
fixture.detectChanges();
engine.flush();
const players = getLog();
expect(players.length).toEqual(3);
const [p1, p2, p3] = players;
expect(p1.previousStyles).toEqual(new Map([['opacity', AUTO_STYLE]]));
expect(p2.previousStyles).toEqual(new Map([['opacity', AUTO_STYLE]]));
expect(p3.previousStyles).toEqual(new Map());
});
it('should provide the styling of previous players that are grouped', () => {
@Component({
selector: 'ani-cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition('1 => 2', [
group([
animate(500, style({'width': '100px'})),
animate(500, style({'height': '100px'})),
]),
animate(500, keyframes([style({'opacity': '0'}), style({'opacity': '1'})])),
]),
transition('2 => 3', [
style({'opacity': '0'}),
animate(500, style({'opacity': '1'})),
]),
]),
],
standalone: false,
})
class Cmp {
exp: any = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
engine.flush();
cmp.exp = '1';
fixture.detectChanges();
engine.flush();
expect(getLog().length).toEqual(0);
resetLog();
cmp.exp = '2';
fixture.detectChanges();
engine.flush();
expect(getLog().length).toEqual(3);
resetLog();
cmp.exp = '3';
fixture.detectChanges();
engine.flush();
const players = getLog();
expect(players.length).toEqual(1);
const player = players[0] as MockAnimationPlayer;
const pp = player.previousPlayers as MockAnimationPlayer[];
expect(pp.length).toEqual(3);
expect(pp[0].currentSnapshot).toEqual(new Map([['width', AUTO_STYLE]]));
expect(pp[1].currentSnapshot).toEqual(new Map([['height', AUTO_STYLE]]));
expect(pp[2].currentSnapshot).toEqual(new Map([['opacity', AUTO_STYLE]]));
});
it('should provid | {
"end_byte": 48110,
"start_byte": 38708,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_48118_57226 | yling of previous players that are grouped and queried and make sure match the players with the correct elements', () => {
@Component({
selector: 'ani-cmp',
template: `
<div class="container" [@myAnimation]="exp">
<div class="inner"></div>
</div>
`,
animations: [
trigger('myAnimation', [
transition('1 => 2', [
style({fontSize: '10px'}),
query('.inner', [style({fontSize: '20px'})]),
animate('1s', style({fontSize: '100px'})),
query('.inner', [animate('1s', style({fontSize: '200px'}))]),
]),
transition('2 => 3', [
animate('1s', style({fontSize: '0px'})),
query('.inner', [animate('1s', style({fontSize: '0px'}))]),
]),
]),
],
standalone: false,
})
class Cmp {
exp: any = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
cmp.exp = '1';
fixture.detectChanges();
resetLog();
cmp.exp = '2';
fixture.detectChanges();
resetLog();
cmp.exp = '3';
fixture.detectChanges();
const players = getLog();
expect(players.length).toEqual(2);
const [p1, p2] = players as MockAnimationPlayer[];
const pp1 = p1.previousPlayers as MockAnimationPlayer[];
expect(p1.element.classList.contains('container')).toBeTruthy();
for (let i = 0; i < pp1.length; i++) {
expect(pp1[i].element).toEqual(p1.element);
}
const pp2 = p2.previousPlayers as MockAnimationPlayer[];
expect(p2.element.classList.contains('inner')).toBeTruthy();
for (let i = 0; i < pp2.length; i++) {
expect(pp2[i].element).toEqual(p2.element);
}
});
it('should properly balance styles between states even if there are no destination state styles', () => {
@Component({
selector: 'ani-cmp',
template: `
<div @myAnimation *ngIf="exp"></div>
`,
animations: [
trigger('myAnimation', [
state('void', style({opacity: 0, width: '0px', height: '0px'})),
transition(':enter', animate(1000)),
]),
],
standalone: false,
})
class Cmp {
exp: boolean = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
engine.flush();
const [p1] = getLog();
expect(p1.keyframes).toEqual([
new Map<string, string | number>([
['opacity', '0'],
['width', '0px'],
['height', '0px'],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', AUTO_STYLE],
['width', AUTO_STYLE],
['height', AUTO_STYLE],
['offset', 1],
]),
]);
});
it('should not apply the destination styles if the final animate step already contains styles', () => {
@Component({
selector: 'ani-cmp',
template: `
<div @myAnimation *ngIf="exp"></div>
`,
animations: [
trigger('myAnimation', [
state('void', style({color: 'red'})),
state('*', style({color: 'blue'})),
transition(':enter', [
style({fontSize: '0px '}),
animate(1000, style({fontSize: '100px'})),
]),
]),
],
standalone: false,
})
class Cmp {
exp: boolean = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
engine.flush();
const players = getLog();
expect(players.length).toEqual(1);
// notice how the final color is NOT blue
expect(players[0].keyframes).toEqual([
new Map<string, string | number>([
['fontSize', '0px'],
['color', 'red'],
['offset', 0],
]),
new Map<string, string | number>([
['fontSize', '100px'],
['color', 'red'],
['offset', 1],
]),
]);
});
it('should invoke an animation trigger that is state-less', () => {
@Component({
selector: 'ani-cmp',
template: `
<div *ngFor="let item of items" @myAnimation></div>
`,
animations: [
trigger('myAnimation', [
transition(':enter', [style({opacity: 0}), animate(1000, style({opacity: 1}))]),
]),
],
standalone: false,
})
class Cmp {
items: number[] = [];
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.items = [1, 2, 3, 4, 5];
fixture.detectChanges();
engine.flush();
expect(getLog().length).toEqual(5);
for (let i = 0; i < 5; i++) {
const item = getLog()[i];
expect(item.duration).toEqual(1000);
expect(item.keyframes).toEqual([
new Map<string, string | number>([
['opacity', '0'],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', '1'],
['offset', 1],
]),
]);
}
});
it('should retain styles on the element once the animation is complete', () => {
@Component({
selector: 'ani-cmp',
template: `
<div #green @green></div>
`,
animations: [
trigger('green', [
state('*', style({backgroundColor: 'green'})),
transition('* => *', animate(500)),
]),
],
standalone: false,
})
class Cmp {
@ViewChild('green') public element: any;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
engine.flush();
const player = engine.players.pop()!;
player.finish();
expect(hasStyle(cmp.element.nativeElement, 'background-color', 'green')).toBeTruthy();
});
it('should retain state styles when the underlying DOM structure changes even if there are no insert/remove animations', () => {
@Component({
selector: 'ani-cmp',
template: `
<div class="item" *ngFor="let item of items" [@color]="colorExp">
{{ item }}
</div>
`,
animations: [trigger('color', [state('green', style({backgroundColor: 'green'}))])],
standalone: false,
})
class Cmp {
public colorExp = 'green';
public items = [0, 1, 2, 3];
reorder() {
const temp = this.items[0];
this.items[0] = this.items[1];
this.items[1] = temp;
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
let elements: HTMLElement[] = fixture.nativeElement.querySelectorAll('.item');
assertBackgroundColor(elements[0], 'green');
assertBackgroundColor(elements[1], 'green');
assertBackgroundColor(elements[2], 'green');
assertBackgroundColor(elements[3], 'green');
elements[0].title = '0a';
elements[1].title = '1a';
cmp.reorder();
fixture.detectChanges();
elements = fixture.nativeElement.querySelectorAll('.item');
assertBackgroundColor(elements[0], 'green');
assertBackgroundColor(elements[1], 'green');
assertBackgroundColor(elements[2], 'green');
assertBackgroundColor(elements[3], 'green');
function assertBackgroundColor(element: HTMLElement, color: string) {
expect(element.style.getPropertyValue('background-color')).toEqual(color);
}
});
it('should retain stat | {
"end_byte": 57226,
"start_byte": 48118,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_57234_65798 | when the underlying DOM structure changes even if there are insert/remove animations', () => {
@Component({
selector: 'ani-cmp',
template: `
<div class="item" *ngFor="let item of items" [@color]="colorExp">
{{ item }}
</div>
`,
animations: [
trigger('color', [
transition('* => *', animate(500)),
state('green', style({backgroundColor: 'green'})),
]),
],
standalone: false,
})
class Cmp {
public colorExp = 'green';
public items = [0, 1, 2, 3];
reorder() {
const temp = this.items[0];
this.items[0] = this.items[1];
this.items[1] = temp;
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
getLog().forEach((p) => p.finish());
let elements: HTMLElement[] = fixture.nativeElement.querySelectorAll('.item');
assertBackgroundColor(elements[0], 'green');
assertBackgroundColor(elements[1], 'green');
assertBackgroundColor(elements[2], 'green');
assertBackgroundColor(elements[3], 'green');
elements[0].title = '0a';
elements[1].title = '1a';
cmp.reorder();
fixture.detectChanges();
getLog().forEach((p) => p.finish());
elements = fixture.nativeElement.querySelectorAll('.item');
assertBackgroundColor(elements[0], 'green');
assertBackgroundColor(elements[1], 'green');
assertBackgroundColor(elements[2], 'green');
assertBackgroundColor(elements[3], 'green');
function assertBackgroundColor(element: HTMLElement, color: string) {
expect(element.style.getPropertyValue('background-color')).toEqual(color);
}
});
it('should keep/restore the trigger value when there are move operations (with *ngFor + trackBy)', fakeAsync(() => {
@Component({
selector: 'ani-cmp',
template: `
<div *ngFor="let item of items, trackBy: trackItem"
@myAnimation (@myAnimation.start)="cb($event)">
item{{ item }}
</div>
`,
animations: [trigger('myAnimation', [])],
standalone: false,
})
class Cmp {
public items: number[] = [];
log: string[] = [];
cb(event: AnimationEvent) {
this.log.push(
`[${event.element.innerText.trim()}] ${event.fromState} => ${event.toState}`,
);
}
trackItem(_index: number, item: number) {
return item.toString();
}
addItem() {
this.items.push(this.items.length);
}
removeItem() {
this.items.pop();
}
reverseItems() {
this.items = this.items.reverse();
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
const completeAnimations = () => {
fixture.detectChanges();
flushMicrotasks();
engine.players.forEach((player) => player.finish());
};
cmp.log = [];
[0, 1, 2].forEach(() => cmp.addItem());
completeAnimations();
expect(cmp.log).toEqual([
'[item0] void => null',
'[item1] void => null',
'[item2] void => null',
]);
cmp.reverseItems();
completeAnimations();
cmp.log = [];
[0, 1, 2].forEach(() => cmp.removeItem());
completeAnimations();
expect(cmp.log).toEqual([
'[item2] null => void',
'[item1] null => void',
'[item0] null => void',
]);
}));
it('should animate removals of nodes to the `void` state for each animation trigger, but treat all auto styles as pre styles', () => {
@Component({
selector: 'ani-cmp',
template: `
<div *ngIf="exp" class="ng-if" [@trig1]="exp2" @trig2></div>
`,
animations: [
trigger('trig1', [transition('state => void', [animate(1000, style({opacity: 0}))])]),
trigger('trig2', [transition(':leave', [animate(1000, style({width: '0px'}))])]),
],
standalone: false,
})
class Cmp {
public exp = true;
public exp2 = 'state';
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
engine.flush();
resetLog();
const element = fixture.nativeElement.querySelector('.ng-if');
assertHasParent(element, true);
cmp.exp = false;
fixture.detectChanges();
engine.flush();
assertHasParent(element, true);
expect(getLog().length).toEqual(2);
const player2 = getLog().pop()!;
const player1 = getLog().pop()!;
expect(player2.keyframes).toEqual([
new Map<string, string | number>([
['width', PRE_STYLE],
['offset', 0],
]),
new Map<string, string | number>([
['width', '0px'],
['offset', 1],
]),
]);
expect(player1.keyframes).toEqual([
new Map<string, string | number>([
['opacity', PRE_STYLE],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', '0'],
['offset', 1],
]),
]);
player2.finish();
player1.finish();
assertHasParent(element, false);
});
it('should properly cancel all existing animations when a removal occurs', () => {
@Component({
selector: 'ani-cmp',
template: `
<div *ngIf="exp" [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition('* => go', [
style({width: '0px'}),
animate(1000, style({width: '100px'})),
]),
]),
],
standalone: false,
})
class Cmp {
public exp: string | null | undefined;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'go';
fixture.detectChanges();
engine.flush();
expect(getLog().length).toEqual(1);
const [player1] = getLog();
resetLog();
let finished = false;
player1.onDone(() => (finished = true));
let destroyed = false;
player1.onDestroy(() => (destroyed = true));
cmp.exp = null;
fixture.detectChanges();
engine.flush();
expect(finished).toBeTruthy();
expect(destroyed).toBeTruthy();
});
it('should not run inner child animations when a parent is set to be removed', () => {
@Component({
selector: 'ani-cmp',
template: `
<div *ngIf="exp" class="parent" >
<div [@myAnimation]="exp2"></div>
</div>
`,
animations: [
trigger('myAnimation', [transition('a => b', [animate(1000, style({width: '0px'}))])]),
],
standalone: false,
})
class Cmp {
public exp = true;
public exp2 = '0';
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
cmp.exp2 = 'a';
fixture.detectChanges();
engine.flush();
resetLog();
cmp.exp = false;
cmp.exp2 = 'b';
fixture.detectChanges();
engine.flush();
expect(getLog().length).toEqual(0);
});
it('should cancel all acti | {
"end_byte": 65798,
"start_byte": 57234,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_65806_74881 | child animations when a parent removal animation is set to go', () => {
@Component({
selector: 'ani-cmp',
template: `
<div *ngIf="exp1" @parent>
<div [@child]="exp2" class="child1"></div>
<div [@child]="exp2" class="child2"></div>
</div>
`,
animations: [
trigger('parent', [
transition(':leave', [style({opacity: 0}), animate(1000, style({opacity: 1}))]),
]),
trigger('child', [
transition('a => b', [style({opacity: 0}), animate(1000, style({opacity: 1}))]),
]),
],
standalone: false,
})
class Cmp {
public exp1: any;
public exp2: any;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp1 = true;
cmp.exp2 = 'a';
fixture.detectChanges();
engine.flush();
resetLog();
cmp.exp2 = 'b';
fixture.detectChanges();
engine.flush();
let players = getLog();
expect(players.length).toEqual(2);
const [p1, p2] = players;
let count = 0;
p1.onDone(() => count++);
p2.onDone(() => count++);
cmp.exp1 = false;
fixture.detectChanges();
engine.flush();
expect(count).toEqual(2);
});
it('should destroy inner animations when a parent node is set for removal', () => {
@Component({
selector: 'ani-cmp',
template: `
<div #parent class="parent">
<div [@child]="exp" class="child1"></div>
<div [@child]="exp" class="child2"></div>
</div>
`,
animations: [
trigger('child', [
transition('a => b', [style({opacity: 0}), animate(1000, style({opacity: 1}))]),
]),
],
standalone: false,
})
class Cmp {
public exp: any;
@ViewChild('parent') public parentElement: any;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
const someTrigger = trigger('someTrigger', []);
const hostElement = fixture.nativeElement;
engine.register(DEFAULT_NAMESPACE_ID, hostElement);
engine.registerTrigger(
DEFAULT_COMPONENT_ID,
DEFAULT_NAMESPACE_ID,
hostElement,
someTrigger.name,
someTrigger,
);
cmp.exp = 'a';
fixture.detectChanges();
engine.flush();
resetLog();
cmp.exp = 'b';
fixture.detectChanges();
engine.flush();
const players = getLog();
expect(players.length).toEqual(2);
const [p1, p2] = players;
let count = 0;
p1.onDone(() => count++);
p2.onDone(() => count++);
engine.onRemove(DEFAULT_NAMESPACE_ID, cmp.parentElement.nativeElement, null);
expect(count).toEqual(2);
});
it('should allow inner removals to happen when a non removal-based parent animation is set to animate', () => {
@Component({
selector: 'ani-cmp',
template: `
<div #parent [@parent]="exp1" class="parent">
<div #child *ngIf="exp2" class="child"></div>
</div>
`,
animations: [
trigger('parent', [
transition('a => b', [style({opacity: 0}), animate(1000, style({opacity: 1}))]),
]),
],
standalone: false,
})
class Cmp {
public exp1: any;
public exp2: any;
@ViewChild('parent') public parent: any;
@ViewChild('child') public child: any;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp1 = 'a';
cmp.exp2 = true;
fixture.detectChanges();
engine.flush();
resetLog();
cmp.exp1 = 'b';
fixture.detectChanges();
engine.flush();
const player = getLog()[0];
const p = cmp.parent.nativeElement;
const c = cmp.child.nativeElement;
expect(p.contains(c)).toBeTruthy();
cmp.exp2 = false;
fixture.detectChanges();
engine.flush();
expect(p.contains(c)).toBeFalsy();
player.finish();
expect(p.contains(c)).toBeFalsy();
});
it('should make inner removals wait until a parent based removal animation has finished', () => {
@Component({
selector: 'ani-cmp',
template: `
<div #parent *ngIf="exp1" @parent class="parent">
<div #child1 *ngIf="exp2" class="child1"></div>
<div #child2 *ngIf="exp2" class="child2"></div>
</div>
`,
animations: [
trigger('parent', [
transition(':leave', [style({opacity: 0}), animate(1000, style({opacity: 1}))]),
]),
],
standalone: false,
})
class Cmp {
public exp1: any;
public exp2: any;
@ViewChild('parent') public parent: any;
@ViewChild('child1') public child1Elm: any;
@ViewChild('child2') public child2Elm: any;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp1 = true;
cmp.exp2 = true;
fixture.detectChanges();
engine.flush();
resetLog();
const p = cmp.parent.nativeElement;
const c1 = cmp.child1Elm.nativeElement;
const c2 = cmp.child2Elm.nativeElement;
cmp.exp1 = false;
cmp.exp2 = false;
fixture.detectChanges();
engine.flush();
expect(p.contains(c1)).toBeTruthy();
expect(p.contains(c2)).toBeTruthy();
cmp.exp2 = false;
fixture.detectChanges();
engine.flush();
expect(p.contains(c1)).toBeTruthy();
expect(p.contains(c2)).toBeTruthy();
});
it('should detect trigger changes based on object.value properties', () => {
@Component({
selector: 'ani-cmp',
template: `
<div [@myAnimation]="{value:exp}"></div>
`,
animations: [
trigger('myAnimation', [
transition('* => 1', [animate(1234, style({opacity: 0}))]),
transition('* => 2', [animate(5678, style({opacity: 0}))]),
]),
],
standalone: false,
})
class Cmp {
public exp: any;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = '1';
fixture.detectChanges();
engine.flush();
let players = getLog();
expect(players.length).toEqual(1);
expect(players[0].duration).toEqual(1234);
resetLog();
cmp.exp = '2';
fixture.detectChanges();
engine.flush();
players = getLog();
expect(players.length).toEqual(1);
expect(players[0].duration).toEqual(5678);
});
it('should not render animations when the object expression value is the same as it was previously', () => {
@Component({
selector: 'ani-cmp',
template: `
<div [@myAnimation]="{value:exp,params:params}"></div>
`,
animations: [
trigger('myAnimation', [transition('* => *', [animate(1234, style({opacity: 0}))])]),
],
standalone: false,
})
class Cmp {
public exp: any;
public params: any;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = '1';
cmp.params = {};
fixture.detectChanges();
engine.flush();
let players = getLog();
expect(players.length).toEqual(1);
expect(players[0].duration).toEqual(1234);
resetLog();
cmp.exp = '1';
cmp.params = {};
fixture.detectChanges();
engine.flush();
players = getLog();
expect(players.length).toEqual(0);
});
it("should update the final stat | {
"end_byte": 74881,
"start_byte": 65806,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_74889_83838 | when params update even if the expression hasn't changed", fakeAsync(() => {
@Component({
selector: 'ani-cmp',
template: `
<div [@myAnimation]="{value:exp,params:{color:color}}"></div>
`,
animations: [
trigger('myAnimation', [
state('*', style({color: '{{ color }}'}), {params: {color: 'black'}}),
transition('* => 1', animate(500)),
]),
],
standalone: false,
})
class Cmp {
public exp: any;
public color: string | null | undefined;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = '1';
cmp.color = 'red';
fixture.detectChanges();
const player = getLog()[0]!;
const element = player.element;
player.finish();
flushMicrotasks();
expect(hasStyle(element, 'color', 'red')).toBeTruthy();
cmp.exp = '1';
cmp.color = 'blue';
fixture.detectChanges();
resetLog();
flushMicrotasks();
expect(hasStyle(element, 'color', 'blue')).toBeTruthy();
cmp.exp = '1';
cmp.color = null;
fixture.detectChanges();
resetLog();
flushMicrotasks();
expect(hasStyle(element, 'color', 'black')).toBeTruthy();
}));
it('should substitute in values if the provided state match is an object with values', () => {
@Component({
selector: 'ani-cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition(
'a => b',
[style({opacity: '{{ start }}'}), animate(1000, style({opacity: '{{ end }}'}))],
buildParams({start: '0', end: '1'}),
),
]),
],
standalone: false,
})
class Cmp {
public exp: any;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = {value: 'a'};
fixture.detectChanges();
engine.flush();
resetLog();
cmp.exp = {value: 'b', params: {start: 0.3, end: 0.6}};
fixture.detectChanges();
engine.flush();
const player = getLog().pop()!;
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['opacity', '0.3'],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', '0.6'],
['offset', 1],
]),
]);
});
it('should retain substituted styles on the element once the animation is complete if referenced in the final state', fakeAsync(() => {
@Component({
selector: 'ani-cmp',
template: `
<div [@myAnimation]="{value:exp, params: { color: color }}"></div>
`,
animations: [
trigger('myAnimation', [
state(
'start',
style({
color: '{{ color }}',
fontSize: '{{ fontSize }}px',
width: '{{ width }}',
}),
{params: {color: 'red', fontSize: '200', width: '10px'}},
),
state(
'final',
style({color: '{{ color }}', fontSize: '{{ fontSize }}px', width: '888px'}),
{params: {color: 'green', fontSize: '50', width: '100px'}},
),
transition('start => final', animate(500)),
]),
],
standalone: false,
})
class Cmp {
public exp: any;
public color: any;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'start';
cmp.color = 'red';
fixture.detectChanges();
resetLog();
cmp.exp = 'final';
cmp.color = 'blue';
fixture.detectChanges();
const players = getLog();
expect(players.length).toEqual(1);
const [p1] = players;
expect(p1.keyframes).toEqual([
new Map<string, string | number>([
['color', 'red'],
['fontSize', '200px'],
['width', '10px'],
['offset', 0],
]),
new Map<string, string | number>([
['color', 'blue'],
['fontSize', '50px'],
['width', '888px'],
['offset', 1],
]),
]);
const element = p1.element;
p1.finish();
flushMicrotasks();
expect(hasStyle(element, 'color', 'blue')).toBeTruthy();
expect(hasStyle(element, 'fontSize', '50px')).toBeTruthy();
expect(hasStyle(element, 'width', '888px')).toBeTruthy();
}));
it('should only evaluate final state param substitutions from the expression and state values and not from the transition options ', fakeAsync(() => {
@Component({
selector: 'ani-cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
state(
'start',
style({
width: '{{ width }}',
height: '{{ height }}',
}),
{params: {width: '0px', height: '0px'}},
),
state(
'final',
style({
width: '{{ width }}',
height: '{{ height }}',
}),
{params: {width: '100px', height: '100px'}},
),
transition('start => final', [animate(500)], {
params: {width: '333px', height: '666px'},
}),
]),
],
standalone: false,
})
class Cmp {
public exp: any;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'start';
fixture.detectChanges();
resetLog();
cmp.exp = 'final';
fixture.detectChanges();
const players = getLog();
expect(players.length).toEqual(1);
const [p1] = players;
expect(p1.keyframes).toEqual([
new Map<string, string | number>([
['width', '0px'],
['height', '0px'],
['offset', 0],
]),
new Map<string, string | number>([
['width', '100px'],
['height', '100px'],
['offset', 1],
]),
]);
const element = p1.element;
p1.finish();
flushMicrotasks();
expect(hasStyle(element, 'width', '100px')).toBeTruthy();
expect(hasStyle(element, 'height', '100px')).toBeTruthy();
}));
it('should apply default params when resolved animation value is null or undefined', () => {
@Component({
selector: 'ani-cmp',
template: `<div [@myAnimation]="exp"></div>`,
animations: [
trigger('myAnimation', [
transition(
'a => b',
[style({opacity: '{{ start }}'}), animate(1000, style({opacity: '{{ end }}'}))],
buildParams({start: '0.4', end: '0.7'}),
),
]),
],
standalone: false,
})
class Cmp {
public exp: any;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = {value: 'a'};
fixture.detectChanges();
engine.flush();
resetLog();
cmp.exp = {value: 'b', params: {start: undefined, end: null}};
fixture.detectChanges();
engine.flush();
const player = getLog().pop()!;
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['opacity', '0.4'],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', '0.7'],
['offset', 1],
]),
]);
});
it('should not flush animations twice | {
"end_byte": 83838,
"start_byte": 74889,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_83846_90974 | inner component runs change detection', () => {
@Component({
selector: 'outer-cmp',
template: `
<div *ngIf="exp" @outer></div>
<inner-cmp #inner></inner-cmp>
`,
animations: [
trigger('outer', [
transition(':enter', [style({opacity: 0}), animate('1s', style({opacity: 1}))]),
]),
],
standalone: false,
})
class OuterCmp {
@ViewChild('inner') public inner: any;
public exp: any = null;
update() {
this.exp = 'go';
}
ngDoCheck() {
if (this.exp == 'go') {
this.inner.update();
}
}
}
@Component({
selector: 'inner-cmp',
template: `
<div *ngIf="exp" @inner></div>
`,
animations: [
trigger('inner', [
transition(':enter', [style({opacity: 0}), animate('1s', style({opacity: 1}))]),
]),
],
standalone: false,
})
class InnerCmp {
public exp: any;
constructor(private _ref: ChangeDetectorRef) {}
update() {
this.exp = 'go';
this._ref.detectChanges();
}
}
TestBed.configureTestingModule({declarations: [OuterCmp, InnerCmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(OuterCmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
expect(getLog()).toEqual([]);
cmp.update();
fixture.detectChanges();
const players = getLog();
expect(players.length).toEqual(2);
});
describe('transition aliases', () => {
describe(':increment', () => {
it('should detect when a value has incremented', () => {
@Component({
selector: 'if-cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition(':increment', [animate(1234, style({background: 'red'}))]),
]),
],
standalone: false,
})
class Cmp {
exp: number = 0;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
let players = getLog();
expect(players.length).toEqual(0);
cmp.exp++;
fixture.detectChanges();
players = getLog();
expect(players.length).toEqual(1);
expect(players[0].duration).toEqual(1234);
resetLog();
cmp.exp = 5;
fixture.detectChanges();
players = getLog();
expect(players.length).toEqual(1);
expect(players[0].duration).toEqual(1234);
});
});
describe(':decrement', () => {
it('should detect when a value has decremented', () => {
@Component({
selector: 'if-cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition(':decrement', [animate(1234, style({background: 'red'}))]),
]),
],
standalone: false,
})
class Cmp {
exp: number = 5;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
let players = getLog();
expect(players.length).toEqual(0);
cmp.exp--;
fixture.detectChanges();
players = getLog();
expect(players.length).toEqual(1);
expect(players[0].duration).toEqual(1234);
resetLog();
cmp.exp = 0;
fixture.detectChanges();
players = getLog();
expect(players.length).toEqual(1);
expect(players[0].duration).toEqual(1234);
});
});
});
it('should animate nodes properly when they have been re-ordered', () => {
@Component({
selector: 'if-cmp',
template: `
<div *ngFor="let item of items" [class]="'class-' + item.value">
<div [@myAnimation]="item.count">
{{ item.value }}
</div>
</div>
`,
animations: [
trigger('myAnimation', [
state('0', style({opacity: 0})),
state('1', style({opacity: 0.4})),
state('2', style({opacity: 0.8})),
transition('* => 1, * => 2', [animate(1000)]),
]),
],
standalone: false,
})
class Cmp {
items = [
{value: '1', count: 0},
{value: '2', count: 0},
{value: '3', count: 0},
{value: '4', count: 0},
{value: '5', count: 0},
];
reOrder() {
this.items = [
this.items[4],
this.items[1],
this.items[3],
this.items[0],
this.items[2],
];
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
const one = cmp.items[0];
const two = cmp.items[1];
one.count++;
fixture.detectChanges();
cmp.reOrder();
fixture.detectChanges();
resetLog();
one.count++;
two.count++;
fixture.detectChanges();
const players = getLog();
expect(players.length).toEqual(2);
});
});
it('should not animate i18n insertBefore', () => {
// I18n uses `insertBefore` API to insert nodes in correct order. Animation assumes that
// any `insertBefore` is a move and tries to animate it.
// NOTE: This test was extracted from `g3`
@Component({
template: `<div i18n>Hello <span>World</span>!</div>`,
animations: [trigger('myAnimation', [transition('* => *', [animate(1000)])])],
standalone: false,
})
class Cmp {}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
const players = getLog();
const span = fixture.debugElement.nativeElement.querySelector('span');
expect(span.innerText).toEqual('World');
// We should not insert `ng-star-inserted` into the span class.
expect(span.className).not.toContain('ng-star-inserted');
});
describe('animation listeners', () => {
| {
"end_byte": 90974,
"start_byte": 83846,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_90980_99292 | it('should trigger a `start` state change listener for when the animation changes state from void => state', fakeAsync(() => {
@Component({
selector: 'if-cmp',
template: `
<div *ngIf="exp" [@myAnimation]="exp" (@myAnimation.start)="callback($event)"></div>
`,
animations: [
trigger('myAnimation', [
transition('void => *', [
style({'opacity': '0'}),
animate(500, style({'opacity': '1'})),
]),
]),
],
standalone: false,
})
class Cmp {
exp: any = false;
event: AnimationEvent | undefined;
callback = (event: any) => {
this.event = event;
};
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'true';
fixture.detectChanges();
flushMicrotasks();
expect(cmp.event?.triggerName).toEqual('myAnimation');
expect(cmp.event?.phaseName).toEqual('start');
expect(cmp.event?.totalTime).toEqual(500);
expect(cmp.event?.fromState).toEqual('void');
expect(cmp.event?.toState).toEqual('true');
}));
it('should trigger a `done` state change listener for when the animation changes state from a => b', fakeAsync(() => {
@Component({
selector: 'if-cmp',
template: `
<div *ngIf="exp" [@myAnimation123]="exp" (@myAnimation123.done)="callback($event)"></div>
`,
animations: [
trigger('myAnimation123', [
transition('* => b', [
style({'opacity': '0'}),
animate(999, style({'opacity': '1'})),
]),
]),
],
standalone: false,
})
class Cmp {
exp: any = false;
event: AnimationEvent | undefined;
callback = (event: any) => {
this.event = event;
};
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'b';
fixture.detectChanges();
engine.flush();
expect(cmp.event).toBeFalsy();
const player = engine.players.pop()!;
player.finish();
flushMicrotasks();
expect(cmp.event?.triggerName).toEqual('myAnimation123');
expect(cmp.event?.phaseName).toEqual('done');
expect(cmp.event?.totalTime).toEqual(999);
expect(cmp.event?.fromState).toEqual('void');
expect(cmp.event?.toState).toEqual('b');
}));
it('should handle callbacks for multiple triggers running simultaneously', fakeAsync(() => {
@Component({
selector: 'if-cmp',
template: `
<div [@ani1]="exp1" (@ani1.done)="callback1($event)"></div>
<div [@ani2]="exp2" (@ani2.done)="callback2($event)"></div>
`,
animations: [
trigger('ani1', [
transition('* => a', [
style({'opacity': '0'}),
animate(999, style({'opacity': '1'})),
]),
]),
trigger('ani2', [
transition('* => b', [
style({'width': '0px'}),
animate(999, style({'width': '100px'})),
]),
]),
],
standalone: false,
})
class Cmp {
exp1: any = false;
exp2: any = false;
event1: AnimationEvent | undefined;
event2: AnimationEvent | undefined;
// tslint:disable:semicolon
callback1 = (event: any) => {
this.event1 = event;
};
// tslint:disable:semicolon
callback2 = (event: any) => {
this.event2 = event;
};
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp1 = 'a';
cmp.exp2 = 'b';
fixture.detectChanges();
engine.flush();
expect(cmp.event1).toBeFalsy();
expect(cmp.event2).toBeFalsy();
const player1 = engine.players[0];
const player2 = engine.players[1];
player1.finish();
player2.finish();
expect(cmp.event1).toBeFalsy();
expect(cmp.event2).toBeFalsy();
flushMicrotasks();
expect(cmp.event1?.triggerName).toBeTruthy('ani1');
expect(cmp.event2?.triggerName).toBeTruthy('ani2');
}));
it('should handle callbacks for multiple triggers running simultaneously on the same element', fakeAsync(() => {
@Component({
selector: 'if-cmp',
template: `
<div [@ani1]="exp1" (@ani1.done)="callback1($event)" [@ani2]="exp2" (@ani2.done)="callback2($event)"></div>
`,
animations: [
trigger('ani1', [
transition('* => a', [
style({'opacity': '0'}),
animate(999, style({'opacity': '1'})),
]),
]),
trigger('ani2', [
transition('* => b', [
style({'width': '0px'}),
animate(999, style({'width': '100px'})),
]),
]),
],
standalone: false,
})
class Cmp {
exp1: any = false;
exp2: any = false;
event1: AnimationEvent | undefined;
event2: AnimationEvent | undefined;
callback1 = (event: any) => {
this.event1 = event;
};
callback2 = (event: any) => {
this.event2 = event;
};
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp1 = 'a';
cmp.exp2 = 'b';
fixture.detectChanges();
engine.flush();
expect(cmp.event1).toBeFalsy();
expect(cmp.event2).toBeFalsy();
const player1 = engine.players[0];
const player2 = engine.players[1];
player1.finish();
player2.finish();
expect(cmp.event1).toBeFalsy();
expect(cmp.event2).toBeFalsy();
flushMicrotasks();
expect(cmp.event1?.triggerName).toBeTruthy('ani1');
expect(cmp.event2?.triggerName).toBeTruthy('ani2');
}));
it('should handle a leave animation for multiple triggers even if not all triggers have their own leave transition specified', fakeAsync(() => {
@Component({
selector: 'if-cmp',
template: `
<div *ngIf="exp" @foo @bar>123</div>
`,
animations: [
trigger('foo', [
transition(':enter', [style({opacity: 0}), animate(1000, style({opacity: 1}))]),
]),
trigger('bar', [transition(':leave', [animate(1000, style({opacity: 0}))])]),
],
standalone: false,
})
class Cmp {
exp: boolean = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const elm = fixture.elementRef.nativeElement;
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
let players = getLog();
expect(players.length).toEqual(1);
let [p1] = players;
p1.finish();
flushMicrotasks();
expect(elm.innerText.trim()).toEqual('123');
resetLog();
cmp.exp = false;
fixture.detectChanges();
players = getLog();
expect(players.length).toEqual(1);
[p1] = players;
p1.finish();
flushMicrotasks();
expect(elm.innerText.trim()).toEqual('');
}));
it('should trigger a state change listener | {
"end_byte": 99292,
"start_byte": 90980,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_99300_105860 | n the animation changes state from void => state on the host element', fakeAsync(() => {
@Component({
selector: 'my-cmp',
template: `...`,
animations: [
trigger('myAnimation2', [
transition('void => *', [
style({'opacity': '0'}),
animate(1000, style({'opacity': '1'})),
]),
]),
],
standalone: false,
})
class Cmp {
event: AnimationEvent | undefined;
@HostBinding('@myAnimation2') exp: any = false;
@HostListener('@myAnimation2.start', ['$event'])
callback = (event: any) => {
this.event = event;
};
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'TRUE';
fixture.detectChanges();
flushMicrotasks();
expect(cmp.event?.triggerName).toEqual('myAnimation2');
expect(cmp.event?.phaseName).toEqual('start');
expect(cmp.event?.totalTime).toEqual(1000);
expect(cmp.event?.fromState).toEqual('void');
expect(cmp.event?.toState).toEqual('TRUE');
}));
it('should always fire callbacks even when a transition is not detected', fakeAsync(() => {
@Component({
selector: 'my-cmp',
template: `
<div [@myAnimation]="exp" (@myAnimation.start)="callback($event)" (@myAnimation.done)="callback($event)"></div>
`,
animations: [trigger('myAnimation', [])],
standalone: false,
})
class Cmp {
exp: string | undefined;
log: any[] = [];
callback = (event: any) => this.log.push(`${event.phaseName} => ${event.toState}`);
}
TestBed.configureTestingModule({
providers: [{provide: AnimationDriver, useClass: NoopAnimationDriver}],
declarations: [Cmp],
});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'a';
fixture.detectChanges();
flushMicrotasks();
expect(cmp.log).toEqual(['start => a', 'done => a']);
cmp.log = [];
cmp.exp = 'b';
fixture.detectChanges();
flushMicrotasks();
expect(cmp.log).toEqual(['start => b', 'done => b']);
}));
it('should fire callback events for leave animations even if there is no leave transition', fakeAsync(() => {
@Component({
selector: 'my-cmp',
template: `
<div *ngIf="exp" @myAnimation (@myAnimation.start)="callback($event)" (@myAnimation.done)="callback($event)"></div>
`,
animations: [trigger('myAnimation', [])],
standalone: false,
})
class Cmp {
exp: boolean = false;
log: any[] = [];
callback = (event: any) => {
const state = event.toState || '_default_';
this.log.push(`${event.phaseName} => ${state}`);
};
}
TestBed.configureTestingModule({
providers: [{provide: AnimationDriver, useClass: NoopAnimationDriver}],
declarations: [Cmp],
});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
flushMicrotasks();
expect(cmp.log).toEqual(['start => _default_', 'done => _default_']);
cmp.log = [];
cmp.exp = false;
fixture.detectChanges();
flushMicrotasks();
expect(cmp.log).toEqual(['start => void', 'done => void']);
}));
it('should fire callbacks on a sub animation once it starts and finishes', fakeAsync(() => {
@Component({
selector: 'my-cmp',
template: `
<div class="parent"
[@parent]="exp1"
(@parent.start)="cb('parent-start',$event)"
(@parent.done)="cb('parent-done', $event)">
<div class="child"
[@child]="exp2"
(@child.start)="cb('child-start',$event)"
(@child.done)="cb('child-done', $event)"></div>
</div>
`,
animations: [
trigger('parent', [
transition('* => go', [
style({width: '0px'}),
animate(1000, style({width: '100px'})),
query('.child', [animateChild({duration: '1s'})]),
animate(1000, style({width: '0px'})),
]),
]),
trigger('child', [
transition('* => go', [
style({height: '0px'}),
animate(1000, style({height: '100px'})),
]),
]),
],
standalone: false,
})
class Cmp {
log: string[] = [];
exp1: string | undefined;
exp2: string | undefined;
cb(name: string, event: AnimationEvent) {
this.log.push(name);
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp1 = 'go';
cmp.exp2 = 'go';
fixture.detectChanges();
engine.flush();
flushMicrotasks();
expect(cmp.log).toEqual(['parent-start', 'child-start']);
cmp.log = [];
const players = getLog();
expect(players.length).toEqual(4);
// players:
// - _scp (skipped child player): player for the child animation
// - pp1 (parent player 1): player for parent animation (from 0px to 100px)
// - pcp (parent child player):
// player for child animation executed by parent via query and animateChild
// - pp2 (parent player 2): player for parent animation (from 100px to 0px)
const [_scp, pp1, pcp, pp2] = players;
pp1.finish();
flushMicrotasks();
expect(cmp.log).toEqual([]);
pcp.finish();
flushMicrotasks();
expect(cmp.log).toEqual([]);
pp2.finish();
flushMicrotasks();
expect(cmp.log).toEqual(['parent-done', 'child-done']);
}));
it('should fire callbacks and collect the co | {
"end_byte": 105860,
"start_byte": 99300,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_105868_109994 | e totalTime and element details for any queried sub animations', fakeAsync(() => {
@Component({
selector: 'my-cmp',
template: `
<div class="parent" [@parent]="exp" (@parent.done)="cb('all','done', $event)">
<div *ngFor="let item of items"
class="item item-{{ item }}"
@child
(@child.start)="cb('c-' + item, 'start', $event)"
(@child.done)="cb('c-' + item, 'done', $event)">
{{ item }}
</div>
</div>
`,
animations: [
trigger('parent', [
transition('* => go', [
style({opacity: 0}),
animate('1s', style({opacity: 1})),
query('.item', [style({opacity: 0}), animate(1000, style({opacity: 1}))]),
query('.item', [animateChild({duration: '1.8s', delay: '300ms'})]),
]),
]),
trigger('child', [
transition(':enter', [style({opacity: 0}), animate(1500, style({opacity: 1}))]),
]),
],
standalone: false,
})
class Cmp {
log: string[] = [];
events: {[name: string]: any} = {};
exp: string | undefined;
items: any = [0, 1, 2, 3];
cb(name: string, phase: string, event: AnimationEvent) {
this.log.push(name + '-' + phase);
this.events[name] = event;
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'go';
fixture.detectChanges();
engine.flush();
flushMicrotasks();
expect(cmp.log).toEqual(['c-0-start', 'c-1-start', 'c-2-start', 'c-3-start']);
cmp.log = [];
const players = getLog();
expect(players.length).toEqual(13);
// players:
// - _sc1p, _sc2p, _sc3p, _sc4p (skipped child n (1 to 4) players):
// players for the children animations
// - pp1 (parent player 1): player for parent animation (from opacity 0 to opacity 1)
// - pc1p1, pc2p1, pc3p1, pc4p1 (parent child n (1 to 4) player 1):
// players for children animations executed by parent via query and animate
// (from opacity 0 to opacity 1)
// - pc1p2, pc2p2, pc3p2, pc4p2 (parent child n (1 to 4) player 2):
// players for children animations executed by parent via query and animateChild
const [
_sc1p,
_sc2p,
_sc3p,
_sc4p,
pp1,
pc1p1,
pc2p1,
pc3p1,
pc4p1,
pc1p2,
pc2p2,
pc3p2,
pc4p2,
] = getLog();
pp1.finish();
pc1p1.finish();
pc2p1.finish();
pc3p1.finish();
pc4p1.finish();
flushMicrotasks();
expect(cmp.log).toEqual([]);
pc1p2.finish();
pc2p2.finish();
pc3p2.finish();
pc4p2.finish();
flushMicrotasks();
expect(cmp.log).toEqual(['all-done', 'c-0-done', 'c-1-done', 'c-2-done', 'c-3-done']);
expect(cmp.events['all'].totalTime).toEqual(4100); // 1000 + 1000 + 1800 + 300
expect(cmp.events['all'].element.innerText.trim().replaceAll('\n', ' ')).toEqual('0 1 2 3');
expect(cmp.events['c-0'].totalTime).toEqual(1500);
expect(cmp.events['c-0'].element.innerText.trim()).toEqual('0');
expect(cmp.events['c-1'].totalTime).toEqual(1500);
expect(cmp.events['c-1'].element.innerText.trim()).toEqual('1');
expect(cmp.events['c-2'].totalTime).toEqual(1500);
expect(cmp.events['c-2'].element.innerText.trim()).toEqual('2');
expect(cmp.events['c-3'].totalTime).toEqual(1500);
expect(cmp.events['c-3'].element.innerText.trim()).toEqual('3');
}));
});
describe('animation control flags', () => {
| {
"end_byte": 109994,
"start_byte": 105868,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_110000_119110 | cribe('[@.disabled]', () => {
it('should disable child animations when set to true', () => {
@Component({
selector: 'if-cmp',
template: `
<div [@.disabled]="disableExp">
<div [@myAnimation]="exp"></div>
</div>
`,
animations: [
trigger('myAnimation', [
transition('* => 1, * => 2', [animate(1234, style({width: '100px'}))]),
]),
],
standalone: false,
})
class Cmp {
exp: any = false;
disableExp = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
resetLog();
cmp.disableExp = true;
cmp.exp = '1';
fixture.detectChanges();
let players = getLog();
expect(players.length).toEqual(0);
cmp.disableExp = false;
cmp.exp = '2';
fixture.detectChanges();
players = getLog();
expect(players.length).toEqual(1);
expect(players[0].totalTime).toEqual(1234);
});
it('should ensure state() values are applied when an animation is disabled', () => {
@Component({
selector: 'if-cmp',
template: `
<div [@.disabled]="disableExp">
<div [@myAnimation]="exp" #elm></div>
</div>
`,
animations: [
trigger('myAnimation', [
state('1', style({height: '100px'})),
state('2', style({height: '200px'})),
state('3', style({height: '300px'})),
transition('* => *', animate(500)),
]),
],
standalone: false,
})
class Cmp {
exp: any = false;
disableExp = false;
@ViewChild('elm', {static: true}) public element: any;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const engine = TestBed.inject(ɵAnimationEngine);
function assertHeight(element: any, height: string) {
expect(element.style['height']).toEqual(height);
}
fixture.detectChanges();
const cmp = fixture.componentInstance;
const element = cmp.element.nativeElement;
fixture.detectChanges();
cmp.disableExp = true;
cmp.exp = '1';
fixture.detectChanges();
assertHeight(element, '100px');
cmp.exp = '2';
fixture.detectChanges();
assertHeight(element, '200px');
cmp.exp = '3';
fixture.detectChanges();
assertHeight(element, '300px');
});
it('should disable animations for the element that they are disabled on', () => {
@Component({
selector: 'if-cmp',
template: `
<div [@.disabled]="disableExp" [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition('* => 1, * => 2', [animate(1234, style({width: '100px'}))]),
]),
],
standalone: false,
})
class Cmp {
exp: any = false;
disableExp = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
resetLog();
cmp.disableExp = true;
cmp.exp = '1';
fixture.detectChanges();
let players = getLog();
expect(players.length).toEqual(0);
resetLog();
cmp.disableExp = false;
cmp.exp = '2';
fixture.detectChanges();
players = getLog();
expect(players.length).toEqual(1);
expect(players[0].totalTime).toEqual(1234);
});
it('should respect inner disabled nodes once a parent becomes enabled', () => {
@Component({
selector: 'if-cmp',
template: `
<div [@.disabled]="disableParentExp">
<div [@.disabled]="disableChildExp">
<div [@myAnimation]="exp"></div>
</div>
</div>
`,
animations: [
trigger('myAnimation', [
transition('* => 1, * => 2, * => 3', [animate(1234, style({width: '100px'}))]),
]),
],
standalone: false,
})
class Cmp {
disableParentExp = false;
disableChildExp = false;
exp = '';
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
resetLog();
cmp.disableParentExp = true;
cmp.disableChildExp = true;
cmp.exp = '1';
fixture.detectChanges();
let players = getLog();
expect(players.length).toEqual(0);
cmp.disableParentExp = false;
cmp.exp = '2';
fixture.detectChanges();
players = getLog();
expect(players.length).toEqual(0);
cmp.disableChildExp = false;
cmp.exp = '3';
fixture.detectChanges();
players = getLog();
expect(players.length).toEqual(1);
});
it('should properly handle dom operations when disabled', () => {
@Component({
selector: 'if-cmp',
template: `
<div [@.disabled]="disableExp" #parent>
<div *ngIf="exp" @myAnimation></div>
</div>
`,
animations: [
trigger('myAnimation', [
transition(':enter', [style({opacity: 0}), animate(1234, style({opacity: 1}))]),
transition(':leave', [animate(1234, style({opacity: 0}))]),
]),
],
standalone: false,
})
class Cmp {
@ViewChild('parent') public parentElm: any;
disableExp = false;
exp = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.disableExp = true;
fixture.detectChanges();
resetLog();
const parent = cmp.parentElm.nativeElement;
cmp.exp = true;
fixture.detectChanges();
expect(getLog().length).toEqual(0);
expect(parent.childElementCount).toEqual(1);
cmp.exp = false;
fixture.detectChanges();
expect(getLog().length).toEqual(0);
expect(parent.childElementCount).toEqual(0);
});
it('should properly resolve animation event listeners when disabled', fakeAsync(() => {
@Component({
selector: 'if-cmp',
template: `
<div [@.disabled]="disableExp">
<div [@myAnimation]="exp" (@myAnimation.start)="startEvent=$event" (@myAnimation.done)="doneEvent=$event"></div>
</div>
`,
animations: [
trigger('myAnimation', [
transition('* => 1, * => 2', [
style({opacity: 0}),
animate(9876, style({opacity: 1})),
]),
]),
],
standalone: false,
})
class Cmp {
disableExp = false;
exp = '';
startEvent: AnimationEvent | undefined;
doneEvent: AnimationEvent | undefined;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.disableExp = true;
fixture.detectChanges();
resetLog();
expect(cmp.startEvent).toBeFalsy();
expect(cmp.doneEvent).toBeFalsy();
cmp.exp = '1';
fixture.detectChanges();
flushMicrotasks();
expect(cmp.startEvent?.totalTime).toEqual(9876);
expect(cmp.startEvent?.disabled).toBeTruthy();
expect(cmp.doneEvent?.totalTime).toEqual(9876);
expect(cmp.doneEvent?.disabled).toBeTruthy();
cmp.exp = '2';
cmp.disableExp = false;
fixture.detectChanges();
flushMicrotasks();
expect(cmp.startEvent?.totalTime).toEqual(9876);
expect(cmp.startEvent?.disabled).toBeFalsy();
// the done event isn't fired because it's an actual animation
}));
it('should work when there are no animations | {
"end_byte": 119110,
"start_byte": 110000,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_119120_127186 | mponent handling the disable/enable flag', () => {
@Component({
selector: 'parent-cmp',
template: `
<div [@.disabled]="disableExp">
<child-cmp #child></child-cmp>
</div>
`,
standalone: false,
})
class ParentCmp {
@ViewChild('child') public child: ChildCmp | null = null;
disableExp = false;
}
@Component({
selector: 'child-cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition('* => go, * => goAgain', [
style({opacity: 0}),
animate('1s', style({opacity: 1})),
]),
]),
],
standalone: false,
})
class ChildCmp {
public exp = '';
}
TestBed.configureTestingModule({declarations: [ParentCmp, ChildCmp]});
const fixture = TestBed.createComponent(ParentCmp);
const cmp = fixture.componentInstance;
cmp.disableExp = true;
fixture.detectChanges();
resetLog();
const child = cmp.child!;
child.exp = 'go';
fixture.detectChanges();
expect(getLog().length).toEqual(0);
resetLog();
cmp.disableExp = false;
child.exp = 'goAgain';
fixture.detectChanges();
expect(getLog().length).toEqual(1);
});
it('should treat the property as true when the expression is missing', () => {
@Component({
selector: 'parent-cmp',
animations: [
trigger('myAnimation', [
transition('* => go', [style({opacity: 0}), animate(500, style({opacity: 1}))]),
]),
],
template: `
<div @.disabled>
<div [@myAnimation]="exp"></div>
</div>
`,
standalone: false,
})
class Cmp {
exp = '';
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
resetLog();
cmp.exp = 'go';
fixture.detectChanges();
expect(getLog().length).toEqual(0);
});
it('should respect parent/sub animations when the respective area in the DOM is disabled', fakeAsync(() => {
@Component({
selector: 'parent-cmp',
animations: [
trigger('parent', [
transition('* => empty', [
style({opacity: 0}),
query('@child', [animateChild()]),
animate('1s', style({opacity: 1})),
]),
]),
trigger('child', [transition(':leave', [animate('1s', style({opacity: 0}))])]),
],
template: `
<div [@.disabled]="disableExp" #container>
<div [@parent]="exp" (@parent.done)="onDone($event)">
<div class="item" *ngFor="let item of items" @child (@child.done)="onDone($event)"></div>
</div>
</div>
`,
standalone: false,
})
class Cmp {
@ViewChild('container') public container: any;
disableExp = false;
exp = '';
items: any[] = [];
doneLog: any[] = [];
onDone(event: any) {
this.doneLog.push(event);
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.disableExp = true;
cmp.items = [0, 1, 2, 3, 4];
fixture.detectChanges();
flushMicrotasks();
cmp.exp = 'empty';
cmp.items = [];
cmp.doneLog = [];
fixture.detectChanges();
flushMicrotasks();
const elms = cmp.container.nativeElement.querySelectorAll('.item');
expect(elms.length).toEqual(0);
expect(cmp.doneLog.length).toEqual(6);
}));
});
});
describe('animation normalization', () => {
it('should convert hyphenated properties to camelcase by default', () => {
@Component({
selector: 'cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition('* => go', [
style({'background-color': 'red', height: '100px', fontSize: '100px'}),
animate(
'1s',
style({'background-color': 'blue', height: '200px', fontSize: '200px'}),
),
]),
]),
],
standalone: false,
})
class Cmp {
exp: any = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'go';
fixture.detectChanges();
const players = getLog();
expect(players.length).toEqual(1);
expect(players[0].keyframes).toEqual([
new Map<string, string | number>([
['backgroundColor', 'red'],
['height', '100px'],
['fontSize', '100px'],
['offset', 0],
]),
new Map<string, string | number>([
['backgroundColor', 'blue'],
['height', '200px'],
['fontSize', '200px'],
['offset', 1],
]),
]);
});
it('should convert hyphenated properties to camelCase by default that are auto/pre style properties', () => {
@Component({
selector: 'cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition('* => go', [
style({'background-color': AUTO_STYLE, 'font-size': '100px'}),
animate('1s', style({'background-color': 'blue', 'font-size': PRE_STYLE})),
]),
]),
],
standalone: false,
})
class Cmp {
exp: any = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'go';
fixture.detectChanges();
const players = getLog();
expect(players.length).toEqual(1);
expect(players[0].keyframes).toEqual([
new Map<string, string | number>([
['backgroundColor', AUTO_STYLE],
['fontSize', '100px'],
['offset', 0],
]),
new Map<string, string | number>([
['backgroundColor', 'blue'],
['fontSize', PRE_STYLE],
['offset', 1],
]),
]);
});
});
it('should throw neither state() or transition() are used inside of trigger()', () => {
@Component({
selector: 'if-cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [trigger('myAnimation', [animate(1000, style({width: '100px'}))])],
standalone: false,
})
class Cmp {
exp: any = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
expect(() => {
TestBed.createComponent(Cmp);
}).toThrowError(
/only state\(\) and transition\(\) definitions can sit inside of a trigger\(\)/,
);
});
describe('animation and useAnimation functions', | {
"end_byte": 127186,
"start_byte": 119120,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_127192_135999 | {
it('should apply the delay specified in the animation', () => {
const animationMetaData = animation(
[style({color: 'red'}), animate(1000, style({color: 'green'}))],
{delay: 3000},
);
@Component({
selector: 'cmp',
template: `
<div @anim *ngIf="exp">
</div>
`,
animations: [trigger('anim', [transition(':enter', useAnimation(animationMetaData))])],
standalone: false,
})
class Cmp {
exp: boolean = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
engine.flush();
const players = getLog();
expect(players.length).toEqual(1);
const [player] = players;
expect(player.delay).toEqual(3000);
expect(player.duration).toEqual(1000);
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['color', 'red'],
['offset', 0],
]),
new Map<string, string | number>([
['color', 'green'],
['offset', 1],
]),
]);
});
it('should apply the delay specified in the animation using params', () => {
const animationMetaData = animation(
[style({color: 'red'}), animate(500, style({color: 'green'}))],
{delay: '{{animationDelay}}ms', params: {animationDelay: 5500}},
);
@Component({
selector: 'cmp',
template: `
<div @anim *ngIf="exp">
</div>
`,
animations: [trigger('anim', [transition(':enter', useAnimation(animationMetaData))])],
standalone: false,
})
class Cmp {
exp: boolean = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
engine.flush();
const players = getLog();
expect(players.length).toEqual(1);
const [player] = players;
expect(player.delay).toEqual(5500);
expect(player.duration).toEqual(500);
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['color', 'red'],
['offset', 0],
]),
new Map<string, string | number>([
['color', 'green'],
['offset', 1],
]),
]);
});
it('should apply the delay specified in the useAnimation call', () => {
const animationMetaData = animation([
style({color: 'red'}),
animate(550, style({color: 'green'})),
]);
@Component({
selector: 'cmp',
template: `
<div @anim *ngIf="exp">
</div>
`,
animations: [
trigger('anim', [transition(':enter', useAnimation(animationMetaData, {delay: 1500}))]),
],
standalone: false,
})
class Cmp {
exp: boolean = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
engine.flush();
const players = getLog();
expect(players.length).toEqual(1);
const [player] = players;
expect(player.delay).toEqual(1500);
expect(player.duration).toEqual(550);
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['color', 'red'],
['offset', 0],
]),
new Map<string, string | number>([
['color', 'green'],
['offset', 1],
]),
]);
});
it('should apply the delay specified in the useAnimation call using params', () => {
const animationMetaData = animation([
style({color: 'red'}),
animate(700, style({color: 'green'})),
]);
@Component({
selector: 'cmp',
template: `
<div @anim *ngIf="exp">
</div>
`,
animations: [
trigger('anim', [
transition(
':enter',
useAnimation(animationMetaData, {
delay: '{{useAnimationDelay}}ms',
params: {useAnimationDelay: 7500},
}),
),
]),
],
standalone: false,
})
class Cmp {
exp: boolean = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
engine.flush();
const players = getLog();
expect(players.length).toEqual(1);
const [player] = players;
expect(player.delay).toEqual(7500);
expect(player.duration).toEqual(700);
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['color', 'red'],
['offset', 0],
]),
new Map<string, string | number>([
['color', 'green'],
['offset', 1],
]),
]);
});
it('should combine the delays specified in the animation and the useAnimation with that of the caller', () => {
const animationMetaData = animation(
[style({color: 'red'}), animate(567, style({color: 'green'}))],
{delay: 1000},
);
@Component({
selector: 'cmp',
template: `
<div @anim *ngIf="exp">
</div>
`,
animations: [
trigger('anim', [
transition(':enter', useAnimation(animationMetaData, {delay: 34}), {delay: 200}),
]),
],
standalone: false,
})
class Cmp {
exp: boolean = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
engine.flush();
const players = getLog();
expect(players.length).toEqual(1);
const [player] = players;
expect(player.delay).toEqual(1234);
expect(player.duration).toEqual(567);
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['color', 'red'],
['offset', 0],
]),
new Map<string, string | number>([
['color', 'green'],
['offset', 1],
]),
]);
});
});
it('should combine multiple errors together into one exception when an animation fails to be built', () => {
@Component({
selector: 'if-cmp',
template: `
<div [@foo]="fooExp" [@bar]="barExp"></div>
`,
animations: [
trigger('foo', [
transition(':enter', []),
transition('* => *', [query('foo', animate(1000, style({background: 'red'})))]),
]),
trigger('bar', [
transition(':enter', []),
transition('* => *', [query('bar', animate(1000, style({background: 'blue'})))]),
]),
],
standalone: false,
})
class Cmp {
fooExp: any = false;
barExp: any = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
cmp.fooExp = 'go';
cmp.barExp = 'go';
let errorMsg: string = '';
try {
fixture.detectChanges();
} catch (e) {
errorMsg = (e as Error).message;
}
expect(errorMsg).toMatch(/@foo has failed due to:/);
expect(errorMsg).toMatch(/`query\("foo"\)` returned zero elements/);
expect(errorMsg).toMatch(/@bar has failed due to:/);
expect(errorMsg).toMatch(/`query\("bar"\)` returned zero elements/);
});
it('should not throw an error if styles overlap in sepa | {
"end_byte": 135999,
"start_byte": 127192,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_136005_143534 | ransitions', () => {
@Component({
selector: 'if-cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [
transition('void => *', [style({opacity: 0}), animate('0.5s 1s', style({opacity: 1}))]),
transition('* => void', [
animate(1000, style({height: 0})),
animate(1000, style({opacity: 0})),
]),
]),
],
standalone: false,
})
class Cmp {
exp: any = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
expect(() => {
TestBed.createComponent(Cmp);
}).not.toThrowError();
});
it("should add the transition provided delay to all the transition's timelines", () => {
@Component({
selector: 'cmp',
template: `
<div @parent *ngIf="exp">
<div @child *ngIf="exp"></div>
</div>
`,
animations: [
trigger('parent', [
transition(
':enter',
[
style({background: 'red'}),
group(
[
animate('1s 3s ease', style({background: 'green'})),
query('@child', animateChild()),
],
{delay: 111},
),
],
{delay: '2s'},
),
]),
trigger('child', [
transition(
':enter',
[style({color: 'white'}), animate('2s 3s ease', style({color: 'black'}))],
{delay: 222},
),
]),
],
standalone: false,
})
class Cmp {
exp: boolean = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
engine.flush();
const players = getLog();
expect(players.length).toEqual(4);
// players:
// - scp (skipped child player): player for the child animation
// - pp1 (parent player 1): player for parent animation (from background red to red)
// - pp2 (parent player 2): player for parent animation (from background red to green)
// - pcp (parent child player):
// player for child animation executed by parent via query and animateChild
const [scp, pp1, pp2, pcp] = players;
expect(scp.delay).toEqual(222);
expect(pp1.delay).toEqual(2000);
expect(pp2.delay).toEqual(2111); // 2000 + 111
expect(pcp.delay).toEqual(0); // all the delays are included in the child animation
expect(pcp.duration).toEqual(7333); // 2s + 3s + 2000 + 111 + 222
});
it('should keep (transition from/to) styles defined in different timelines', () => {
@Component({
selector: 'cmp',
template: '<div @animation *ngIf="exp"></div>',
animations: [
trigger('animation', [
transition(':enter', [
group([
style({opacity: 0, color: 'red'}),
// Note: the objective of this test is to make sure the animation
// transitions from opacity 0 and color red to opacity 1 and color blue,
// even though the two styles are defined in different timelines
animate(500, style({opacity: 1, color: 'blue'})),
]),
]),
]),
],
standalone: false,
})
class Cmp {
exp: boolean = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
engine.flush();
const players = getLog();
expect(players.length).toEqual(1);
const [player] = players;
expect(player.keyframes).toEqual([
new Map<string, string | number>([
['opacity', '0'],
['color', 'red'],
['offset', 0],
]),
new Map<string, string | number>([
['opacity', '1'],
['color', 'blue'],
['offset', 1],
]),
]);
});
describe('errors for not using the animation module', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{provide: RendererFactory2, useExisting: ɵDomRendererFactory2}],
});
});
function syntheticPropError(name: string, nameKind: string) {
return `NG05105: Unexpected synthetic ${nameKind} ${name} found. Please make sure that:
- Either \`BrowserAnimationsModule\` or \`NoopAnimationsModule\` are imported in your application.
- There is corresponding configuration for the animation named \`${name}\` defined in the \`animations\` field of the \`@Component\` decorator (see https://angular.io/api/core/Component#animations).`;
}
describe('when modules are missing', () => {
it('should throw when using an @prop binding without the animation module', () => {
@Component({
template: `<div [@myAnimation]="true"></div>`,
standalone: false,
})
class Cmp {}
TestBed.configureTestingModule({declarations: [Cmp]});
const comp = TestBed.createComponent(Cmp);
expect(() => comp.detectChanges()).toThrowError(
syntheticPropError('@myAnimation', 'property'),
);
});
it('should throw when using an @prop listener without the animation module', () => {
@Component({
template: `<div (@myAnimation.start)="a = true"></div>`,
standalone: false,
})
class Cmp {
a = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
expect(() => TestBed.createComponent(Cmp)).toThrowError(
syntheticPropError('@myAnimation.start', 'listener'),
);
});
});
describe('when modules are present, but animations are missing', () => {
it('should throw when using an @prop property, BrowserAnimationModule is imported, but there is no animation rule', () => {
@Component({
template: `<div [@myAnimation]="true"></div>`,
standalone: false,
})
class Cmp {}
TestBed.configureTestingModule({declarations: [Cmp], imports: [BrowserAnimationsModule]});
const comp = TestBed.createComponent(Cmp);
expect(() => comp.detectChanges()).toThrowError(
syntheticPropError('@myAnimation', 'property'),
);
});
it('should throw when using an @prop listener, BrowserAnimationModule is imported, but there is no animation rule', () => {
@Component({
template: `<div (@myAnimation.start)="true"></div>`,
standalone: false,
})
class Cmp {}
TestBed.configureTestingModule({declarations: [Cmp], imports: [BrowserAnimationsModule]});
expect(() => TestBed.createComponent(Cmp)).toThrowError(
syntheticPropError('@myAnimation.start', 'listener'),
);
});
});
});
describe('non-animatable css props', () => {
functio | {
"end_byte": 143534,
"start_byte": 136005,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_integration_spec.ts_143540_148457 | dAndAnimateSimpleTestComponent(triggerAnimationData: AnimationMetadata[]) {
@Component({
selector: 'cmp',
template: `
<div *ngIf="exp" [@myAnimation]="exp">
<p *ngIf="exp"></p>
</div>
`,
animations: [trigger('myAnimation', [transition('void => *', triggerAnimationData)])],
standalone: false,
})
class Cmp {
exp: any = false;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
engine.flush();
}
it('should show a warning if the animation tries to transition a non-animatable property', () => {
const spyWarn = spyOn(console, 'warn');
buildAndAnimateSimpleTestComponent([
style({display: 'block'}),
animate(500, style({display: 'inline'})),
]);
expect(spyWarn).toHaveBeenCalledOnceWith(
'Warning: The animation trigger "myAnimation" is attempting to animate the following' +
' not animatable properties: display' +
'\n' +
'(to check the list of all animatable properties visit https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties)',
);
});
it('should not show a warning if the animation tries to transition an animatable property', () => {
const spyWarn = spyOn(console, 'warn');
buildAndAnimateSimpleTestComponent([
style({fontSize: 5}),
animate(500, style({fontSize: 15})),
]);
expect(spyWarn).not.toHaveBeenCalled();
});
it('should show a single warning if the animation tries to transition multiple non-animatable properties', () => {
const spyWarn = spyOn(console, 'warn');
buildAndAnimateSimpleTestComponent([
style({display: 'block', fontStyle: 'normal'}),
animate(500, style({display: 'inline', fontStyle: 'italic'})),
]);
expect(spyWarn).toHaveBeenCalledOnceWith(
'Warning: The animation trigger "myAnimation" is attempting to animate the following' +
' not animatable properties: display, fontStyle' +
'\n' +
'(to check the list of all animatable properties visit https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties)',
);
});
it('should only warn on non-animatable properties if the animation tries to transition both animate and non-animatable properties', () => {
const spyWarn = spyOn(console, 'warn');
buildAndAnimateSimpleTestComponent([
style({'flex-direction': 'column', fontSize: 5}),
animate(500, style({'flex-direction': 'row', fontSize: 10})),
]);
expect(spyWarn).toHaveBeenCalledOnceWith(
'Warning: The animation trigger "myAnimation" is attempting to animate the following' +
' not animatable properties: flex-direction' +
'\n' +
'(to check the list of all animatable properties visit https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties)',
);
});
it('should not show a warning if the animation uses but does not animate a non-animatable property', () => {
const spyWarn = spyOn(console, 'warn');
buildAndAnimateSimpleTestComponent([transition('void => *', [style({display: 'block'})])]);
expect(spyWarn).not.toHaveBeenCalled();
});
it('should not show a warning if the same non-animatable property is used (with different values) on different elements in the same transition', () => {
const spyWarn = spyOn(console, 'warn');
buildAndAnimateSimpleTestComponent([
style({position: 'relative'}),
query(':enter', [
style({
position: 'absolute',
}),
]),
]);
expect(spyWarn).not.toHaveBeenCalled();
});
it('should not show a warning if a different easing function is used in different steps', () => {
const spyWarn = spyOn(console, 'warn');
buildAndAnimateSimpleTestComponent([
sequence([
animate('1s ease-in', style({background: 'red'})),
animate('1s ease-out', style({background: 'green'})),
]),
]);
expect(spyWarn).not.toHaveBeenCalled();
});
});
});
})();
function assertHasParent(element: any, yes: boolean) {
const parent = element.parentNode;
if (yes) {
expect(parent).toBeTruthy();
} else {
expect(parent).toBeFalsy();
}
}
function buildParams(params: {[name: string]: any}): AnimationOptions {
return {params};
}
| {
"end_byte": 148457,
"start_byte": 143540,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_integration_spec.ts"
} |
angular/packages/core/test/animation/animation_query_integration_spec.ts_0_1198 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
animate,
animateChild,
AnimationPlayer,
AUTO_STYLE,
group,
query,
sequence,
stagger,
state,
style,
transition,
trigger,
ɵAnimationGroupPlayer as AnimationGroupPlayer,
} from '@angular/animations';
import {
AnimationDriver,
ɵAnimationEngine,
ɵnormalizeKeyframes as normalizeKeyframes,
} from '@angular/animations/browser';
import {TransitionAnimationPlayer} from '@angular/animations/browser/src/render/transition_animation_engine';
import {ENTER_CLASSNAME, LEAVE_CLASSNAME} from '@angular/animations/browser/src/util';
import {MockAnimationDriver, MockAnimationPlayer} from '@angular/animations/browser/testing';
import {CommonModule} from '@angular/common';
import {Component, HostBinding, ViewChild} from '@angular/core';
import {fakeAsync, flushMicrotasks, TestBed} from '@angular/core/testing';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {HostListener} from '../../src/metadata/directives';
(function () {
| {
"end_byte": 1198,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/animation/animation_query_integration_spec.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.