_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/core/test/render3/instructions_spec.ts_1349_8937 | () => {
function createAnchor() {
ɵɵelement(0, 'a');
}
function createDiv() {
ɵɵelement(0, 'div');
}
function createScript() {
ɵɵelement(0, 'script');
}
afterEach(ViewFixture.cleanUp);
describe('ɵɵadvance', () => {
it('should error in DevMode if index is out of range', () => {
// Only one constant added, meaning only index `0` is valid.
const t = new ViewFixture({create: createDiv, decls: 1});
expect(() => {
t.update(() => {
ɵɵadvance(-1);
});
}).toThrow();
expect(() => {
t.update(() => {
ɵɵadvance();
});
}).toThrow();
});
});
describe('bind', () => {
it('should update bindings when value changes with the correct perf counters', () => {
ngDevModeResetPerfCounters();
const t = new ViewFixture({create: createAnchor, decls: 1, vars: 1});
t.update(() => {
ɵɵproperty('title', 'Hello');
});
expect(t.html).toEqual('<a title="Hello"></a>');
t.update(() => {
ɵɵproperty('title', 'World');
});
expect(t.html).toEqual('<a title="World"></a>');
expect(ngDevMode).toEqual(
jasmine.objectContaining({
firstCreatePass: 1,
tNode: 2, // 1 for hostElement + 1 for the template under test
tView: 2, // 1 for rootView + 1 for the template view
rendererCreateElement: 1,
rendererSetProperty: 2,
}),
);
});
it('should not update bindings when value does not change, with the correct perf counters', () => {
ngDevModeResetPerfCounters();
const idempotentUpdate = () => {
ɵɵproperty('title', 'Hello');
};
const t = new ViewFixture({
create: createAnchor,
update: idempotentUpdate,
decls: 1,
vars: 1,
});
t.update();
expect(t.html).toEqual('<a title="Hello"></a>');
t.update();
expect(t.html).toEqual('<a title="Hello"></a>');
expect(ngDevMode).toEqual(
jasmine.objectContaining({
firstCreatePass: 1,
tNode: 2, // 1 for hostElement + 1 for the template under test
tView: 2, // 1 for rootView + 1 for the template view
rendererCreateElement: 1,
rendererSetProperty: 1,
}),
);
});
});
describe('element', () => {
it('should create an element with the correct perf counters', () => {
ngDevModeResetPerfCounters();
const t = new ViewFixture({
create: () => {
ɵɵelement(0, 'div', 0);
},
decls: 1,
vars: 0,
consts: [['id', 'test', 'title', 'Hello']],
});
const div = (t.host as HTMLElement).querySelector('div')!;
expect(div.id).toEqual('test');
expect(div.title).toEqual('Hello');
expect(ngDevMode).toEqual(
jasmine.objectContaining({
firstCreatePass: 1,
tNode: 2, // 1 for div, 1 for host element
tView: 2, // 1 for rootView + 1 for the template view
rendererCreateElement: 1,
}),
);
});
it('should instantiate nodes at high indices', () => {
@Component({
selector: 'comp',
standalone: true,
template: '{{ name }}',
})
class Comp {
@Input() name = '';
}
const ctx = {name: 'initial name'};
const createText = () => {
// Artificially inflating the slot IDs of this app component
// to mimic an app with a very large view.
ɵɵelement(4097, 'comp');
};
const updateText = () => {
ɵɵadvance(4097);
ɵɵproperty('name', ctx.name);
};
const fixture = new ViewFixture({
create: createText,
update: updateText,
decls: 4098,
vars: 1,
directives: [Comp],
});
fixture.update();
expect(fixture.html).toEqual('<comp>initial name</comp>');
ctx.name = 'some name';
fixture.update();
expect(fixture.html).toEqual('<comp>some name</comp>');
});
});
describe('attribute', () => {
it('should use sanitizer function', () => {
ngDevModeResetPerfCounters();
const t = new ViewFixture({create: createDiv, decls: 1, vars: 1});
t.update(() => {
ɵɵattribute('title', 'javascript:true', ɵɵsanitizeUrl);
});
expect(t.html).toEqual('<div title="unsafe:javascript:true"></div>');
t.update(() => {
ɵɵattribute('title', bypassSanitizationTrustUrl('javascript:true'), ɵɵsanitizeUrl);
});
expect(t.html).toEqual('<div title="javascript:true"></div>');
expect(ngDevMode).toEqual(
jasmine.objectContaining({
firstCreatePass: 1,
tNode: 2, // 1 for div, 1 for host element
tView: 2, // 1 for rootView + 1 for the template view
rendererCreateElement: 1,
rendererSetAttribute: 2,
}),
);
});
});
describe('property', () => {
/**
* TODO: We need to replace this with an acceptance test, but for right now,
* this is the only test that ensures chaining works, since code generation
* is not producing chained instructions yet.
*/
it('should chain', () => {
ngDevModeResetPerfCounters();
// <div [title]="title" [accesskey]="key"></div>
const t = new ViewFixture({create: createDiv, update: () => {}, decls: 1, vars: 2});
t.update(() => {
ɵɵproperty('title', 'one')('accessKey', 'A');
});
expect(t.html).toEqual('<div accesskey="A" title="one"></div>');
t.update(() => {
ɵɵproperty('title', 'two')('accessKey', 'B');
});
expect(t.html).toEqual('<div accesskey="B" title="two"></div>');
expect(ngDevMode).toEqual(
jasmine.objectContaining({
firstCreatePass: 1,
tNode: 2, // 1 for div, 1 for host element
tView: 2, // 1 for rootView + 1 for the template view
rendererCreateElement: 1,
rendererSetProperty: 4,
}),
);
});
});
describe('styleProp', () => {
it('should allow values even if a bypass operation is applied', () => {
let backgroundImage: string | SafeValue = 'url("http://server")';
const t = new ViewFixture({
create: () => {
return createDiv();
},
update: () => {
ɵɵstyleProp('background-image', backgroundImage);
},
decls: 2,
vars: 2,
});
t.update();
// nothing is set because sanitizer suppresses it.
expect((t.host.firstChild as HTMLElement).style.getPropertyValue('background-image')).toEqual(
'url("http://server")',
);
backgroundImage = bypassSanitizationTrustStyle('url("http://server2")');
t.update();
expect((t.host.firstChild as HTMLElement).style.getPropertyValue('background-image')).toEqual(
'url("http://server2")',
);
});
});
describe('styleMap', () => {
const attrs = [[AttributeMarker.Styles, 'height', '10px']];
function createDivWithStyle() {
ɵɵelement(0, 'div', 0);
}
it('should add style', () => {
const fixture = new ViewFixture({
create: createDivWithStyle,
update: () => {
ɵɵstyleMap({'background-color': 'red'});
},
decls: 1,
vars: 2,
consts: attrs,
});
fixture.update();
expect(fixture.html).toEqual('<div style="background-color: red; height: 10px;"></div>');
});
});
describe('elementClass', () => {
function createDivWithStyli | {
"end_byte": 8937,
"start_byte": 1349,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/instructions_spec.ts"
} |
angular/packages/core/test/render3/instructions_spec.ts_8941_10264 | {
ɵɵelement(0, 'div');
}
it('should add class', () => {
const fixture = new ViewFixture({
create: createDivWithStyling,
update: () => {
ɵɵclassMap('multiple classes');
},
decls: 1,
vars: 2,
});
fixture.update();
const div = fixture.host.querySelector('div.multiple')!;
expect(getSortedClassName(div)).toEqual('classes multiple');
});
});
describe('performance counters', () => {
it('should create tView only once for each nested level', () => {
@Component({
selector: 'nested-loops',
standalone: true,
template: `
<ul *ngFor="let row of rows">
<li *ngFor="let col of row.cols">{{col}}</li>
</ul>
`,
imports: [CommonModule],
})
class NestedLoops {
rows = [
['a', 'b'],
['A', 'B'],
['a', 'b'],
['A', 'B'],
];
}
ngDevModeResetPerfCounters();
TestBed.createComponent(NestedLoops);
expect(ngDevMode).toEqual(
jasmine.objectContaining({
// Expect: component view + ngFor(row) + ngFor(col)
tView: 3, // should be: 3
}),
);
});
});
describe('sanitization injection compatibility', () => {
it('sho | {
"end_byte": 10264,
"start_byte": 8941,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/instructions_spec.ts"
} |
angular/packages/core/test/render3/instructions_spec.ts_10268_17662 | work for url sanitization', () => {
const s = new LocalMockSanitizer((value) => `${value}-sanitized`);
const t = new ViewFixture({create: createAnchor, decls: 1, vars: 1, sanitizer: s});
const inputValue = 'http://foo';
const outputValue = 'http://foo-sanitized';
t.update(() => {
ɵɵattribute('href', inputValue, ɵɵsanitizeUrl);
});
expect(t.html).toEqual(`<a href="${outputValue}"></a>`);
expect(s.lastSanitizedValue).toEqual(outputValue);
});
it('should bypass url sanitization if marked by the service', () => {
const s = new LocalMockSanitizer((value) => '');
const t = new ViewFixture({create: createAnchor, decls: 1, vars: 1, sanitizer: s});
const inputValue = s.bypassSecurityTrustUrl('http://foo');
const outputValue = 'http://foo';
t.update(() => {
ɵɵattribute('href', inputValue, ɵɵsanitizeUrl);
});
expect(t.html).toEqual(`<a href="${outputValue}"></a>`);
expect(s.lastSanitizedValue).toBeFalsy();
});
it('should bypass ivy-level url sanitization if a custom sanitizer is used', () => {
const s = new LocalMockSanitizer((value) => '');
const t = new ViewFixture({create: createAnchor, decls: 1, vars: 1, sanitizer: s});
const inputValue = bypassSanitizationTrustUrl('http://foo');
const outputValue = 'http://foo-ivy';
t.update(() => {
ɵɵattribute('href', inputValue, ɵɵsanitizeUrl);
});
expect(t.html).toEqual(`<a href="${outputValue}"></a>`);
expect(s.lastSanitizedValue).toBeFalsy();
});
it('should work for style sanitization', () => {
const s = new LocalMockSanitizer((value) => `color:blue`);
const t = new ViewFixture({create: createDiv, decls: 1, vars: 1, sanitizer: s});
const inputValue = 'color:red';
const outputValue = 'color:blue';
t.update(() => {
ɵɵattribute('style', inputValue, ɵɵsanitizeStyle);
});
expect(stripStyleWsCharacters(t.html)).toEqual(`<div style="${outputValue}"></div>`);
expect(s.lastSanitizedValue).toEqual(outputValue);
});
it('should bypass style sanitization if marked by the service', () => {
const s = new LocalMockSanitizer((value) => '');
const t = new ViewFixture({create: createDiv, decls: 1, vars: 1, sanitizer: s});
const inputValue = s.bypassSecurityTrustStyle('color:maroon');
const outputValue = 'color:maroon';
t.update(() => {
ɵɵattribute('style', inputValue, ɵɵsanitizeStyle);
});
expect(stripStyleWsCharacters(t.html)).toEqual(`<div style="${outputValue}"></div>`);
expect(s.lastSanitizedValue).toBeFalsy();
});
it('should bypass ivy-level style sanitization if a custom sanitizer is used', () => {
const s = new LocalMockSanitizer((value) => '');
const t = new ViewFixture({create: createDiv, decls: 1, vars: 1, sanitizer: s});
const inputValue = bypassSanitizationTrustStyle('font-family:foo');
const outputValue = 'font-family:foo-ivy';
t.update(() => {
ɵɵattribute('style', inputValue, ɵɵsanitizeStyle);
});
expect(stripStyleWsCharacters(t.html)).toEqual(`<div style="${outputValue}"></div>`);
expect(s.lastSanitizedValue).toBeFalsy();
});
it('should work for resourceUrl sanitization', () => {
const s = new LocalMockSanitizer((value) => `${value}-sanitized`);
const t = new ViewFixture({create: createScript, decls: 1, vars: 1, sanitizer: s});
const inputValue = 'http://resource';
const outputValue = 'http://resource-sanitized';
t.update(() => {
ɵɵattribute('src', inputValue, ɵɵsanitizeResourceUrl);
});
expect(t.html).toEqual(`<script src="${outputValue}"></script>`);
expect(s.lastSanitizedValue).toEqual(outputValue);
});
it('should bypass resourceUrl sanitization if marked by the service', () => {
const s = new LocalMockSanitizer((value) => '');
const t = new ViewFixture({create: createScript, decls: 1, vars: 1, sanitizer: s});
const inputValue = s.bypassSecurityTrustResourceUrl('file://all-my-secrets.pdf');
const outputValue = 'file://all-my-secrets.pdf';
t.update(() => {
ɵɵattribute('src', inputValue, ɵɵsanitizeResourceUrl);
});
expect(t.html).toEqual(`<script src="${outputValue}"></script>`);
expect(s.lastSanitizedValue).toBeFalsy();
});
it('should bypass ivy-level resourceUrl sanitization if a custom sanitizer is used', () => {
const s = new LocalMockSanitizer((value) => '');
const t = new ViewFixture({create: createScript, decls: 1, vars: 1, sanitizer: s});
const inputValue = bypassSanitizationTrustResourceUrl('file://all-my-secrets.pdf');
const outputValue = 'file://all-my-secrets.pdf-ivy';
t.update(() => {
ɵɵattribute('src', inputValue, ɵɵsanitizeResourceUrl);
});
expect(t.html).toEqual(`<script src="${outputValue}"></script>`);
expect(s.lastSanitizedValue).toBeFalsy();
});
it('should work for script sanitization', () => {
const s = new LocalMockSanitizer((value) => `${value} //sanitized`);
const t = new ViewFixture({create: createScript, decls: 1, vars: 1, sanitizer: s});
const inputValue = 'fn();';
const outputValue = 'fn(); //sanitized';
t.update(() => {
ɵɵproperty('innerHTML', inputValue, ɵɵsanitizeScript);
});
expect(t.html).toEqual(`<script>${outputValue}</script>`);
expect(s.lastSanitizedValue).toEqual(outputValue);
});
it('should bypass script sanitization if marked by the service', () => {
const s = new LocalMockSanitizer((value) => '');
const t = new ViewFixture({create: createScript, decls: 1, vars: 1, sanitizer: s});
const inputValue = s.bypassSecurityTrustScript('alert("bar")');
const outputValue = 'alert("bar")';
t.update(() => {
ɵɵproperty('innerHTML', inputValue, ɵɵsanitizeScript);
});
expect(t.html).toEqual(`<script>${outputValue}</script>`);
expect(s.lastSanitizedValue).toBeFalsy();
});
it('should bypass ivy-level script sanitization if a custom sanitizer is used', () => {
const s = new LocalMockSanitizer((value) => '');
const t = new ViewFixture({create: createScript, decls: 1, vars: 1, sanitizer: s});
const inputValue = bypassSanitizationTrustScript('alert("bar")');
const outputValue = 'alert("bar")-ivy';
t.update(() => {
ɵɵproperty('innerHTML', inputValue, ɵɵsanitizeScript);
});
expect(t.html).toEqual(`<script>${outputValue}</script>`);
expect(s.lastSanitizedValue).toBeFalsy();
});
it('should work for html sanitization', () => {
const s = new LocalMockSanitizer((value) => `${value} <!--sanitized-->`);
const t = new ViewFixture({create: createDiv, decls: 1, vars: 1, sanitizer: s});
const inputValue = '<header></header>';
const outputValue = '<header></header> <!--sanitized-->';
t.update(() => {
ɵɵproperty('innerHTML', inputValue, ɵɵsanitizeHtml);
});
expect(t.html).toEqual(`<div>${outputValue}</div>`);
expect(s.lastSanitizedValue).toEqual(outputValue);
});
it('should bypass html sanitization if marked by the service', () => {
const s = new LocalMockSanitizer((value) | {
"end_byte": 17662,
"start_byte": 10268,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/instructions_spec.ts"
} |
angular/packages/core/test/render3/instructions_spec.ts_17668_20581 | ;
const t = new ViewFixture({create: createDiv, decls: 1, vars: 1, sanitizer: s});
const inputValue = s.bypassSecurityTrustHtml('<div onclick="alert(123)"></div>');
const outputValue = '<div onclick="alert(123)"></div>';
t.update(() => {
ɵɵproperty('innerHTML', inputValue, ɵɵsanitizeHtml);
});
expect(t.html).toEqual(`<div>${outputValue}</div>`);
expect(s.lastSanitizedValue).toBeFalsy();
});
it('should bypass ivy-level script sanitization if a custom sanitizer is used', () => {
const s = new LocalMockSanitizer((value) => '');
const t = new ViewFixture({create: createDiv, decls: 1, vars: 1, sanitizer: s});
const inputValue = bypassSanitizationTrustHtml('<div onclick="alert(123)"></div>');
const outputValue = '<div onclick="alert(123)"></div>-ivy';
t.update(() => {
ɵɵproperty('innerHTML', inputValue, ɵɵsanitizeHtml);
});
expect(t.html).toEqual(`<div>${outputValue}</div>`);
expect(s.lastSanitizedValue).toBeFalsy();
});
});
});
class LocalSanitizedValue {
constructor(public value: any) {}
toString() {
return this.value;
}
}
class LocalMockSanitizer implements Sanitizer {
// using a non-null assertion because it's (re)set by sanitize()
public lastSanitizedValue!: string | null;
constructor(private _interceptor: (value: string | null | any) => string) {}
sanitize(
context: SecurityContext,
value: LocalSanitizedValue | string | null | any,
): string | null {
if (getSanitizationBypassType(value) != null) {
return unwrapSafeValue(value) + '-ivy';
}
if (value instanceof LocalSanitizedValue) {
return value.toString();
}
return (this.lastSanitizedValue = this._interceptor(value));
}
bypassSecurityTrustHtml(value: string) {
return new LocalSanitizedValue(value);
}
bypassSecurityTrustStyle(value: string) {
return new LocalSanitizedValue(value);
}
bypassSecurityTrustScript(value: string) {
return new LocalSanitizedValue(value);
}
bypassSecurityTrustUrl(value: string) {
return new LocalSanitizedValue(value);
}
bypassSecurityTrustResourceUrl(value: string) {
return new LocalSanitizedValue(value);
}
}
class MockSanitizerInterceptor {
public lastValue: string | null = null;
constructor(private _interceptorFn?: ((value: any) => any) | null) {}
sanitize(
context: SecurityContext,
value: LocalSanitizedValue | string | null | any,
): string | null {
if (this._interceptorFn) {
this._interceptorFn(value);
}
return (this.lastValue = value);
}
}
function stripStyleWsCharacters(value: string): string {
// color: blue; => color:blue
return value.replace(/;/g, '').replace(/:\s+/g, ':');
}
| {
"end_byte": 20581,
"start_byte": 17668,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/instructions_spec.ts"
} |
angular/packages/core/test/render3/testing_spec.ts_0_1529 | /**
* @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 {withBody} from '@angular/private/testing';
describe('testing', () => {
describe('withBody', () => {
let passed: boolean;
beforeEach(() => (passed = false));
afterEach(() => expect(passed).toEqual(true));
it(
'should set up body',
withBody('<span>works!</span>', () => {
expect(document.body.innerHTML).toEqual('<span>works!</span>');
passed = true;
}),
);
it(
'should support promises',
withBody('<span>works!</span>', () => {
return Promise.resolve(true).then(() => {
passed = true;
});
}),
);
it(
'should support async and await',
withBody('<span>works!</span>', async () => {
await Promise.resolve(true);
passed = true;
}),
);
});
describe('domino', () => {
it('should have document present', () => {
// In Browser this tests passes, bun we also want to make sure we pass in node.js
// We expect that node.js will load domino for us.
expect(document).toBeTruthy();
});
});
describe('requestAnimationFrame', () => {
it('should have requestAnimationFrame', (done) => {
// In Browser we have requestAnimationFrame, but verify that we also have it node.js
requestAnimationFrame(() => done());
});
});
});
| {
"end_byte": 1529,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/testing_spec.ts"
} |
angular/packages/core/test/render3/providers_spec.ts_0_8391 | /**
* @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 {TestBed} from '@angular/core/testing';
import {
Component,
createEnvironmentInjector,
ElementRef,
EnvironmentInjector,
inject,
Injectable,
InjectFlags,
InjectionToken,
NgModule,
RendererFactory2,
Type,
ViewContainerRef,
ɵɵdefineInjectable,
ɵɵdefineInjector,
ɵɵdefineNgModule,
ɵɵinject,
} from '../../src/core';
import {forwardRef} from '../../src/di/forward_ref';
import {ɵɵgetInheritedFactory} from '../../src/render3/index';
import {getInjector} from '../../src/render3/util/discovery_utils';
import {expectProvidersScenario} from './providers_helper';
describe('providers', () => {
describe('should support all types of Provider:', () => {
abstract class Greeter {
abstract greet: string;
}
const GREETER = new InjectionToken<Greeter>('greeter');
class GreeterClass implements Greeter {
greet = 'Class';
hasBeenCleanedUp = false;
ngOnDestroy() {
this.hasBeenCleanedUp = true;
}
}
class GreeterDeps implements Greeter {
constructor(public greet: string) {}
}
class GreeterBuiltInDeps implements Greeter {
public greet: string;
constructor(
private message: string,
private elementRef: ElementRef,
) {
this.greet = this.message + ' from ' + this.elementRef.nativeElement.tagName;
}
}
class GreeterProvider {
provide() {
return 'Provided';
}
}
@Injectable()
class GreeterInj implements Greeter {
public greet: string;
constructor(private provider: GreeterProvider) {
this.greet = this.provider.provide();
}
static ɵprov = ɵɵdefineInjectable({
token: GreeterInj,
factory: () => new GreeterInj(ɵɵinject(GreeterProvider as any)),
});
}
it('TypeProvider', () => {
expectProvidersScenario({
parent: {
providers: [GreeterClass],
componentAssertion: () => {
expect(inject(GreeterClass).greet).toEqual('Class');
},
},
});
});
it('ValueProvider', () => {
expectProvidersScenario({
parent: {
providers: [{provide: GREETER, useValue: {greet: 'Value'}}],
componentAssertion: () => {
expect(inject(GREETER).greet).toEqual('Value');
},
},
});
});
it('ClassProvider', () => {
expectProvidersScenario({
parent: {
providers: [{provide: GREETER, useClass: GreeterClass}],
componentAssertion: () => {
expect(inject(GREETER).greet).toEqual('Class');
},
},
});
});
it('ExistingProvider', () => {
expectProvidersScenario({
parent: {
providers: [GreeterClass, {provide: GREETER, useExisting: GreeterClass}],
componentAssertion: () => {
expect(inject(GREETER).greet).toEqual('Class');
},
},
});
});
it('FactoryProvider', () => {
expectProvidersScenario({
parent: {
providers: [GreeterClass, {provide: GREETER, useFactory: () => new GreeterClass()}],
componentAssertion: () => {
expect(inject(GREETER).greet).toEqual('Class');
},
},
});
});
const MESSAGE = new InjectionToken<string>('message');
it('ClassProvider with deps', () => {
expectProvidersScenario({
parent: {
providers: [
{provide: MESSAGE, useValue: 'Message'},
{provide: GREETER, useClass: GreeterDeps, deps: [MESSAGE]},
],
componentAssertion: () => {
expect(inject(GREETER).greet).toEqual('Message');
},
},
});
});
it('ClassProvider with built-in deps', () => {
expectProvidersScenario({
parent: {
providers: [
{provide: MESSAGE, useValue: 'Message'},
{provide: GREETER, useClass: GreeterBuiltInDeps, deps: [MESSAGE, ElementRef]},
],
componentAssertion: () => {
expect(inject(GREETER).greet).toEqual('Message from PARENT');
},
},
});
});
it('FactoryProvider with deps', () => {
expectProvidersScenario({
parent: {
providers: [
{provide: MESSAGE, useValue: 'Message'},
{provide: GREETER, useFactory: (msg: string) => new GreeterDeps(msg), deps: [MESSAGE]},
],
componentAssertion: () => {
expect(inject(GREETER).greet).toEqual('Message');
},
},
});
});
it('FactoryProvider with built-in deps', () => {
expectProvidersScenario({
parent: {
providers: [
{provide: MESSAGE, useValue: 'Message'},
{
provide: GREETER,
useFactory: (msg: string, elementRef: ElementRef) =>
new GreeterBuiltInDeps(msg, elementRef),
deps: [MESSAGE, ElementRef],
},
],
componentAssertion: () => {
expect(inject(GREETER).greet).toEqual('Message from PARENT');
},
},
});
});
it('ClassProvider with injectable', () => {
expectProvidersScenario({
parent: {
providers: [GreeterProvider, {provide: GREETER, useClass: GreeterInj}],
componentAssertion: () => {
expect(inject(GREETER).greet).toEqual('Provided');
},
},
});
});
describe('forwardRef', () => {
it('forwardRef resolves later', (done) => {
setTimeout(() => {
expectProvidersScenario({
parent: {
providers: [forwardRef(() => ForLater)],
componentAssertion: () => {
expect(inject(ForLater) instanceof ForLater).toBeTruthy();
},
},
});
done();
}, 0);
});
class ForLater {}
// The following test that forwardRefs are called, so we don't search for an anon fn
it('ValueProvider wrapped in forwardRef', () => {
expectProvidersScenario({
parent: {
providers: [
{
provide: GREETER,
useValue: forwardRef(() => {
return {greet: 'Value'};
}),
},
],
componentAssertion: () => {
expect(inject(GREETER).greet).toEqual('Value');
},
},
});
});
it('ClassProvider wrapped in forwardRef', () => {
let greeterInstance: GreeterClass | null = null;
expectProvidersScenario({
parent: {
providers: [{provide: GREETER, useClass: forwardRef(() => GreeterClass)}],
componentAssertion: () => {
greeterInstance = inject(GREETER) as GreeterClass;
expect(greeterInstance.greet).toEqual('Class');
},
},
});
expect(greeterInstance).not.toBeNull();
expect(greeterInstance!.hasBeenCleanedUp).toBe(true);
});
it('ExistingProvider wrapped in forwardRef', () => {
expectProvidersScenario({
parent: {
providers: [
GreeterClass,
{provide: GREETER, useExisting: forwardRef(() => GreeterClass)},
],
componentAssertion: () => {
expect(inject(GREETER).greet).toEqual('Class');
},
},
});
});
it('@Inject annotation wrapped in forwardRef', () => {
// @Inject(forwardRef(() => GREETER))
expectProvidersScenario({
parent: {
providers: [{provide: GREETER, useValue: {greet: 'Value'}}],
componentAssertion: () => {
expect(inject(forwardRef(() => GREETER)).greet).toEqual('Value');
},
},
});
});
});
});
/*
* All tests below assume this structure:
* ```
* <parent>
* <#VIEW#>
* <view-child>
* </view-child>
* </#VIEW#>
* <content-child>
* </content-child>
* </parent>
* ```
*/
describe('o | {
"end_byte": 8391,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/providers_spec.ts"
} |
angular/packages/core/test/render3/providers_spec.ts_8395_11281 | ide rules:', () => {
it('directiveProviders should override providers', () => {
expectProvidersScenario({
parent: {
providers: [{provide: String, useValue: 'Message 1'}],
directiveProviders: [{provide: String, useValue: 'Message 2'}],
componentAssertion: () => {
expect(inject(String)).toEqual('Message 2');
},
},
});
});
it('viewProviders should override providers', () => {
expectProvidersScenario({
parent: {
providers: [{provide: String, useValue: 'Message 1'}],
viewProviders: [{provide: String, useValue: 'Message 2'}],
componentAssertion: () => {
expect(inject(String)).toEqual('Message 2');
},
},
});
});
it('viewProviders should override directiveProviders', () => {
expectProvidersScenario({
parent: {
directiveProviders: [{provide: String, useValue: 'Message 1'}],
viewProviders: [{provide: String, useValue: 'Message 2'}],
componentAssertion: () => {
expect(inject(String)).toEqual('Message 2');
},
},
});
});
it('last declared directive should override other directives', () => {
expectProvidersScenario({
parent: {
directive2Providers: [{provide: String, useValue: 'Message 1'}],
directiveProviders: [{provide: String, useValue: 'Message 2'}],
componentAssertion: () => {
expect(inject(String)).toEqual('Message 2');
},
},
});
});
it('last provider should override previous one in component providers', () => {
expectProvidersScenario({
parent: {
providers: [
{provide: String, useValue: 'Message 1'},
{provide: String, useValue: 'Message 2'},
],
componentAssertion: () => {
expect(inject(String)).toEqual('Message 2');
},
},
});
});
it('last provider should override previous one in component view providers', () => {
expectProvidersScenario({
parent: {
viewProviders: [
{provide: String, useValue: 'Message 1'},
{provide: String, useValue: 'Message 2'},
],
componentAssertion: () => {
expect(inject(String)).toEqual('Message 2');
},
},
});
});
it('last provider should override previous one in directive providers', () => {
expectProvidersScenario({
parent: {
directiveProviders: [
{provide: String, useValue: 'Message 1'},
{provide: String, useValue: 'Message 2'},
],
componentAssertion: () => {
expect(inject(String)).toEqual('Message 2');
},
},
});
});
});
describe('s | {
"end_byte": 11281,
"start_byte": 8395,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/providers_spec.ts"
} |
angular/packages/core/test/render3/providers_spec.ts_11285_20673 | e', () => {
@NgModule({
providers: [{provide: String, useValue: 'From module'}],
})
class MyModule {}
describe('without directives', () => {
it('should work without providers nor viewProviders in component', () => {
expectProvidersScenario({
parent: {
componentAssertion: () => {
expect(inject(String)).toEqual('From module');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From module');
},
},
viewChild: {
componentAssertion: () => {
expect(inject(String)).toEqual('From module');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From module');
},
},
contentChild: {
componentAssertion: () => {
expect(inject(String)).toEqual('From module');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From module');
},
},
ngModule: MyModule,
});
});
it('should work with only providers in component', () => {
expectProvidersScenario({
parent: {
providers: [{provide: String, useValue: 'From providers'}],
componentAssertion: () => {
expect(inject(String)).toEqual('From providers');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From providers');
},
},
viewChild: {
componentAssertion: () => {
expect(inject(String)).toEqual('From providers');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From providers');
},
},
contentChild: {
componentAssertion: () => {
expect(inject(String)).toEqual('From providers');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From providers');
},
},
ngModule: MyModule,
});
});
it('should work with only viewProviders in component', () => {
expectProvidersScenario({
parent: {
viewProviders: [{provide: String, useValue: 'From viewProviders'}],
componentAssertion: () => {
expect(inject(String)).toEqual('From viewProviders');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From module');
},
},
viewChild: {
componentAssertion: () => {
expect(inject(String)).toEqual('From viewProviders');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From viewProviders');
},
},
contentChild: {
componentAssertion: () => {
expect(inject(String)).toEqual('From module');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From module');
},
},
ngModule: MyModule,
});
});
it('should work with both providers and viewProviders in component', () => {
expectProvidersScenario({
parent: {
providers: [{provide: String, useValue: 'From providers'}],
viewProviders: [{provide: String, useValue: 'From viewProviders'}],
componentAssertion: () => {
expect(inject(String)).toEqual('From viewProviders');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From providers');
},
},
viewChild: {
componentAssertion: () => {
expect(inject(String)).toEqual('From viewProviders');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From viewProviders');
},
},
contentChild: {
componentAssertion: () => {
expect(inject(String)).toEqual('From providers');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From providers');
},
},
ngModule: MyModule,
});
});
});
describe('with directives (order in ɵcmp.directives matters)', () => {
it('should work without providers nor viewProviders in component', () => {
expectProvidersScenario({
parent: {
directiveProviders: [{provide: String, useValue: 'From directive'}],
directive2Providers: [{provide: String, useValue: 'Never'}],
componentAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
},
viewChild: {
componentAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
},
contentChild: {
componentAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
},
ngModule: MyModule,
});
});
it('should work with only providers in component', () => {
expectProvidersScenario({
parent: {
providers: [{provide: String, useValue: 'From providers'}],
directiveProviders: [{provide: String, useValue: 'From directive'}],
directive2Providers: [{provide: String, useValue: 'Never'}],
componentAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
},
viewChild: {
componentAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
},
contentChild: {
componentAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
},
ngModule: MyModule,
});
});
it('should work with only viewProviders in component', () => {
expectProvidersScenario({
parent: {
viewProviders: [{provide: String, useValue: 'From viewProviders'}],
directiveProviders: [{provide: String, useValue: 'From directive'}],
directive2Providers: [{provide: String, useValue: 'Never'}],
componentAssertion: () => {
expect(inject(String)).toEqual('From viewProviders');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
},
viewChild: {
componentAssertion: () => {
expect(inject(String)).toEqual('From viewProviders');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From viewProviders');
},
},
contentChild: {
componentAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
},
ngModule: MyModule,
});
});
it('should work with both providers and viewProviders in component', () => {
expectProvidersScenario({
parent: {
providers: [{provide: String, useValue: 'From providers'}],
viewProviders: [{provide: String, useValue: 'From viewProviders'}],
directiveProviders: [{provide: String, useValue: 'From directive'}],
directive2Providers: [{provide: String, useValue: 'Never'}],
componentAssertion: () => {
expect(inject(String)).toEqual('From viewProviders');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
},
viewChild: {
componentAssertion: () => {
expect(inject(String)).toEqual('From viewProviders');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From viewProviders');
},
},
contentChild: {
componentAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
directiveAssertion: () => {
expect(inject(String)).toEqual('From directive');
},
},
ngModule: MyModule,
});
});
});
});
describe('mu | {
"end_byte": 20673,
"start_byte": 11285,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/providers_spec.ts"
} |
angular/packages/core/test/render3/providers_spec.ts_20677_25263 | , () => {
@NgModule({
providers: [{provide: String, useValue: 'From module', multi: true}],
})
class MyModule {}
describe('without directives', () => {
it('should work without providers nor viewProviders in component', () => {
expectProvidersScenario({
parent: {
componentAssertion: () => {
expect(inject(String)).toEqual(['From module']);
},
directiveAssertion: () => {
expect(inject(String)).toEqual(['From module']);
},
},
viewChild: {
componentAssertion: () => {
expect(inject(String)).toEqual(['From module']);
},
directiveAssertion: () => {
expect(inject(String)).toEqual(['From module']);
},
},
contentChild: {
componentAssertion: () => {
expect(inject(String)).toEqual(['From module']);
},
directiveAssertion: () => {
expect(inject(String)).toEqual(['From module']);
},
},
ngModule: MyModule,
});
});
it('should work with only providers in component', () => {
expectProvidersScenario({
parent: {
providers: [{provide: String, useValue: 'From providers', multi: true}],
componentAssertion: () => {
expect(inject(String)).toEqual(['From providers']);
},
directiveAssertion: () => {
expect(inject(String)).toEqual(['From providers']);
},
},
viewChild: {
componentAssertion: () => {
expect(inject(String)).toEqual(['From providers']);
},
directiveAssertion: () => {
expect(inject(String)).toEqual(['From providers']);
},
},
contentChild: {
componentAssertion: () => {
expect(inject(String)).toEqual(['From providers']);
},
directiveAssertion: () => {
expect(inject(String)).toEqual(['From providers']);
},
},
ngModule: MyModule,
});
});
it('should work with only viewProviders in component', () => {
expectProvidersScenario({
parent: {
viewProviders: [{provide: String, useValue: 'From viewProviders', multi: true}],
componentAssertion: () => {
expect(inject(String)).toEqual(['From viewProviders']);
},
directiveAssertion: () => {
expect(inject(String)).toEqual(['From module']);
},
},
viewChild: {
componentAssertion: () => {
expect(inject(String)).toEqual(['From viewProviders']);
},
directiveAssertion: () => {
expect(inject(String)).toEqual(['From viewProviders']);
},
},
contentChild: {
componentAssertion: () => {
expect(inject(String)).toEqual(['From module']);
},
directiveAssertion: () => {
expect(inject(String)).toEqual(['From module']);
},
},
ngModule: MyModule,
});
});
it('should work with both providers and viewProviders in component', () => {
expectProvidersScenario({
parent: {
providers: [{provide: String, useValue: 'From providers', multi: true}],
viewProviders: [{provide: String, useValue: 'From viewProviders', multi: true}],
componentAssertion: () => {
expect(inject(String)).toEqual(['From providers', 'From viewProviders']);
},
directiveAssertion: () => {
expect(inject(String)).toEqual(['From providers']);
},
},
viewChild: {
componentAssertion: () => {
expect(inject(String)).toEqual(['From providers', 'From viewProviders']);
},
directiveAssertion: () => {
expect(inject(String)).toEqual(['From providers', 'From viewProviders']);
},
},
contentChild: {
componentAssertion: () => {
expect(inject(String)).toEqual(['From providers']);
},
directiveAssertion: () => {
expect(inject(String)).toEqual(['From providers']);
},
},
ngModule: MyModule,
});
});
});
describe(' | {
"end_byte": 25263,
"start_byte": 20677,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/providers_spec.ts"
} |
angular/packages/core/test/render3/providers_spec.ts_25269_33541 | irectives (order in ɵcmp.directives matters)', () => {
it('should work without providers nor viewProviders in component', () => {
expectProvidersScenario({
parent: {
directiveProviders: [{provide: String, useValue: 'From directive 1', multi: true}],
directive2Providers: [{provide: String, useValue: 'From directive 2', multi: true}],
componentAssertion: () => {
expect(inject(String)).toEqual(['From directive 2', 'From directive 1']);
},
directiveAssertion: () => {
expect(inject(String)).toEqual(['From directive 2', 'From directive 1']);
},
},
viewChild: {
componentAssertion: () => {
expect(inject(String)).toEqual(['From directive 2', 'From directive 1']);
},
directiveAssertion: () => {
expect(inject(String)).toEqual(['From directive 2', 'From directive 1']);
},
},
contentChild: {
componentAssertion: () => {
expect(inject(String)).toEqual(['From directive 2', 'From directive 1']);
},
directiveAssertion: () => {
expect(inject(String)).toEqual(['From directive 2', 'From directive 1']);
},
},
ngModule: MyModule,
});
});
it('should work with only providers in component', () => {
expectProvidersScenario({
parent: {
providers: [{provide: String, useValue: 'From providers', multi: true}],
directiveProviders: [{provide: String, useValue: 'From directive 1', multi: true}],
directive2Providers: [{provide: String, useValue: 'From directive 2', multi: true}],
componentAssertion: () => {
expect(inject(String)).toEqual([
'From providers',
'From directive 2',
'From directive 1',
]);
},
directiveAssertion: () => {
expect(inject(String)).toEqual([
'From providers',
'From directive 2',
'From directive 1',
]);
},
},
viewChild: {
componentAssertion: () => {
expect(inject(String)).toEqual([
'From providers',
'From directive 2',
'From directive 1',
]);
},
directiveAssertion: () => {
expect(inject(String)).toEqual([
'From providers',
'From directive 2',
'From directive 1',
]);
},
},
contentChild: {
componentAssertion: () => {
expect(inject(String)).toEqual([
'From providers',
'From directive 2',
'From directive 1',
]);
},
directiveAssertion: () => {
expect(inject(String)).toEqual([
'From providers',
'From directive 2',
'From directive 1',
]);
},
},
ngModule: MyModule,
});
});
it('should work with only viewProviders in component', () => {
expectProvidersScenario({
parent: {
viewProviders: [{provide: String, useValue: 'From viewProviders', multi: true}],
directiveProviders: [{provide: String, useValue: 'From directive 1', multi: true}],
directive2Providers: [{provide: String, useValue: 'From directive 2', multi: true}],
componentAssertion: () => {
expect(inject(String)).toEqual([
'From viewProviders',
'From directive 2',
'From directive 1',
]);
},
directiveAssertion: () => {
expect(inject(String)).toEqual(['From directive 2', 'From directive 1']);
},
},
viewChild: {
componentAssertion: () => {
expect(inject(String)).toEqual([
'From viewProviders',
'From directive 2',
'From directive 1',
]);
},
directiveAssertion: () => {
expect(inject(String)).toEqual([
'From viewProviders',
'From directive 2',
'From directive 1',
]);
},
},
contentChild: {
componentAssertion: () => {
expect(inject(String)).toEqual(['From directive 2', 'From directive 1']);
},
directiveAssertion: () => {
expect(inject(String)).toEqual(['From directive 2', 'From directive 1']);
},
},
ngModule: MyModule,
});
});
it('should work with both providers and viewProviders in component', () => {
expectProvidersScenario({
parent: {
providers: [{provide: String, useValue: 'From providers', multi: true}],
viewProviders: [{provide: String, useValue: 'From viewProviders', multi: true}],
directiveProviders: [{provide: String, useValue: 'From directive 1', multi: true}],
directive2Providers: [{provide: String, useValue: 'From directive 2', multi: true}],
componentAssertion: () => {
expect(inject(String)).toEqual([
'From providers',
'From viewProviders',
'From directive 2',
'From directive 1',
]);
},
directiveAssertion: () => {
expect(inject(String)).toEqual([
'From providers',
'From directive 2',
'From directive 1',
]);
},
},
viewChild: {
componentAssertion: () => {
expect(inject(String)).toEqual([
'From providers',
'From viewProviders',
'From directive 2',
'From directive 1',
]);
},
directiveAssertion: () => {
expect(inject(String)).toEqual([
'From providers',
'From viewProviders',
'From directive 2',
'From directive 1',
]);
},
},
contentChild: {
componentAssertion: () => {
expect(inject(String)).toEqual([
'From providers',
'From directive 2',
'From directive 1',
]);
},
directiveAssertion: () => {
expect(inject(String)).toEqual([
'From providers',
'From directive 2',
'From directive 1',
]);
},
},
ngModule: MyModule,
});
});
});
});
describe('tree-shakable injectables', () => {
it('should work with root', () => {
@Injectable({providedIn: 'root'})
class FooForRoot {
static ɵprov = ɵɵdefineInjectable({
token: FooForRoot,
factory: () => new FooForRoot(),
providedIn: 'root',
});
}
expectProvidersScenario({
parent: {
componentAssertion: () => {
expect(inject(FooForRoot) instanceof FooForRoot).toBeTruthy();
},
},
});
});
it('should work with a module', () => {
@NgModule({
providers: [{provide: String, useValue: 'From module'}],
})
class MyModule {}
@Injectable({providedIn: MyModule})
class FooForModule {
static ɵprov = ɵɵdefineInjectable({
token: FooForModule,
factory: () => new FooForModule(),
providedIn: MyModule,
});
}
expectProvidersScenario({
parent: {
componentAssertion: () => {
expect(inject(FooForModule) instanceof FooForModule).toBeTruthy();
},
},
ngModule: MyModule,
});
});
});
describe('- dynamic | {
"end_byte": 33541,
"start_byte": 25269,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/providers_spec.ts"
} |
angular/packages/core/test/render3/providers_spec.ts_33545_40542 | ponents dependency resolution', () => {
let hostComponent: HostComponent | null = null;
@Component({
standalone: true,
template: `{{s}}`,
selector: 'embedded-cmp',
})
class EmbeddedComponent {
constructor(private s: String) {}
}
@Component({
standalone: true,
selector: 'host-cmp',
template: `foo`,
providers: [{provide: String, useValue: 'From host component'}],
})
class HostComponent {
constructor(public vcref: ViewContainerRef) {
hostComponent = this;
}
}
@Component({
standalone: true,
imports: [HostComponent],
template: `<host-cmp></host-cmp>`,
providers: [{provide: String, useValue: 'From app component'}],
})
class AppComponent {
constructor() {}
}
afterEach(() => (hostComponent = null));
it('should not cross the root view boundary, and use the root view injector', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('<host-cmp>foo</host-cmp><!--container-->');
hostComponent!.vcref.createComponent(EmbeddedComponent, {
injector: {
get: (token: any, notFoundValue?: any) => {
return token === String ? 'From custom root view injector' : notFoundValue;
},
},
});
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual(
'<host-cmp>foo</host-cmp><embedded-cmp>From custom root view injector</embedded-cmp><!--container-->',
);
});
it('should not cross the root view boundary, and use the module injector if no root view injector', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('<host-cmp>foo</host-cmp><!--container-->');
const environmentInjector = createEnvironmentInjector(
[{provide: String, useValue: 'From module injector'}],
TestBed.get(EnvironmentInjector),
);
hostComponent!.vcref.createComponent(EmbeddedComponent, {
injector: {get: (token: any, notFoundValue?: any) => notFoundValue},
environmentInjector: environmentInjector,
});
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual(
'<host-cmp>foo</host-cmp><embedded-cmp>From module injector</embedded-cmp><!--container-->',
);
});
it('should cross the root view boundary to the parent of the host, thanks to the default root view injector', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('<host-cmp>foo</host-cmp><!--container-->');
hostComponent!.vcref.createComponent(EmbeddedComponent);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual(
'<host-cmp>foo</host-cmp><embedded-cmp>From app component</embedded-cmp><!--container-->',
);
});
});
describe('deps boundary:', () => {
it('the deps of a token declared in providers should not be resolved with tokens from viewProviders', () => {
@Injectable()
class MyService {
constructor(public value: String) {}
}
expectProvidersScenario({
parent: {
providers: [MyService, {provide: String, useValue: 'providers'}],
viewProviders: [{provide: String, useValue: 'viewProviders'}],
componentAssertion: () => {
expect(inject(String)).toEqual('viewProviders');
expect(inject(MyService).value).toEqual('providers');
},
},
});
});
it('should make sure that parent service does not see overrides in child directives', () => {
@Injectable()
class Greeter {
constructor(public greeting: String) {}
}
expectProvidersScenario({
parent: {
providers: [Greeter, {provide: String, useValue: 'parent'}],
},
viewChild: {
providers: [{provide: String, useValue: 'view'}],
componentAssertion: () => {
expect(inject(Greeter).greeting).toEqual('parent');
},
},
});
});
});
describe('injection flags', () => {
@NgModule({
providers: [{provide: String, useValue: 'Module'}],
})
class MyModule {}
it('should not fall through to ModuleInjector if flags limit the scope', () => {
expectProvidersScenario({
ngModule: MyModule,
parent: {
componentAssertion: () => {
expect(inject(String)).toEqual('Module');
expect(inject(String, InjectFlags.Optional | InjectFlags.Self)).toBeNull();
expect(inject(String, InjectFlags.Optional | InjectFlags.Host)).toBeNull();
},
},
});
});
});
describe('from a node without injector', () => {
abstract class Some {
abstract location: String;
}
@Injectable()
class SomeInj implements Some {
constructor(public location: String) {}
}
@Component({
standalone: true,
selector: 'my-cmp',
template: `<p></p>`,
providers: [{provide: String, useValue: 'From my component'}],
viewProviders: [{provide: Number, useValue: 123}],
})
class MyComponent {}
@Component({
standalone: true,
imports: [MyComponent],
template: `<my-cmp></my-cmp>`,
providers: [
{provide: String, useValue: 'From app component'},
{provide: Some, useClass: SomeInj},
],
})
class AppComponent {}
it('should work from within the template', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('<my-cmp><p></p></my-cmp>');
const p = fixture.nativeElement.querySelector('p');
const injector = getInjector(p);
expect(injector.get(Number)).toEqual(123);
expect(injector.get(String)).toEqual('From my component');
expect(injector.get(Some).location).toEqual('From app component');
});
it('should work from the host of the component', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('<my-cmp><p></p></my-cmp>');
const myCmp = fixture.nativeElement.querySelector('my-cmp');
const injector = getInjector(myCmp as any);
expect(injector.get(Number)).toEqual(123);
expect(injector.get(String)).toEqual('From my component');
expect(injector.get(Some).location).toEqual('From app component');
});
});
// Note: these tests check the behavior of `getInheritedFactory` specifically.
// Since `getInheritedFactory` is only generated in AOT, the tests can't be
// ported directly to TestBed while running in JIT mode.
describe('getInherit | {
"end_byte": 40542,
"start_byte": 33545,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/providers_spec.ts"
} |
angular/packages/core/test/render3/providers_spec.ts_40545_44167 | actory on class with custom decorator', () => {
function addFoo() {
return (constructor: Type<any>): any => {
const decoratedClass = class Extender extends constructor {
foo = 'bar';
};
return decoratedClass;
};
}
it('should find the correct factories if a parent class has a custom decorator', () => {
class GrandParent {
static ɵfac = function GrandParent_Factory() {};
}
@addFoo()
class Parent extends GrandParent {
static override ɵfac = function Parent_Factory() {};
}
class Child extends Parent {
static override ɵfac = function Child_Factory() {};
}
expect(ɵɵgetInheritedFactory(Child).name).toBe('Parent_Factory');
expect(ɵɵgetInheritedFactory(Parent).name).toBe('GrandParent_Factory');
expect(ɵɵgetInheritedFactory(GrandParent).name).toBeFalsy();
});
it('should find the correct factories if a child class has a custom decorator', () => {
class GrandParent {
static ɵfac = function GrandParent_Factory() {};
}
class Parent extends GrandParent {
static override ɵfac = function Parent_Factory() {};
}
@addFoo()
class Child extends Parent {
static override ɵfac = function Child_Factory() {};
}
expect(ɵɵgetInheritedFactory(Child).name).toBe('Parent_Factory');
expect(ɵɵgetInheritedFactory(Parent).name).toBe('GrandParent_Factory');
expect(ɵɵgetInheritedFactory(GrandParent).name).toBeFalsy();
});
it('should find the correct factories if a grandparent class has a custom decorator', () => {
@addFoo()
class GrandParent {
static ɵfac = function GrandParent_Factory() {};
}
class Parent extends GrandParent {
static override ɵfac = function Parent_Factory() {};
}
class Child extends Parent {
static override ɵfac = function Child_Factory() {};
}
expect(ɵɵgetInheritedFactory(Child).name).toBe('Parent_Factory');
expect(ɵɵgetInheritedFactory(Parent).name).toBe('GrandParent_Factory');
expect(ɵɵgetInheritedFactory(GrandParent).name).toBeFalsy();
});
it('should find the correct factories if all classes have a custom decorator', () => {
@addFoo()
class GrandParent {
static ɵfac = function GrandParent_Factory() {};
}
@addFoo()
class Parent extends GrandParent {
static override ɵfac = function Parent_Factory() {};
}
@addFoo()
class Child extends Parent {
static override ɵfac = function Child_Factory() {};
}
expect(ɵɵgetInheritedFactory(Child).name).toBe('Parent_Factory');
expect(ɵɵgetInheritedFactory(Parent).name).toBe('GrandParent_Factory');
expect(ɵɵgetInheritedFactory(GrandParent).name).toBeFalsy();
});
it('should find the correct factories if parent and grandparent classes have a custom decorator', () => {
@addFoo()
class GrandParent {
static ɵfac = function GrandParent_Factory() {};
}
@addFoo()
class Parent extends GrandParent {
static override ɵfac = function Parent_Factory() {};
}
class Child extends Parent {
static override ɵfac = function Child_Factory() {};
}
expect(ɵɵgetInheritedFactory(Child).name).toBe('Parent_Factory');
expect(ɵɵgetInheritedFactory(Parent).name).toBe('GrandParent_Factory');
expect(ɵɵgetInheritedFactory(GrandParent).name).toBeFalsy();
});
});
});
| {
"end_byte": 44167,
"start_byte": 40545,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/providers_spec.ts"
} |
angular/packages/core/test/render3/reactive_safety_spec.ts_0_7223 | /**
* @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,
ComponentFactoryResolver,
createComponent,
createEnvironmentInjector,
effect,
ENVIRONMENT_INITIALIZER,
EnvironmentInjector,
EventEmitter,
inject,
Injectable,
InjectionToken,
NgModule,
Output,
TemplateRef,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import {getActiveConsumer} from '@angular/core/primitives/signals';
import {createInjector} from '@angular/core/src/di/create_injector';
import {setUseMicrotaskEffectsByDefault} from '@angular/core/src/render3/reactivity/effect';
import {TestBed} from '@angular/core/testing';
/*
* Contains tests which validate that certain actions within the framework (for example, creating
* new views) are automatically "untracked" when started in a reactive context.
*/
describe('reactive safety', () => {
let prev: boolean;
beforeEach(() => {
prev = setUseMicrotaskEffectsByDefault(false);
});
afterEach(() => setUseMicrotaskEffectsByDefault(prev));
describe('view creation', () => {
it('should be safe to call ViewContainerRef.createEmbeddedView', () => {
@Component({
standalone: true,
template: `<ng-template #tmpl>Template</ng-template>`,
})
class TestCmp {
vcr = inject(ViewContainerRef);
@ViewChild('tmpl', {read: TemplateRef}) tmpl!: TemplateRef<unknown>;
}
const fix = TestBed.createComponent(TestCmp);
fix.detectChanges();
const cmp = fix.componentInstance;
expectNotToThrowInReactiveContext(() => cmp.vcr.createEmbeddedView(cmp.tmpl));
});
it('should be safe to call TemplateRef.create', () => {
@Component({
standalone: true,
template: `<ng-template #tmpl>Template</ng-template>`,
})
class TestCmp {
@ViewChild('tmpl', {read: TemplateRef}) tmpl!: TemplateRef<unknown>;
}
const fix = TestBed.createComponent(TestCmp);
fix.detectChanges();
const cmp = fix.componentInstance;
expectNotToThrowInReactiveContext(() => cmp.tmpl.createEmbeddedView(cmp.tmpl));
});
it('should be safe to call createComponent', () => {
@Component({
standalone: true,
template: '',
})
class TestCmp {
constructor() {
expect(getActiveConsumer()).toBe(null);
}
}
const environmentInjector = TestBed.inject(EnvironmentInjector);
expectNotToThrowInReactiveContext(() => createComponent(TestCmp, {environmentInjector}));
});
it('should be safe to call ComponentFactory.create()', () => {
@Component({
standalone: true,
template: '',
})
class TestCmp {
constructor() {
expect(getActiveConsumer()).toBe(null);
}
}
const injector = TestBed.inject(EnvironmentInjector);
const resolver = TestBed.inject(ComponentFactoryResolver);
const factory = resolver.resolveComponentFactory(TestCmp);
expectNotToThrowInReactiveContext(() => factory.create(injector));
});
it('should be safe to flip @if to true', () => {
@Component({
standalone: true,
template: `
@if (cond) {
(creating this view should not throw)
}
`,
})
class TestCmp {
cond = false;
}
const fix = TestBed.createComponent(TestCmp);
fix.detectChanges();
expectNotToThrowInReactiveContext(() => {
fix.componentInstance.cond = true;
fix.detectChanges();
});
});
});
describe('view destruction', () => {
it('should be safe to destroy a ComponentRef', () => {
@Component({
standalone: true,
template: '',
})
class HostCmp {
vcr = inject(ViewContainerRef);
}
@Component({
standalone: true,
template: '',
})
class GuestCmp {
ngOnDestroy(): void {
expect(getActiveConsumer()).toBe(null);
}
}
const fix = TestBed.createComponent(HostCmp);
const guest = fix.componentInstance.vcr.createComponent(GuestCmp);
fix.detectChanges();
expectNotToThrowInReactiveContext(() => expect(() => guest.destroy()));
});
});
describe('dependency injection', () => {
it('should be safe to inject a provided service', () => {
@Injectable()
class Service {
constructor() {
expect(getActiveConsumer()).toBe(null);
}
}
const injector = createEnvironmentInjector([Service], TestBed.inject(EnvironmentInjector));
expectNotToThrowInReactiveContext(() => injector.get(Service));
});
it('should be safe to inject a token provided with a factory', () => {
const token = new InjectionToken<string>('');
const injector = createEnvironmentInjector(
[
{
provide: token,
useFactory: () => {
expect(getActiveConsumer()).toBe(null);
return '';
},
},
],
TestBed.inject(EnvironmentInjector),
);
expectNotToThrowInReactiveContext(() => injector.get(token));
});
it('should be safe to use an ENVIRONMENT_INITIALIZER', () => {
expectNotToThrowInReactiveContext(() =>
createEnvironmentInjector(
[
{
provide: ENVIRONMENT_INITIALIZER,
useValue: () => expect(getActiveConsumer()).toBe(null),
multi: true,
},
],
TestBed.inject(EnvironmentInjector),
),
);
});
it('should be safe to use an NgModule initializer', () => {
@NgModule({})
class TestModule {
constructor() {
expect(getActiveConsumer()).toBe(null);
}
}
expectNotToThrowInReactiveContext(() =>
createInjector(TestModule, TestBed.inject(EnvironmentInjector)),
);
});
it('should be safe to destroy an injector', () => {
@Injectable()
class Service {
ngOnDestroy(): void {
expect(getActiveConsumer()).toBe(null);
}
}
const injector = createEnvironmentInjector([Service], TestBed.inject(EnvironmentInjector));
injector.get(Service);
expectNotToThrowInReactiveContext(() => injector.destroy());
});
});
describe('outputs', () => {
it('should be safe to emit an output', () => {
@Component({
standalone: true,
template: '',
})
class TestCmp {
@Output() output = new EventEmitter<string>();
}
const cmp = TestBed.createComponent(TestCmp).componentInstance;
cmp.output.subscribe(() => {
expect(getActiveConsumer()).toBe(null);
});
expectNotToThrowInReactiveContext(() => cmp.output.emit(''));
});
});
});
function expectNotToThrowInReactiveContext(fn: () => void): void {
const injector = TestBed.inject(EnvironmentInjector);
effect(
() => {
expect(fn).not.toThrow();
},
{injector},
);
TestBed.flushEffects();
}
| {
"end_byte": 7223,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/reactive_safety_spec.ts"
} |
angular/packages/core/test/render3/utils.ts_0_3948 | /**
* @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
*/
/** Template string function that can be used to strip indentation from a given string literal. */
export function dedent(strings: TemplateStringsArray, ...values: any[]) {
let joinedString = '';
for (let i = 0; i < values.length; i++) {
joinedString += `${strings[i]}${values[i]}`;
}
joinedString += strings[strings.length - 1];
const lines = joinedString.split('\n');
while (isBlank(lines[0])) {
lines.shift();
}
while (isBlank(lines[lines.length - 1])) {
lines.pop();
}
let minWhitespacePrefix = lines.reduce(
(min, line) => Math.min(min, numOfWhiteSpaceLeadingChars(line)),
Number.MAX_SAFE_INTEGER,
);
return lines.map((line) => line.substring(minWhitespacePrefix)).join('\n');
}
/**
* Tests to see if the line is blank.
*
* A blank line is such which contains only whitespace.
* @param text string to test for blank-ness.
*/
function isBlank(text: string): boolean {
return /^\s*$/.test(text);
}
/**
* Returns number of whitespace leading characters.
*
* @param text
*/
function numOfWhiteSpaceLeadingChars(text: string): number {
return text.match(/^\s*/)![0].length;
}
/**
* Jasmine AsymmetricMatcher which can be used to assert `.debug` properties.
*
* ```
* expect(obj).toEqual({
* create: matchDebug('someValue')
* })
* ```
*
* In the above example it will assert that `obj.create.debug === 'someValue'`.
*
* @param expected Expected value.
*/
export function matchDebug<T>(expected: T): any {
const matcher = function () {};
let actual: any = matchDebug;
matcher.asymmetricMatch = function (objectWithDebug: any, matchersUtil: jasmine.MatchersUtil) {
return matchersUtil.equals((actual = objectWithDebug.debug), expected);
};
matcher.jasmineToString = function (pp: (value: any) => string) {
if (actual === matchDebug) {
// `asymmetricMatch` never got called hence no error to display
return '';
}
return buildFailureMessage(actual, expected, pp);
};
return matcher;
}
export function buildFailureMessage(
actual: any,
expected: any,
pp: (value: any) => string,
): string {
const diffs: string[] = [];
listPropertyDifferences(diffs, '', actual, expected, 5, pp);
return '\n ' + diffs.join('\n ');
}
function listPropertyDifferences(
diffs: string[],
path: string,
actual: any,
expected: any,
depth: number,
pp: (value: any) => string,
) {
if (actual === expected) return;
if (typeof actual !== typeof expected) {
diffs.push(`${path}: Expected ${pp(actual)} to be ${pp(expected)}`);
} else if (depth && Array.isArray(expected)) {
if (!Array.isArray(actual)) {
diffs.push(`${path}: Expected ${pp(expected)} but was ${pp(actual)}`);
} else {
const maxLength = Math.max(actual.length, expected.length);
listPropertyDifferences(
diffs,
path + '.length',
expected.length,
actual.length,
depth - 1,
pp,
);
for (let i = 0; i < maxLength; i++) {
const actualItem = actual[i];
const expectedItem = expected[i];
listPropertyDifferences(
diffs,
path + '[' + i + ']',
actualItem,
expectedItem,
depth - 1,
pp,
);
}
}
} else if (
depth &&
expected &&
typeof expected === 'object' &&
actual &&
typeof actual === 'object'
) {
new Set(Object.keys(expected).concat(Object.keys(actual))).forEach((key) => {
const actualItem = actual[key];
const expectedItem = expected[key];
listPropertyDifferences(diffs, path + '.' + key, actualItem, expectedItem, depth - 1, pp);
});
} else {
diffs.push(`${path}: Expected ${pp(actual)} to be ${pp(expected)}`);
}
}
| {
"end_byte": 3948,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/utils.ts"
} |
angular/packages/core/test/render3/change_detection_spec.ts_0_1340 | /**
* @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 {TestBed} from '@angular/core/testing';
import {withBody} from '@angular/private/testing';
import {Component, RendererFactory2} from '../../src/core';
describe('change detection', () => {
it(
'should call begin and end when the renderer factory implements them',
withBody('<my-comp></my-comp>', () => {
const log: string[] = [];
@Component({
selector: 'my-comp',
standalone: true,
template: '{{ value }}',
})
class MyComponent {
get value(): string {
log.push('detect changes');
return 'works';
}
}
const rendererFactory = TestBed.inject(RendererFactory2);
rendererFactory.begin = () => log.push('begin');
rendererFactory.end = () => log.push('end');
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual('works');
expect(log).toEqual([
'begin',
'detect changes', // regular change detection cycle
'end',
'detect changes', // check no changes cycle
]);
}),
);
});
| {
"end_byte": 1340,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/change_detection_spec.ts"
} |
angular/packages/core/test/render3/reactivity_spec.ts_0_1264 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {AsyncPipe} from '@angular/common';
import {
AfterViewInit,
ApplicationRef,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
computed,
ContentChildren,
createComponent,
createEnvironmentInjector,
destroyPlatform,
Directive,
effect,
EnvironmentInjector,
ErrorHandler,
inject,
Injectable,
Injector,
Input,
NgZone,
OnChanges,
provideExperimentalZonelessChangeDetection,
QueryList,
signal,
SimpleChanges,
TemplateRef,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import {SIGNAL} from '@angular/core/primitives/signals';
import {takeUntilDestroyed, toObservable} from '@angular/core/rxjs-interop';
import {createInjector} from '@angular/core/src/di/create_injector';
import {
EffectNode,
setUseMicrotaskEffectsByDefault,
} from '@angular/core/src/render3/reactivity/effect';
import {TestBed} from '@angular/core/testing';
import {bootstrapApplication} from '@angular/platform-browser';
import {withBody} from '@angular/private/testing';
import {filter, firstValueFrom, map} from 'rxjs'; | {
"end_byte": 1264,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/reactivity_spec.ts"
} |
angular/packages/core/test/render3/reactivity_spec.ts_1266_9943 | describe('reactivity', () => {
let prev: boolean;
beforeEach(() => {
prev = setUseMicrotaskEffectsByDefault(false);
});
afterEach(() => setUseMicrotaskEffectsByDefault(prev));
describe('effects', () => {
beforeEach(destroyPlatform);
afterEach(destroyPlatform);
it(
'should run effects in the zone in which they get created',
withBody('<test-cmp></test-cmp>', async () => {
const log: string[] = [];
@Component({
selector: 'test-cmp',
standalone: true,
template: '',
})
class Cmp {
constructor(ngZone: NgZone) {
effect(() => {
log.push(Zone.current.name);
});
ngZone.runOutsideAngular(() => {
effect(() => {
log.push(Zone.current.name);
});
});
}
}
await bootstrapApplication(Cmp);
expect(log).not.toEqual(['angular', 'angular']);
}),
);
it('should contribute to application stableness when an effect is pending', async () => {
const someSignal = signal('initial');
const appRef = TestBed.inject(ApplicationRef);
const isStable: boolean[] = [];
const sub = appRef.isStable.subscribe((stable) => isStable.push(stable));
expect(isStable).toEqual([true]);
TestBed.runInInjectionContext(() => effect(() => someSignal()));
expect(isStable).toEqual([true, false]);
appRef.tick();
expect(isStable).toEqual([true, false, true]);
});
it('should propagate errors to the ErrorHandler', () => {
TestBed.configureTestingModule({
providers: [{provide: ErrorHandler, useFactory: () => new FakeErrorHandler()}],
rethrowApplicationErrors: false,
});
let run = false;
let lastError: any = null;
class FakeErrorHandler extends ErrorHandler {
override handleError(error: any): void {
lastError = error;
}
}
const appRef = TestBed.inject(ApplicationRef);
effect(
() => {
run = true;
throw new Error('fail!');
},
{injector: appRef.injector},
);
appRef.tick();
expect(run).toBeTrue();
expect(lastError.message).toBe('fail!');
});
// Disabled while we consider whether this actually makes sense.
// This test _used_ to show that `effect()` was usable inside component error handlers, partly
// because effect errors used to report to component error handlers. Now, effect errors are
// always reported to the top-level error handler, which has never been able to use `effect()`
// as `effect()` depends transitively on `ApplicationRef` which depends circularly on
// `ErrorHandler`.
xit('should be usable inside an ErrorHandler', async () => {
const shouldError = signal(false);
let lastError: any = null;
class FakeErrorHandler extends ErrorHandler {
constructor() {
super();
effect(() => {
if (shouldError()) {
throw new Error('fail!');
}
});
}
override handleError(error: any): void {
lastError = error;
}
}
TestBed.configureTestingModule({
providers: [{provide: ErrorHandler, useClass: FakeErrorHandler}],
rethrowApplicationErrors: false,
});
const appRef = TestBed.inject(ApplicationRef);
expect(() => appRef.tick()).not.toThrow();
shouldError.set(true);
expect(() => appRef.tick()).not.toThrow();
expect(lastError?.message).toBe('fail!');
});
it('should run effect cleanup function on destroy', async () => {
let counterLog: number[] = [];
let cleanupCount = 0;
@Component({
selector: 'test-cmp',
standalone: true,
template: '',
})
class Cmp {
counter = signal(0);
effectRef = effect((onCleanup) => {
counterLog.push(this.counter());
onCleanup(() => {
cleanupCount++;
});
});
}
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
await fixture.whenStable();
expect(counterLog).toEqual([0]);
// initially an effect runs but the default cleanup function is noop
expect(cleanupCount).toBe(0);
fixture.componentInstance.counter.set(5);
fixture.detectChanges();
await fixture.whenStable();
expect(counterLog).toEqual([0, 5]);
expect(cleanupCount).toBe(1);
fixture.destroy();
expect(counterLog).toEqual([0, 5]);
expect(cleanupCount).toBe(2);
});
it('should run effects created in ngAfterViewInit', () => {
let didRun = false;
@Component({
selector: 'test-cmp',
standalone: true,
template: '',
})
class Cmp implements AfterViewInit {
injector = inject(Injector);
ngAfterViewInit(): void {
effect(
() => {
didRun = true;
},
{injector: this.injector},
);
}
}
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
expect(didRun).toBeTrue();
});
it('should create root effects when outside of a component, using injection context', () => {
TestBed.configureTestingModule({});
const counter = signal(0);
const log: number[] = [];
TestBed.runInInjectionContext(() => effect(() => log.push(counter())));
TestBed.flushEffects();
expect(log).toEqual([0]);
counter.set(1);
TestBed.flushEffects();
expect(log).toEqual([0, 1]);
});
it('should create root effects when outside of a component, using an injector', () => {
TestBed.configureTestingModule({});
const counter = signal(0);
const log: number[] = [];
effect(() => log.push(counter()), {injector: TestBed.inject(Injector)});
TestBed.flushEffects();
expect(log).toEqual([0]);
counter.set(1);
TestBed.flushEffects();
expect(log).toEqual([0, 1]);
});
it('should create root effects inside a component when specified', () => {
TestBed.configureTestingModule({});
const counter = signal(0);
const log: number[] = [];
@Component({
standalone: true,
template: '',
})
class TestCmp {
constructor() {
effect(() => log.push(counter()), {forceRoot: true});
}
}
// Running this creates the effect. Note: we never CD this component.
TestBed.createComponent(TestCmp);
TestBed.flushEffects();
expect(log).toEqual([0]);
counter.set(1);
TestBed.flushEffects();
expect(log).toEqual([0, 1]);
});
it('should check components made dirty from markForCheck() from an effect', async () => {
TestBed.configureTestingModule({
providers: [provideExperimentalZonelessChangeDetection()],
});
const source = signal('');
@Component({
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: '{{ data }}',
})
class TestCmp {
cdr = inject(ChangeDetectorRef);
data = '';
effectRef = effect(() => {
if (this.data !== source()) {
this.data = source();
this.cdr.markForCheck();
}
});
}
const fix = TestBed.createComponent(TestCmp);
await fix.whenStable();
source.set('test');
await fix.whenStable();
expect(fix.nativeElement.innerHTML).toBe('test');
});
it('should check components made dirty from markForCheck() from an effect in a service', async () => {
TestBed.configureTestingModule({
providers: [provideExperimentalZonelessChangeDetection()],
});
const source = signal('');
@Injectable()
class Service {
data = '';
cdr = inject(ChangeDetectorRef);
effectRef = effect(() => {
if (this.data !== source()) {
this.data = source();
this.cdr.markForCheck();
}
});
}
@Component({
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [Service],
template: '{{ service.data }}',
})
class TestCmp {
service = inject(Service);
}
const fix = TestBed.createComponent(TestCmp);
await fix.whenStable();
source.set('test');
await fix.whenStable();
expect(fix.nativeElement.innerHTML).toBe('test');
}); | {
"end_byte": 9943,
"start_byte": 1266,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/reactivity_spec.ts"
} |
angular/packages/core/test/render3/reactivity_spec.ts_9949_13665 | it('should check views made dirty from markForCheck() from an effect in a directive', async () => {
TestBed.configureTestingModule({
providers: [provideExperimentalZonelessChangeDetection()],
});
const source = signal('');
@Directive({
standalone: true,
selector: '[dir]',
})
class Dir {
tpl = inject(TemplateRef);
vcr = inject(ViewContainerRef);
cdr = inject(ChangeDetectorRef);
ctx = {
$implicit: '',
};
ref = this.vcr.createEmbeddedView(this.tpl, this.ctx);
effectRef = effect(() => {
if (this.ctx.$implicit !== source()) {
this.ctx.$implicit = source();
this.cdr.markForCheck();
}
});
}
@Component({
standalone: true,
imports: [Dir],
template: `<ng-template dir let-data>{{data}}</ng-template>`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
class TestCmp {}
const fix = TestBed.createComponent(TestCmp);
await fix.whenStable();
source.set('test');
await fix.whenStable();
expect(fix.nativeElement.innerHTML).toContain('test');
});
describe('destruction', () => {
it('should still destroy root effects with the DestroyRef of the component', () => {
TestBed.configureTestingModule({});
const counter = signal(0);
const log: number[] = [];
@Component({
standalone: true,
template: '',
})
class TestCmp {
constructor() {
effect(() => log.push(counter()), {forceRoot: true});
}
}
const fix = TestBed.createComponent(TestCmp);
TestBed.flushEffects();
expect(log).toEqual([0]);
// Destroy the effect.
fix.destroy();
counter.set(1);
TestBed.flushEffects();
expect(log).toEqual([0]);
});
it('should destroy effects when the parent component is destroyed', () => {
let destroyed = false;
@Component({
standalone: true,
})
class TestCmp {
constructor() {
effect((onCleanup) => onCleanup(() => (destroyed = true)));
}
}
const fix = TestBed.createComponent(TestCmp);
fix.detectChanges();
fix.destroy();
expect(destroyed).toBeTrue();
});
it('should destroy effects when their view is destroyed, separately from DestroyRef', () => {
let destroyed = false;
@Component({
standalone: true,
})
class TestCmp {
readonly injector = Injector.create({providers: [], parent: inject(Injector)});
constructor() {
effect((onCleanup) => onCleanup(() => (destroyed = true)), {injector: this.injector});
}
}
const fix = TestBed.createComponent(TestCmp);
fix.detectChanges();
fix.destroy();
expect(destroyed).toBeTrue();
});
it('should destroy effects when their DestroyRef is separately destroyed', () => {
let destroyed = false;
@Component({
standalone: true,
})
class TestCmp {
readonly injector = Injector.create({providers: [], parent: inject(Injector)});
constructor() {
effect((onCleanup) => onCleanup(() => (destroyed = true)), {injector: this.injector});
}
}
const fix = TestBed.createComponent(TestCmp);
fix.detectChanges();
(fix.componentInstance.injector as Injector & {destroy(): void}).destroy();
expect(destroyed).toBeTrue();
});
});
}); | {
"end_byte": 13665,
"start_byte": 9949,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/reactivity_spec.ts"
} |
angular/packages/core/test/render3/reactivity_spec.ts_13669_19856 | describe('safeguards', () => {
it('should allow writing to signals within effects', () => {
const counter = signal(0);
effect(() => counter.set(1), {injector: TestBed.inject(Injector)});
TestBed.flushEffects();
expect(counter()).toBe(1);
});
it('should allow writing to signals in ngOnChanges', () => {
@Component({
selector: 'with-input',
standalone: true,
template: '{{inSignal()}}',
})
class WithInput implements OnChanges {
inSignal = signal<string | undefined>(undefined);
@Input() in: string | undefined;
ngOnChanges(changes: SimpleChanges): void {
if (changes['in']) {
this.inSignal.set(changes['in'].currentValue);
}
}
}
@Component({
selector: 'test-cmp',
standalone: true,
imports: [WithInput],
template: `<with-input [in]="'A'" />|<with-input [in]="'B'" />`,
})
class Cmp {}
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('A|B');
});
it('should allow writing to signals in a constructor', () => {
@Component({
selector: 'with-constructor',
standalone: true,
template: '{{state()}}',
})
class WithConstructor {
state = signal('property initializer');
constructor() {
this.state.set('constructor');
}
}
@Component({
selector: 'test-cmp',
standalone: true,
imports: [WithConstructor],
template: `<with-constructor />`,
})
class Cmp {}
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('constructor');
});
it('should allow writing to signals in input setters', () => {
@Component({
selector: 'with-input-setter',
standalone: true,
template: '{{state()}}',
})
class WithInputSetter {
state = signal('property initializer');
@Input()
set testInput(newValue: string) {
this.state.set(newValue);
}
}
@Component({
selector: 'test-cmp',
standalone: true,
imports: [WithInputSetter],
template: `
<with-input-setter [testInput]="'binding'" />|<with-input-setter testInput="static" />
`,
})
class Cmp {}
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('binding|static');
});
it('should allow writing to signals in query result setters', () => {
@Component({
selector: 'with-query',
standalone: true,
template: '{{items().length}}',
})
class WithQuery {
items = signal<unknown[]>([]);
@ContentChildren('item')
set itemsQuery(result: QueryList<unknown>) {
this.items.set(result.toArray());
}
}
@Component({
selector: 'test-cmp',
standalone: true,
imports: [WithQuery],
template: `<with-query><div #item></div></with-query>`,
})
class Cmp {}
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('1');
});
it('should not execute query setters in the reactive context', () => {
const state = signal('initial');
@Component({
selector: 'with-query-setter',
standalone: true,
template: '<div #el></div>',
})
class WithQuerySetter {
el: unknown;
@ViewChild('el', {static: true})
set elQuery(result: unknown) {
// read a signal in a setter - I want to verify that framework executes this code outside of
// the reactive context
state();
this.el = result;
}
}
@Component({
selector: 'test-cmp',
standalone: true,
template: ``,
})
class Cmp {
noOfCmpCreated = 0;
constructor(environmentInjector: EnvironmentInjector) {
// A slightly artificial setup where a component instance is created using imperative APIs.
// We don't have control over the timing / reactive context of such API calls so need to
// code defensively in the framework.
// Here we want to specifically verify that an effect is _not_ re-run if a signal read
// happens in a query setter of a dynamically created component.
effect(() => {
createComponent(WithQuerySetter, {environmentInjector});
this.noOfCmpCreated++;
});
}
}
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
expect(fixture.componentInstance.noOfCmpCreated).toBe(1);
state.set('changed');
fixture.detectChanges();
expect(fixture.componentInstance.noOfCmpCreated).toBe(1);
});
it('should allow toObservable subscription in template (with async pipe)', () => {
@Component({
selector: 'test-cmp',
standalone: true,
imports: [AsyncPipe],
template: '{{counter$ | async}}',
})
class Cmp {
counter$ = toObservable(signal(0));
}
const fixture = TestBed.createComponent(Cmp);
expect(() => fixture.detectChanges(true)).not.toThrow();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('0');
});
it('should assign a debugName to the underlying node for an effect', async () => {
@Component({
selector: 'test-cmp',
standalone: true,
template: '',
})
class Cmp {
effectRef = effect(() => {}, {debugName: 'TEST_DEBUG_NAME'});
}
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
const component = fixture.componentInstance;
const effectRef = component.effectRef as unknown as {[SIGNAL]: EffectNode};
expect(effectRef[SIGNAL].debugName).toBe('TEST_DEBUG_NAME');
}); | {
"end_byte": 19856,
"start_byte": 13669,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/reactivity_spec.ts"
} |
angular/packages/core/test/render3/reactivity_spec.ts_19862_25868 | describe('effects created in components should first run after ngOnInit', () => {
it('when created during bootstrapping', () => {
let log: string[] = [];
@Component({
standalone: true,
selector: 'test-cmp',
template: '',
})
class TestCmp {
constructor() {
effect(() => log.push('effect'));
}
ngOnInit(): void {
log.push('init');
}
}
const fixture = TestBed.createComponent(TestCmp);
TestBed.flushEffects();
expect(log).toEqual([]);
fixture.detectChanges();
expect(log).toEqual(['init', 'effect']);
});
it('when created during change detection', () => {
let log: string[] = [];
@Component({
standalone: true,
selector: 'test-cmp',
template: '',
})
class TestCmp {
ngOnInitRan = false;
constructor() {
effect(() => log.push('effect'));
}
ngOnInit(): void {
log.push('init');
}
}
@Component({
standalone: true,
selector: 'driver-cmp',
imports: [TestCmp],
template: `
@if (cond) {
<test-cmp />
}
`,
})
class DriverCmp {
cond = false;
}
const fixture = TestBed.createComponent(DriverCmp);
fixture.detectChanges();
expect(log).toEqual([]);
// Toggle the @if, which should create and run the effect.
fixture.componentInstance.cond = true;
fixture.detectChanges();
expect(log).toEqual(['init', 'effect']);
});
it('when created dynamically', () => {
let log: string[] = [];
@Component({
standalone: true,
selector: 'test-cmp',
template: '',
})
class TestCmp {
ngOnInitRan = false;
constructor() {
effect(() => log.push('effect'));
}
ngOnInit(): void {
log.push('init');
}
}
@Component({
standalone: true,
selector: 'driver-cmp',
template: '',
})
class DriverCmp {
vcr = inject(ViewContainerRef);
}
const fixture = TestBed.createComponent(DriverCmp);
fixture.detectChanges();
fixture.componentInstance.vcr.createComponent(TestCmp);
// Verify that simply creating the component didn't schedule the effect.
TestBed.flushEffects();
expect(log).toEqual([]);
// Running change detection should schedule and run the effect.
fixture.detectChanges();
expect(log).toEqual(['init', 'effect']);
});
it('when created in a service provided in a component', () => {
let log: string[] = [];
@Injectable()
class EffectService {
constructor() {
effect(() => log.push('effect'));
}
}
@Component({
standalone: true,
selector: 'test-cmp',
template: '',
providers: [EffectService],
})
class TestCmp {
svc = inject(EffectService);
ngOnInit(): void {
log.push('init');
}
}
const fixture = TestBed.createComponent(TestCmp);
TestBed.flushEffects();
expect(log).toEqual([]);
fixture.detectChanges();
expect(log).toEqual(['init', 'effect']);
});
it('if multiple effects are created', () => {
let log: string[] = [];
@Component({
standalone: true,
selector: 'test-cmp',
template: '',
})
class TestCmp {
constructor() {
effect(() => log.push('effect a'));
effect(() => log.push('effect b'));
effect(() => log.push('effect c'));
}
ngOnInit(): void {
log.push('init');
}
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(log[0]).toBe('init');
expect(log).toContain('effect a');
expect(log).toContain('effect b');
expect(log).toContain('effect c');
});
});
describe('should disallow creating an effect context', () => {
it('inside template effect', () => {
@Component({
standalone: false,
template: '{{someFn()}}',
})
class Cmp {
someFn() {
effect(() => {});
}
}
const fixture = TestBed.createComponent(Cmp);
expect(() => fixture.detectChanges(true)).toThrowError(
/effect\(\) cannot be called from within a reactive context./,
);
});
it('inside computed', () => {
expect(() => {
computed(() => {
effect(() => {});
})();
}).toThrowError(/effect\(\) cannot be called from within a reactive context./);
});
it('inside an effect', () => {
@Component({
standalone: false,
template: '',
})
class Cmp {
constructor() {
effect(() => {
this.someFnThatWillCreateAnEffect();
});
}
someFnThatWillCreateAnEffect() {
effect(() => {});
}
}
TestBed.configureTestingModule({
providers: [
{
provide: ErrorHandler,
useClass: class extends ErrorHandler {
override handleError(e: Error) {
throw e;
}
},
},
],
});
const fixture = TestBed.createComponent(Cmp);
expect(() => fixture.detectChanges()).toThrowError(
/effect\(\) cannot be called from within a reactive context./,
);
});
});
});
}); | {
"end_byte": 25868,
"start_byte": 19862,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/reactivity_spec.ts"
} |
angular/packages/core/test/render3/imported_renderer2.ts_0_2035 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {PLATFORM_BROWSER_ID, PLATFORM_SERVER_ID} from '@angular/common/src/platform_id';
import {NgZone, RendererFactory2, RendererType2} from '@angular/core';
import {NoopNgZone} from '@angular/core/src/zone/ng_zone';
import {EventManager, ɵDomRendererFactory2, ɵSharedStylesHost} from '@angular/platform-browser';
import {EventManagerPlugin} from '@angular/platform-browser/src/dom/events/event_manager';
export class SimpleDomEventsPlugin extends EventManagerPlugin {
constructor(doc: any) {
super(doc);
}
override supports(eventName: string): boolean {
return true;
}
override addEventListener(element: HTMLElement, eventName: string, handler: Function): Function {
let callback: EventListener = handler as EventListener;
element.addEventListener(eventName, callback, false);
return () => this.removeEventListener(element, eventName, callback);
}
removeEventListener(target: any, eventName: string, callback: Function): void {
return target.removeEventListener.apply(target, [eventName, callback, false]);
}
}
export function getRendererFactory2(document: any): RendererFactory2 {
const fakeNgZone: NgZone = new NoopNgZone();
const eventManager = new EventManager([new SimpleDomEventsPlugin(document)], fakeNgZone);
const appId = 'appid';
const rendererFactory = new ɵDomRendererFactory2(
eventManager,
new ɵSharedStylesHost(document, appId),
appId,
true,
document,
isNode ? PLATFORM_SERVER_ID : PLATFORM_BROWSER_ID,
fakeNgZone,
);
const origCreateRenderer = rendererFactory.createRenderer;
rendererFactory.createRenderer = function (element: any, type: RendererType2 | null) {
const renderer = origCreateRenderer.call(this, element, type);
renderer.destroyNode = () => {};
return renderer;
};
return rendererFactory;
}
| {
"end_byte": 2035,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/imported_renderer2.ts"
} |
angular/packages/core/test/render3/view_utils_spec.ts_0_986 | /**
* @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 {createLContainer, createTNode} from '@angular/core/src/render3/instructions/shared';
import {isLContainer, isLView} from '@angular/core/src/render3/interfaces/type_checks';
import {ViewFixture} from './view_fixture';
describe('view_utils', () => {
it('should verify unwrap methods (isLView and isLContainer)', () => {
const viewFixture = new ViewFixture();
const tNode = createTNode(null!, null, 3, 0, 'div', []);
const lContainer = createLContainer(
viewFixture.lView,
viewFixture.lView,
viewFixture.host,
tNode,
);
expect(isLView(viewFixture.lView)).toBe(true);
expect(isLView(lContainer)).toBe(false);
expect(isLContainer(viewFixture.lView)).toBe(false);
expect(isLContainer(lContainer)).toBe(true);
});
});
| {
"end_byte": 986,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/view_utils_spec.ts"
} |
angular/packages/core/test/render3/list_reconciliation_spec.ts_0_2288 | /**
* @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 {LiveCollection, reconcile} from '@angular/core/src/render3/list_reconciliation';
import {assertDefined} from '@angular/core/src/util/assert';
interface ItemAdapter<T, V> {
create(index: number, value: V): T;
update(item: T, index: number, value: V): void;
unwrap(item: T): V;
}
class NoopItemFactory<T, V> implements ItemAdapter<T, V> {
create(index: number, value: V): T {
return value as any as T;
}
update(item: T, index: number, value: V): void {}
unwrap(item: T): V {
return item as any as V;
}
}
class LoggingLiveCollection<T, V> extends LiveCollection<T, V> {
operations = {
at: 0,
key: 0,
};
private logs: any[][] = [];
constructor(
private arr: T[],
private itemFactory: ItemAdapter<T, V> = new NoopItemFactory<T, V>(),
) {
super();
}
get length(): number {
return this.arr.length;
}
override at(index: number): V {
return this.itemFactory.unwrap(this.getItem(index));
}
override attach(index: number, item: T): void {
this.logs.push(['attach', index, item]);
this.arr.splice(index, 0, item);
}
override detach(index: number): T {
const item = this.getItem(index);
this.logs.push(['detach', index, item]);
this.arr.splice(index, 1);
return item;
}
override create(index: number, value: V): T {
this.logs.push(['create', index, value]);
return this.itemFactory.create(index, value);
}
override destroy(item: T): void {
this.logs.push(['destroy', item]);
}
override updateValue(index: number, value: V): void {
this.itemFactory.update(this.getItem(index), index, value);
}
getCollection() {
return this.arr;
}
getLogs() {
return this.logs;
}
clearLogs() {
this.logs = [];
}
private getItem(index: number): T {
this.operations.at++;
const item = this.arr.at(index);
assertDefined(item, `Invalid index ${index} - item was undefined`);
return item;
}
}
function trackByIdentity<T>(index: number, item: T) {
return item;
}
function trackByIndex<T>(index: number) {
return index;
} | {
"end_byte": 2288,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/list_reconciliation_spec.ts"
} |
angular/packages/core/test/render3/list_reconciliation_spec.ts_2290_8603 | describe('list reconciliation', () => {
describe('fast path', () => {
it('should do nothing if 2 lists are the same', () => {
const pc = new LoggingLiveCollection(['a', 'b', 'c']);
reconcile(pc, ['a', 'b', 'c'], trackByIdentity);
expect(pc.getCollection()).toEqual(['a', 'b', 'c']);
expect(pc.getLogs()).toEqual([]);
});
it('should add items at the end', () => {
const pc = new LoggingLiveCollection(['a', 'b']);
reconcile(pc, ['a', 'b', 'c'], trackByIdentity);
expect(pc.getCollection()).toEqual(['a', 'b', 'c']);
expect(pc.getLogs()).toEqual([
['create', 2, 'c'],
['attach', 2, 'c'],
]);
});
it('should swap items', () => {
const pc = new LoggingLiveCollection(['a', 'b', 'c']);
reconcile(pc, ['c', 'b', 'a'], trackByIdentity);
expect(pc.getCollection()).toEqual(['c', 'b', 'a']);
// TODO: think of expressing as swap
expect(pc.getLogs()).toEqual([
['detach', 2, 'c'],
['detach', 0, 'a'],
['attach', 0, 'c'],
['attach', 2, 'a'],
]);
});
it('should should optimally swap adjacent items', () => {
const pc = new LoggingLiveCollection(['a', 'b']);
reconcile(pc, ['b', 'a'], trackByIdentity);
expect(pc.getCollection()).toEqual(['b', 'a']);
expect(pc.getLogs()).toEqual([
['detach', 1, 'b'],
['attach', 0, 'b'],
]);
});
it('should detect moves to the front', () => {
const pc = new LoggingLiveCollection(['a', 'b', 'c', 'd']);
reconcile(pc, ['a', 'd', 'b', 'c'], trackByIdentity);
expect(pc.getCollection()).toEqual(['a', 'd', 'b', 'c']);
expect(pc.getLogs()).toEqual([
['detach', 3, 'd'],
['attach', 1, 'd'],
]);
});
it('should delete items in the middle', () => {
const pc = new LoggingLiveCollection(['a', 'x', 'b', 'c']);
reconcile(pc, ['a', 'b', 'c'], trackByIdentity);
expect(pc.getCollection()).toEqual(['a', 'b', 'c']);
expect(pc.getLogs()).toEqual([
['detach', 1, 'x'],
['destroy', 'x'],
]);
});
it('should delete items from the beginning', () => {
const pc = new LoggingLiveCollection(['a', 'b', 'c']);
reconcile(pc, ['c'], trackByIdentity);
expect(pc.getCollection()).toEqual(['c']);
expect(pc.getLogs()).toEqual([
['detach', 1, 'b'],
['destroy', 'b'],
['detach', 0, 'a'],
['destroy', 'a'],
]);
});
it('should delete items from the end', () => {
const pc = new LoggingLiveCollection(['a', 'b', 'c']);
reconcile(pc, ['a'], trackByIdentity);
expect(pc.getCollection()).toEqual(['a']);
expect(pc.getLogs()).toEqual([
['detach', 2, 'c'],
['destroy', 'c'],
['detach', 1, 'b'],
['destroy', 'b'],
]);
});
it('should work with duplicated items', () => {
const pc = new LoggingLiveCollection(['a', 'a', 'a']);
reconcile(pc, ['a', 'a', 'a'], trackByIdentity);
expect(pc.getCollection()).toEqual(['a', 'a', 'a']);
expect(pc.getLogs()).toEqual([]);
});
});
describe('slow path', () => {
it('should delete multiple items from the middle', () => {
const pc = new LoggingLiveCollection(['a', 'x1', 'b', 'x2', 'c']);
reconcile(pc, ['a', 'b', 'c'], trackByIdentity);
expect(pc.getCollection()).toEqual(['a', 'b', 'c']);
expect(pc.getLogs()).toEqual([
['detach', 1, 'x1'],
['detach', 2, 'x2'],
['destroy', 'x2'],
['destroy', 'x1'],
]);
});
it('should add multiple items in the middle', () => {
const pc = new LoggingLiveCollection(['a', 'b', 'c']);
reconcile(pc, ['a', 'n1', 'b', 'n2', 'c'], trackByIdentity);
expect(pc.getCollection()).toEqual(['a', 'n1', 'b', 'n2', 'c']);
expect(pc.getLogs()).toEqual([
['create', 1, 'n1'],
['attach', 1, 'n1'],
['create', 3, 'n2'],
['attach', 3, 'n2'],
]);
});
it('should go back to the fast path when start / end is different', () => {
const pc = new LoggingLiveCollection(['s1', 'a', 'b', 'c', 'e1']);
reconcile(pc, ['s2', 'a', 'b', 'c', 'e2'], trackByIdentity);
expect(pc.getCollection()).toEqual(['s2', 'a', 'b', 'c', 'e2']);
expect(pc.getLogs()).toEqual([
// item gets created at index 0 since we know it is not in the old array
['create', 0, 's2'],
['attach', 0, 's2'],
// item at index 1 gets detached since it is not part of the new collection
['detach', 1, 's1'],
// we are on the fast path again, skipping 'a', 'b', 'c'
// item gets created at index 4 since we know it is not in the old array
['create', 4, 'e2'],
['attach', 4, 'e2'],
// the rest gets detached / destroyed
['detach', 5, 'e1'],
['destroy', 'e1'],
['destroy', 's1'],
]);
});
it('should detect moves to the back', () => {
const pc = new LoggingLiveCollection(['a', 'b', 'c', 'd']);
reconcile(pc, ['b', 'c', 'n1', 'n2', 'n3', 'a', 'd'], trackByIdentity);
expect(pc.getCollection()).toEqual(['b', 'c', 'n1', 'n2', 'n3', 'a', 'd']);
expect(pc.getLogs()).toEqual([
['detach', 0, 'a'],
['create', 2, 'n1'],
['attach', 2, 'n1'],
['create', 3, 'n2'],
['attach', 3, 'n2'],
['create', 4, 'n3'],
['attach', 4, 'n3'],
['attach', 5, 'a'],
]);
});
it('should create / reuse duplicated items as needed', () => {
const trackByKey = (idx: number, item: {k: number}) => item.k;
const pc = new LoggingLiveCollection<{k: number}, {k: number}>([
{k: 1},
{k: 1},
{k: 2},
{k: 3},
]);
reconcile(pc, [{k: 2}, {k: 3}, {k: 1}, {k: 1}, {k: 1}, {k: 4}], trackByKey);
expect(pc.getCollection()).toEqual([{k: 2}, {k: 3}, {k: 1}, {k: 1}, {k: 1}, {k: 4}]);
expect(pc.getLogs()).toEqual([
['detach', 0, {k: 1}],
['detach', 0, {k: 1}],
['attach', 2, {k: 1}],
['attach', 3, {k: 1}],
['create', 4, {k: 1}],
['attach', 4, {k: 1}],
['create', 5, {k: 4}],
['attach', 5, {k: 4}],
]);
});
}); | {
"end_byte": 8603,
"start_byte": 2290,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/list_reconciliation_spec.ts"
} |
angular/packages/core/test/render3/list_reconciliation_spec.ts_8607_11358 | describe('iterables', () => {
it('should do nothing if 2 lists represented as iterables are the same', () => {
const pc = new LoggingLiveCollection(['a', 'b', 'c']);
reconcile(pc, new Set(['a', 'b', 'c']), trackByIdentity);
expect(pc.getCollection()).toEqual(['a', 'b', 'c']);
expect(pc.getLogs()).toEqual([]);
});
it('should add items at the end', () => {
const pc = new LoggingLiveCollection(['a', 'b']);
reconcile(pc, new Set(['a', 'b', 'c']), trackByIdentity);
expect(pc.getCollection()).toEqual(['a', 'b', 'c']);
expect(pc.getLogs()).toEqual([
['create', 2, 'c'],
['attach', 2, 'c'],
]);
});
it('should add multiple items in the middle', () => {
const pc = new LoggingLiveCollection(['a', 'b', 'c']);
reconcile(pc, new Set(['a', 'n1', 'b', 'n2', 'c']), trackByIdentity);
expect(pc.getCollection()).toEqual(['a', 'n1', 'b', 'n2', 'c']);
expect(pc.getLogs()).toEqual([
['create', 1, 'n1'],
['attach', 1, 'n1'],
['create', 3, 'n2'],
['attach', 3, 'n2'],
]);
});
it('should delete items from the end', () => {
const pc = new LoggingLiveCollection(['a', 'b', 'c']);
reconcile(pc, new Set(['a']), trackByIdentity);
expect(pc.getCollection()).toEqual(['a']);
expect(pc.getLogs()).toEqual([
['detach', 2, 'c'],
['destroy', 'c'],
['detach', 1, 'b'],
['destroy', 'b'],
]);
});
it('should detect (slow) moves to the front', () => {
const pc = new LoggingLiveCollection(['a', 'b', 'c', 'd']);
reconcile(pc, new Set(['a', 'd', 'b', 'c']), trackByIdentity);
expect(pc.getCollection()).toEqual(['a', 'd', 'b', 'c']);
expect(pc.getLogs()).toEqual([
['detach', 1, 'b'],
['detach', 1, 'c'],
['attach', 2, 'b'],
['attach', 3, 'c'],
]);
});
it('should detect (fast) moves to the back', () => {
const pc = new LoggingLiveCollection(['a', 'b', 'c', 'd']);
reconcile(pc, new Set(['b', 'c', 'a', 'd']), trackByIdentity);
expect(pc.getCollection()).toEqual(['b', 'c', 'a', 'd']);
expect(pc.getLogs()).toEqual([
['detach', 0, 'a'],
['attach', 2, 'a'],
]);
});
it('should allow switching collection types', () => {
const pc = new LoggingLiveCollection(['a', 'b', 'c']);
reconcile(pc, new Set(['a', 'b', 'c']), trackByIdentity);
expect(pc.getCollection()).toEqual(['a', 'b', 'c']);
expect(pc.getLogs()).toEqual([]);
reconcile(pc, ['a', 'b', 'c'], trackByIdentity);
expect(pc.getCollection()).toEqual(['a', 'b', 'c']);
expect(pc.getLogs()).toEqual([]);
});
}); | {
"end_byte": 11358,
"start_byte": 8607,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/list_reconciliation_spec.ts"
} |
angular/packages/core/test/render3/list_reconciliation_spec.ts_11362_15450 | describe('identity and index update', () => {
interface KeyValueItem<K, V> {
k: K;
v: V;
}
interface RepeaterLikeItem<T> {
index: number;
implicit: T;
}
class RepeaterLikeItemFactory<T> implements ItemAdapter<RepeaterLikeItem<T>, T> {
keySequence = 0;
create(index: number, value: T): RepeaterLikeItem<T> {
return {index: index, implicit: value};
}
update(item: RepeaterLikeItem<T>, index: number, value: T): void {
item.index = index;
item.implicit = value;
}
unwrap(item: RepeaterLikeItem<T>): T {
return item.implicit;
}
}
function trackByKey<K, V>(index: number, item: KeyValueItem<K, V>) {
return item.k;
}
it('should update when tracking by index - fast path from the start', () => {
const pc = new LoggingLiveCollection([], new RepeaterLikeItemFactory());
reconcile(pc, ['a', 'b', 'c'], trackByIndex);
expect(pc.getCollection()).toEqual([
{index: 0, implicit: 'a'},
{index: 1, implicit: 'b'},
{index: 2, implicit: 'c'},
]);
reconcile(pc, ['c', 'b', 'a'], trackByIndex);
expect(pc.getCollection()).toEqual([
{index: 0, implicit: 'c'},
{index: 1, implicit: 'b'},
{index: 2, implicit: 'a'},
]);
});
it('should update when tracking by key - fast path from the end', () => {
const pc = new LoggingLiveCollection(
[],
new RepeaterLikeItemFactory<KeyValueItem<string, string>>(),
);
reconcile(pc, [{k: 'o', v: 'o'}], trackByKey);
expect(pc.getCollection()).toEqual([{index: 0, implicit: {k: 'o', v: 'o'}}]);
reconcile(
pc,
[
{k: 'n', v: 'n'},
{k: 'o', v: 'oo'},
],
trackByKey,
);
expect(pc.getCollection()).toEqual([
{index: 0, implicit: {k: 'n', v: 'n'}},
// TODO: this scenario shows situation where the index is not correctly updated
{index: 0, implicit: {k: 'o', v: 'oo'}},
]);
});
it('should update when swapping on the fast path', () => {
const pc = new LoggingLiveCollection(
[],
new RepeaterLikeItemFactory<KeyValueItem<number, string>>(),
);
reconcile(
pc,
[
{k: 0, v: 'a'},
{k: 1, v: 'b'},
{k: 2, v: 'c'},
],
trackByKey as any,
);
expect(pc.getCollection()).toEqual([
{index: 0, implicit: {k: 0, v: 'a'}},
{index: 1, implicit: {k: 1, v: 'b'}},
{index: 2, implicit: {k: 2, v: 'c'}},
]);
reconcile(
pc,
[
{k: 2, v: 'cc'},
{k: 1, v: 'bb'},
{k: 0, v: 'aa'},
],
trackByKey as any,
);
expect(pc.getCollection()).toEqual([
{index: 0, implicit: {k: 2, v: 'cc'}},
{index: 1, implicit: {k: 1, v: 'bb'}},
{index: 2, implicit: {k: 0, v: 'aa'}},
]);
});
it('should update when moving forward on the fast path', () => {
const pc = new LoggingLiveCollection(
[],
new RepeaterLikeItemFactory<KeyValueItem<number, string>>(),
);
reconcile(
pc,
[
{k: 0, v: 'a'},
{k: 1, v: 'b'},
{k: 2, v: 'c'},
{k: 3, v: 'd'},
],
trackByKey as any,
);
expect(pc.getCollection()).toEqual([
{index: 0, implicit: {k: 0, v: 'a'}},
{index: 1, implicit: {k: 1, v: 'b'}},
{index: 2, implicit: {k: 2, v: 'c'}},
{index: 3, implicit: {k: 3, v: 'd'}},
]);
reconcile(
pc,
[
{k: 0, v: 'aa'},
{k: 3, v: 'dd'},
{k: 1, v: 'bb'},
{k: 2, v: 'cc'},
],
trackByKey as any,
);
expect(pc.getCollection()).toEqual([
{index: 0, implicit: {k: 0, v: 'aa'}},
{index: 1, implicit: {k: 3, v: 'dd'}},
{index: 2, implicit: {k: 1, v: 'bb'}},
{index: 3, implicit: {k: 2, v: 'cc'}},
]);
});
});
}); | {
"end_byte": 15450,
"start_byte": 11362,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/list_reconciliation_spec.ts"
} |
angular/packages/core/test/render3/is_shape_of_spec.ts_0_1394 | /**
* @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 {isShapeOf, ShapeOf} from './is_shape_of';
describe('isShapeOf', () => {
const ShapeOfEmptyObject: ShapeOf<{}> = {};
it('should not match for non objects', () => {
expect(isShapeOf(null, ShapeOfEmptyObject)).toBeFalse();
expect(isShapeOf(0, ShapeOfEmptyObject)).toBeFalse();
expect(isShapeOf(1, ShapeOfEmptyObject)).toBeFalse();
expect(isShapeOf(true, ShapeOfEmptyObject)).toBeFalse();
expect(isShapeOf(false, ShapeOfEmptyObject)).toBeFalse();
expect(isShapeOf(undefined, ShapeOfEmptyObject)).toBeFalse();
});
it('should match on empty object', () => {
expect(isShapeOf({}, ShapeOfEmptyObject)).toBeTrue();
expect(isShapeOf({extra: 'is ok'}, ShapeOfEmptyObject)).toBeTrue();
});
it('should match on shape', () => {
expect(isShapeOf({required: 1}, {required: true})).toBeTrue();
expect(isShapeOf({required: true, extra: 'is ok'}, {required: true})).toBeTrue();
});
it('should not match if missing property', () => {
expect(isShapeOf({required: 1}, {required: true, missing: true})).toBeFalse();
expect(
isShapeOf({required: true, extra: 'is ok'}, {required: true, missing: true}),
).toBeFalse();
});
});
| {
"end_byte": 1394,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/is_shape_of_spec.ts"
} |
angular/packages/core/test/render3/view_fixture.ts_0_6457 | /**
* @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 {Sanitizer, Type} from '@angular/core';
import {stringifyElement} from '@angular/platform-browser/testing/src/browser_util';
import {extractDirectiveDef} from '../../src/render3/definition';
import {refreshView} from '../../src/render3/instructions/change_detection';
import {renderView} from '../../src/render3/instructions/render';
import {createLView, createTNode, createTView} from '../../src/render3/instructions/shared';
import {
DirectiveDef,
DirectiveDefList,
DirectiveTypesOrFactory,
PipeDef,
PipeDefList,
PipeTypesOrFactory,
RenderFlags,
} from '../../src/render3/interfaces/definition';
import {TConstants, TElementNode, TNodeType} from '../../src/render3/interfaces/node';
import {
HEADER_OFFSET,
LView,
LViewFlags,
TView,
TViewType,
} from '../../src/render3/interfaces/view';
import {enterView, leaveView, specOnlyIsInstructionStateEmpty} from '../../src/render3/state';
import {noop} from '../../src/util/noop';
import {getRendererFactory2} from './imported_renderer2';
/**
* Fixture useful for testing operations which need `LView` / `TView`
*/
export class ViewFixture {
/**
* Clean up the `LFrame` stack between tests.
*/
static cleanUp() {
while (!specOnlyIsInstructionStateEmpty()) {
leaveView();
}
}
private createFn?: () => void;
private updateFn?: () => void;
private context?: {};
/**
* DOM element which acts as a host to the `LView`.
*/
host: HTMLElement;
tView: TView;
lView: LView;
constructor({
create,
update,
decls,
vars,
consts,
context,
directives,
sanitizer,
}: {
create?: () => void;
update?: () => void;
decls?: number;
vars?: number;
consts?: TConstants;
context?: {};
directives?: any[];
sanitizer?: Sanitizer;
} = {}) {
this.context = context;
this.createFn = create;
this.updateFn = update;
const document = (((typeof global == 'object' && global) || window) as any).document;
const rendererFactory = getRendererFactory2(document);
const hostRenderer = rendererFactory.createRenderer(null, null);
this.host = hostRenderer.createElement('host-element') as HTMLElement;
const hostTView = createTView(
TViewType.Root,
null,
null,
1,
0,
null,
null,
null,
null,
null,
null,
);
const hostLView = createLView(
null,
hostTView,
{},
LViewFlags.CheckAlways | LViewFlags.IsRoot,
null,
null,
{
rendererFactory,
sanitizer: sanitizer || null,
changeDetectionScheduler: null,
},
hostRenderer,
null,
null,
null,
);
let template = noop;
if (create) {
// If `create` function is provided - assemble a template function
// based on it and pass to the `createTView` function to store in
// `tView` for future use. The update function would be stored and
// invoked separately.
template = (rf: RenderFlags, ctx: {}) => {
if (rf & RenderFlags.Create) {
create();
}
};
}
this.tView = createTView(
TViewType.Component,
null,
template,
decls || 0,
vars || 0,
directives ? toDefs(directives, (dir) => extractDirectiveDef(dir)!) : null,
null,
null,
null,
consts || null,
null,
);
const hostTNode = createTNode(
hostTView,
null,
TNodeType.Element,
0,
'host-element',
null,
) as TElementNode;
// Store TNode at the first slot right after the header part
hostTView.data[HEADER_OFFSET] = hostTNode;
this.lView = createLView(
hostLView,
this.tView,
context || {},
LViewFlags.CheckAlways,
this.host,
hostTNode,
null,
hostRenderer,
null,
null,
null,
);
if (this.createFn) {
renderView(this.tView, this.lView, this.context);
}
}
get html(): string {
return toHtml(this.host.firstChild as Element);
}
/**
* Invokes an update block function, which can either be provided during
* the `ViewFixture` initialization or as an argument.
*
* @param updateFn An update block function to invoke.
*/
update(updateFn?: () => void) {
updateFn ||= this.updateFn;
if (!updateFn) {
throw new Error(
'The `ViewFixture.update` was invoked, but there was no `update` function ' +
'provided during the `ViewFixture` instantiation or specified as an argument ' +
'in this call.',
);
}
refreshView(this.tView, this.lView, updateFn, this.context);
}
/**
* If you use `ViewFixture` and `enter()`, please add `afterEach(ViewFixture.cleanup);` to ensure
* that he global `LFrame` stack gets cleaned up between the tests.
*/
enterView() {
enterView(this.lView);
}
leaveView() {
leaveView();
}
apply(fn: () => void) {
this.enterView();
try {
fn();
} finally {
this.leaveView();
}
}
}
function toDefs(
types: DirectiveTypesOrFactory | undefined | null,
mapFn: (type: Type<any>) => DirectiveDef<any>,
): DirectiveDefList | null;
function toDefs(
types: PipeTypesOrFactory | undefined | null,
mapFn: (type: Type<any>) => PipeDef<any>,
): PipeDefList | null;
function toDefs(
types: Type<any>[] | (() => Type<any>[]) | undefined | null,
mapFn: (type: Type<any>) => PipeDef<any> | DirectiveDef<any>,
): any {
if (!types) return null;
if (typeof types == 'function') {
types = types();
}
return types.map(mapFn);
}
function toHtml(element: Element, keepNgReflect = false): string {
if (element) {
let html = stringifyElement(element);
if (!keepNgReflect) {
html = html
.replace(/\sng-reflect-\S*="[^"]*"/g, '')
.replace(/<!--bindings=\{(\W.*\W\s*)?\}-->/g, '');
}
html = html
.replace(/^<div host="">(.*)<\/div>$/, '$1')
.replace(/^<div fixture="mark">(.*)<\/div>$/, '$1')
.replace(/^<div host="mark">(.*)<\/div>$/, '$1')
.replace(' style=""', '')
.replace(/<!--container-->/g, '')
.replace(/<!--ng-container-->/g, '');
return html;
} else {
return '';
}
}
| {
"end_byte": 6457,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/view_fixture.ts"
} |
angular/packages/core/test/render3/global_utils_spec.ts_0_2807 | /**
* @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 {setProfiler} from '@angular/core/src/render3/profiler';
import {applyChanges} from '../../src/render3/util/change_detection_utils';
import {
getComponent,
getContext,
getDirectiveMetadata,
getDirectives,
getHostElement,
getInjector,
getListeners,
getOwningComponent,
getRootComponents,
} from '../../src/render3/util/discovery_utils';
import {
GLOBAL_PUBLISH_EXPANDO_KEY,
GlobalDevModeUtils,
publishDefaultGlobalUtils,
publishGlobalUtil,
} from '../../src/render3/util/global_utils';
import {global} from '../../src/util/global';
type GlobalUtilFunctions = keyof GlobalDevModeUtils['ng'];
describe('global utils', () => {
describe('publishGlobalUtil', () => {
it('should publish a function to the window', () => {
const w = global as any as GlobalDevModeUtils;
const foo = 'foo' as GlobalUtilFunctions;
expect(w[GLOBAL_PUBLISH_EXPANDO_KEY][foo]).toBeFalsy();
const fooFn = () => {};
publishGlobalUtil(foo, fooFn);
expect(w[GLOBAL_PUBLISH_EXPANDO_KEY][foo]).toBe(fooFn);
});
});
describe('publishDefaultGlobalUtils', () => {
beforeEach(() => publishDefaultGlobalUtils());
it('should publish getComponent', () => {
assertPublished('getComponent', getComponent);
});
it('should publish getContext', () => {
assertPublished('getContext', getContext);
});
it('should publish getListeners', () => {
assertPublished('getListeners', getListeners);
});
it('should publish getOwningComponent', () => {
assertPublished('getOwningComponent', getOwningComponent);
});
it('should publish getRootComponents', () => {
assertPublished('getRootComponents', getRootComponents);
});
it('should publish getDirectives', () => {
assertPublished('getDirectives', getDirectives);
});
it('should publish getHostComponent', () => {
assertPublished('getHostElement', getHostElement);
});
it('should publish getInjector', () => {
assertPublished('getInjector', getInjector);
});
it('should publish applyChanges', () => {
assertPublished('applyChanges', applyChanges);
});
it('should publish getDirectiveMetadata', () => {
assertPublished('getDirectiveMetadata', getDirectiveMetadata);
});
it('should publish ɵsetProfiler', () => {
assertPublished('ɵsetProfiler', setProfiler);
});
});
});
function assertPublished(name: GlobalUtilFunctions, value: Function) {
const w = global as any as GlobalDevModeUtils;
expect(w[GLOBAL_PUBLISH_EXPANDO_KEY][name]).toBe(value);
}
| {
"end_byte": 2807,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/global_utils_spec.ts"
} |
angular/packages/core/test/render3/BUILD.bazel_0_2107 | load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "render3_lib",
testonly = True,
srcs = glob(
["**/*.ts"],
exclude = [
"**/*_perf.ts",
"domino.d.ts",
"load_domino.ts",
"is_shape_of.ts",
"jit_spec.ts",
"matchers.ts",
],
),
deps = [
":matchers",
"//packages:types",
"//packages/animations",
"//packages/animations/browser",
"//packages/animations/browser/testing",
"//packages/common",
"//packages/compiler",
"//packages/core",
"//packages/core/primitives/signals",
"//packages/core/rxjs-interop",
"//packages/core/src/di/interface",
"//packages/core/src/interface",
"//packages/core/src/util",
"//packages/core/testing",
"//packages/platform-browser",
"//packages/platform-browser/animations",
"//packages/platform-browser/testing",
"//packages/private/testing",
"@npm//rxjs",
],
)
ts_library(
name = "matchers",
testonly = True,
srcs = [
"is_shape_of.ts",
"matchers.ts",
],
deps = [
"//packages/core",
],
)
ts_library(
name = "domino",
testonly = True,
srcs = [
"load_domino.ts",
],
deps = [
"//packages/common",
"//packages/compiler",
"//packages/platform-server",
"//packages/platform-server:bundled_domino_lib",
"//packages/zone.js/lib:zone_d_ts",
],
)
ts_library(
name = "render3_node_lib",
testonly = True,
srcs = [],
deps = [
":domino",
":render3_lib",
],
)
jasmine_node_test(
name = "render3",
bootstrap = [
":domino",
"//tools/testing:node",
],
deps = [
":render3_node_lib",
"//packages/zone.js/lib",
],
)
karma_web_test_suite(
name = "render3_web",
deps = [
":render3_lib",
],
)
| {
"end_byte": 2107,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/BUILD.bazel"
} |
angular/packages/core/test/render3/query_spec.ts_0_3057 | /**
* @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,
Injectable,
QueryList,
TemplateRef,
ViewChild,
ViewChildren,
ViewContainerRef,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
describe('query', () => {
describe('predicate', () => {
describe('providers', () => {
@Injectable()
class Service {}
@Injectable()
class Alias {}
let directive: MyDirective | null = null;
@Directive({
selector: '[myDir]',
standalone: true,
providers: [Service, {provide: Alias, useExisting: Service}],
})
class MyDirective {
constructor(public service: Service) {
directive = this;
}
}
beforeEach(() => (directive = null));
// https://stackblitz.com/edit/ng-viewengine-viewchild-providers?file=src%2Fapp%2Fapp.component.ts
it('should query for providers that are present on a directive', () => {
@Component({
selector: 'app',
template: '<div myDir></div>',
imports: [MyDirective],
standalone: true,
})
class App {
@ViewChild(MyDirective) directive!: MyDirective;
@ViewChild(Service) service!: Service;
@ViewChild(Alias) alias!: Alias;
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const component = fixture.componentInstance;
expect(component.directive).toBe(directive!);
expect(component.service).toBe(directive!.service);
expect(component.alias).toBe(directive!.service);
});
it('should resolve a provider if given as read token', () => {
@Component({
selector: 'app',
standalone: true,
template: '<div myDir></div>',
imports: [MyDirective],
})
class App {
@ViewChild(MyDirective, {read: Alias}) service!: Service;
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.service).toBe(directive!.service);
});
});
});
it('should restore queries if view changes', () => {
@Directive({
selector: '[someDir]',
standalone: true,
})
class SomeDir {
constructor(
public vcr: ViewContainerRef,
public temp: TemplateRef<any>,
) {
this.vcr.createEmbeddedView(this.temp);
}
}
@Component({
selector: 'app',
standalone: true,
template: `
<div *someDir></div>
<div #foo></div>
`,
imports: [SomeDir],
})
class AppComponent {
@ViewChildren('foo') query!: QueryList<any>;
}
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(fixture.componentInstance.query.length).toBe(1);
});
});
| {
"end_byte": 3057,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/query_spec.ts"
} |
angular/packages/core/test/render3/providers_helper.ts_0_3709 | /**
* @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, Provider, Type, ViewEncapsulation} from '@angular/core';
import {TestBed} from '@angular/core/testing';
export interface ComponentTest {
providers?: Provider[];
viewProviders?: Provider[];
directiveProviders?: Provider[];
directive2Providers?: Provider[];
directiveAssertion?: () => void;
componentAssertion?: () => void;
}
export function expectProvidersScenario(defs: {
app?: ComponentTest;
parent?: ComponentTest;
viewChild?: ComponentTest;
contentChild?: ComponentTest;
ngModule?: Type<any>;
}): void {
@Component({
standalone: true,
selector: 'view-child',
template: 'view-child',
encapsulation: ViewEncapsulation.None,
providers: defs.viewChild?.providers ?? [],
viewProviders: defs.viewChild?.viewProviders ?? [],
})
class ViewChildComponent {
constructor() {
defs.viewChild?.componentAssertion?.();
}
}
@Directive({
standalone: true,
selector: 'view-child',
providers: defs.viewChild?.directiveProviders ?? [],
})
class ViewChildDirective {
constructor() {
defs.viewChild?.directiveAssertion?.();
}
}
@Component({
standalone: true,
selector: 'content-child',
template: 'content-child',
encapsulation: ViewEncapsulation.None,
providers: defs.contentChild?.providers ?? [],
viewProviders: defs.contentChild?.viewProviders ?? [],
})
class ContentChildComponent {
constructor() {
defs.contentChild?.componentAssertion?.();
}
}
@Directive({
standalone: true,
selector: 'content-child',
providers: defs.contentChild?.directiveProviders ?? [],
})
class ContentChildDirective {
constructor() {
defs.contentChild?.directiveAssertion?.();
}
}
@Component({
standalone: true,
imports: [ViewChildComponent, ViewChildDirective],
selector: 'parent',
template: '<view-child></view-child>',
encapsulation: ViewEncapsulation.None,
providers: defs.parent?.providers ?? [],
viewProviders: defs.parent?.viewProviders ?? [],
})
class ParentComponent {
constructor() {
defs.parent?.componentAssertion?.();
}
}
@Directive({
standalone: true,
selector: 'parent',
providers: defs.parent?.directiveProviders ?? [],
})
class ParentDirective {
constructor() {
defs.parent?.directiveAssertion?.();
}
}
@Directive({
standalone: true,
selector: 'parent',
providers: defs.parent?.directive2Providers ?? [],
})
class ParentDirective2 {
constructor() {
defs.parent?.directiveAssertion?.();
}
}
@Component({
standalone: true,
imports: [
ParentComponent,
// Note: tests are sensitive to the ordering here - the providers from `ParentDirective`
// should override the providers from `ParentDirective2`.
ParentDirective2,
ParentDirective,
ContentChildComponent,
ContentChildDirective,
],
template: '<parent><content-child></content-child></parent>',
providers: defs.app?.providers ?? [],
viewProviders: defs.app?.viewProviders ?? [],
})
class App {
constructor() {
defs.app?.componentAssertion?.();
}
}
TestBed.configureTestingModule({
imports: defs.ngModule ? [defs.ngModule] : [],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toEqual(
'<parent><view-child>view-child</view-child></parent>',
);
fixture.destroy();
}
| {
"end_byte": 3709,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/providers_helper.ts"
} |
angular/packages/core/test/render3/microtask_effect_spec.ts_0_914 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {AsyncPipe} from '@angular/common';
import {
AfterViewInit,
ApplicationRef,
Component,
computed,
ContentChildren,
createComponent,
createEnvironmentInjector,
destroyPlatform,
ɵmicrotaskEffect as microtaskEffect,
EnvironmentInjector,
ErrorHandler,
inject,
Injectable,
Injector,
Input,
NgZone,
OnChanges,
QueryList,
signal,
SimpleChanges,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import {toObservable} from '@angular/core/rxjs-interop';
import {TestBed} from '@angular/core/testing';
import {bootstrapApplication} from '@angular/platform-browser';
import {withBody} from '@angular/private/testing';
import {filter, firstValueFrom, map} from 'rxjs';
| {
"end_byte": 914,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/microtask_effect_spec.ts"
} |
angular/packages/core/test/render3/microtask_effect_spec.ts_916_9646 | escribe('microtask effects', () => {
beforeEach(destroyPlatform);
afterEach(destroyPlatform);
it(
'should run effects in the zone in which they get created',
withBody('<test-cmp></test-cmp>', async () => {
const log: string[] = [];
@Component({
selector: 'test-cmp',
standalone: true,
template: '',
})
class Cmp {
constructor(ngZone: NgZone) {
microtaskEffect(() => {
log.push(Zone.current.name);
});
ngZone.runOutsideAngular(() => {
microtaskEffect(() => {
log.push(Zone.current.name);
});
});
}
}
await bootstrapApplication(Cmp);
expect(log).not.toEqual(['angular', 'angular']);
}),
);
it('should contribute to application stableness when an effect is pending', async () => {
const someSignal = signal('initial');
@Component({
standalone: true,
template: '',
})
class App {
unused = microtaskEffect(() => someSignal());
}
const appRef = TestBed.inject(ApplicationRef);
const componentRef = createComponent(App, {
environmentInjector: TestBed.inject(EnvironmentInjector),
});
// Effect is not scheduled until change detection runs for the component
await expectAsync(firstValueFrom(appRef.isStable)).toBeResolvedTo(true);
componentRef.changeDetectorRef.detectChanges();
const stableEmits: boolean[] = [];
const p = firstValueFrom(
appRef.isStable.pipe(
map((stable) => {
stableEmits.push(stable);
return stableEmits;
}),
filter((emits) => emits.length === 2),
),
);
await expectAsync(p).toBeResolvedTo([false, true]);
componentRef.destroy();
});
it('should propagate errors to the ErrorHandler', () => {
let run = false;
let lastError: any = null;
class FakeErrorHandler extends ErrorHandler {
override handleError(error: any): void {
lastError = error;
}
}
const injector = createEnvironmentInjector(
[{provide: ErrorHandler, useFactory: () => new FakeErrorHandler()}],
TestBed.inject(EnvironmentInjector),
);
microtaskEffect(
() => {
run = true;
throw new Error('fail!');
},
{injector},
);
expect(() => TestBed.flushEffects()).not.toThrow();
expect(run).toBeTrue();
expect(lastError.message).toBe('fail!');
});
it('should be usable inside an ErrorHandler', async () => {
const shouldError = signal(false);
let lastError: any = null;
class FakeErrorHandler extends ErrorHandler {
constructor() {
super();
microtaskEffect(() => {
if (shouldError()) {
throw new Error('fail!');
}
});
}
override handleError(error: any): void {
lastError = error;
}
}
@Component({
standalone: true,
template: '',
providers: [{provide: ErrorHandler, useClass: FakeErrorHandler}],
})
class App {
errorHandler = inject(ErrorHandler);
}
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.componentInstance.errorHandler).toBeInstanceOf(FakeErrorHandler);
expect(lastError).toBe(null);
shouldError.set(true);
fixture.detectChanges();
expect(lastError?.message).toBe('fail!');
});
it('should run effect cleanup function on destroy', async () => {
let counterLog: number[] = [];
let cleanupCount = 0;
@Component({
selector: 'test-cmp',
standalone: true,
template: '',
})
class Cmp {
counter = signal(0);
effectRef = microtaskEffect((onCleanup) => {
counterLog.push(this.counter());
onCleanup(() => {
cleanupCount++;
});
});
}
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
await fixture.whenStable();
expect(counterLog).toEqual([0]);
// initially an effect runs but the default cleanup function is noop
expect(cleanupCount).toBe(0);
fixture.componentInstance.counter.set(5);
fixture.detectChanges();
await fixture.whenStable();
expect(counterLog).toEqual([0, 5]);
expect(cleanupCount).toBe(1);
fixture.destroy();
expect(counterLog).toEqual([0, 5]);
expect(cleanupCount).toBe(2);
});
it('should run effects created in ngAfterViewInit', () => {
let didRun = false;
@Component({
selector: 'test-cmp',
standalone: true,
template: '',
})
class Cmp implements AfterViewInit {
injector = inject(Injector);
ngAfterViewInit(): void {
microtaskEffect(
() => {
didRun = true;
},
{injector: this.injector},
);
}
}
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
expect(didRun).toBeTrue();
});
it(
'should disallow writing to signals within effects by default',
withBody('<test-cmp></test-cmp>', async () => {
@Component({
selector: 'test-cmp',
standalone: true,
template: '',
})
class Cmp {
counter = signal(0);
constructor() {
microtaskEffect(() => {
expect(() => this.counter.set(1)).toThrow();
});
}
}
await (await bootstrapApplication(Cmp)).whenStable();
}),
);
it('should allow writing to signals within effects when option set', () => {
const counter = signal(0);
microtaskEffect(() => counter.set(1), {
allowSignalWrites: true,
injector: TestBed.inject(Injector),
});
TestBed.flushEffects();
expect(counter()).toBe(1);
});
it('should allow writing to signals in ngOnChanges', () => {
@Component({
selector: 'with-input',
standalone: true,
template: '{{inSignal()}}',
})
class WithInput implements OnChanges {
inSignal = signal<string | undefined>(undefined);
@Input() in: string | undefined;
ngOnChanges(changes: SimpleChanges): void {
if (changes['in']) {
this.inSignal.set(changes['in'].currentValue);
}
}
}
@Component({
selector: 'test-cmp',
standalone: true,
imports: [WithInput],
template: `<with-input [in]="'A'" />|<with-input [in]="'B'" />`,
})
class Cmp {}
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('A|B');
});
it('should allow writing to signals in a constructor', () => {
@Component({
selector: 'with-constructor',
standalone: true,
template: '{{state()}}',
})
class WithConstructor {
state = signal('property initializer');
constructor() {
this.state.set('constructor');
}
}
@Component({
selector: 'test-cmp',
standalone: true,
imports: [WithConstructor],
template: `<with-constructor />`,
})
class Cmp {}
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('constructor');
});
it('should allow writing to signals in input setters', () => {
@Component({
selector: 'with-input-setter',
standalone: true,
template: '{{state()}}',
})
class WithInputSetter {
state = signal('property initializer');
@Input()
set testInput(newValue: string) {
this.state.set(newValue);
}
}
@Component({
selector: 'test-cmp',
standalone: true,
imports: [WithInputSetter],
template: `
<with-input-setter [testInput]="'binding'" />|<with-input-setter testInput="static" />
`,
})
class Cmp {}
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('binding|static');
});
it('should allow writing to signals in query result setters', () => {
@Component({
selector: 'with-query',
standalone: true,
template: '{{items().length}}',
})
class WithQuery {
items = signal<unknown[]>([]);
@ContentChildren('item')
set itemsQuery(result: QueryList<unknown>) {
this.items.set(result.toArray());
}
}
@Component({
selector: 'test-cmp',
standalone: true,
imports: [WithQuery],
template: `<with-query><div #item></div></with-query>`,
})
class Cmp {}
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('1');
});
| {
"end_byte": 9646,
"start_byte": 916,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/microtask_effect_spec.ts"
} |
angular/packages/core/test/render3/microtask_effect_spec.ts_9650_17421 | t('should not execute query setters in the reactive context', () => {
const state = signal('initial');
@Component({
selector: 'with-query-setter',
standalone: true,
template: '<div #el></div>',
})
class WithQuerySetter {
el: unknown;
@ViewChild('el', {static: true})
set elQuery(result: unknown) {
// read a signal in a setter - I want to verify that framework executes this code outside of
// the reactive context
state();
this.el = result;
}
}
@Component({
selector: 'test-cmp',
standalone: true,
template: ``,
})
class Cmp {
noOfCmpCreated = 0;
constructor(environmentInjector: EnvironmentInjector) {
// A slightly artificial setup where a component instance is created using imperative APIs.
// We don't have control over the timing / reactive context of such API calls so need to
// code defensively in the framework.
// Here we want to specifically verify that an effect is _not_ re-run if a signal read
// happens in a query setter of a dynamically created component.
microtaskEffect(() => {
createComponent(WithQuerySetter, {environmentInjector});
this.noOfCmpCreated++;
});
}
}
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
expect(fixture.componentInstance.noOfCmpCreated).toBe(1);
state.set('changed');
fixture.detectChanges();
expect(fixture.componentInstance.noOfCmpCreated).toBe(1);
});
it('should allow toObservable subscription in template (with async pipe)', () => {
@Component({
selector: 'test-cmp',
standalone: true,
imports: [AsyncPipe],
template: '{{counter$ | async}}',
})
class Cmp {
counter$ = toObservable(signal(0));
}
const fixture = TestBed.createComponent(Cmp);
expect(() => fixture.detectChanges(true)).not.toThrow();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('0');
});
describe('effects created in components should first run after ngOnInit', () => {
it('when created during bootstrapping', () => {
let log: string[] = [];
@Component({
standalone: true,
selector: 'test-cmp',
template: '',
})
class TestCmp {
constructor() {
microtaskEffect(() => log.push('effect'));
}
ngOnInit(): void {
log.push('init');
}
}
const fixture = TestBed.createComponent(TestCmp);
TestBed.flushEffects();
expect(log).toEqual([]);
fixture.detectChanges();
expect(log).toEqual(['init', 'effect']);
});
it('when created during change detection', () => {
let log: string[] = [];
@Component({
standalone: true,
selector: 'test-cmp',
template: '',
})
class TestCmp {
ngOnInitRan = false;
constructor() {
microtaskEffect(() => log.push('effect'));
}
ngOnInit(): void {
log.push('init');
}
}
@Component({
standalone: true,
selector: 'driver-cmp',
imports: [TestCmp],
template: `
@if (cond) {
<test-cmp />
}
`,
})
class DriverCmp {
cond = false;
}
const fixture = TestBed.createComponent(DriverCmp);
fixture.detectChanges();
expect(log).toEqual([]);
// Toggle the @if, which should create and run the effect.
fixture.componentInstance.cond = true;
fixture.detectChanges();
expect(log).toEqual(['init', 'effect']);
});
it('when created dynamically', () => {
let log: string[] = [];
@Component({
standalone: true,
selector: 'test-cmp',
template: '',
})
class TestCmp {
ngOnInitRan = false;
constructor() {
microtaskEffect(() => log.push('effect'));
}
ngOnInit(): void {
log.push('init');
}
}
@Component({
standalone: true,
selector: 'driver-cmp',
template: '',
})
class DriverCmp {
vcr = inject(ViewContainerRef);
}
const fixture = TestBed.createComponent(DriverCmp);
fixture.detectChanges();
const ref = fixture.componentInstance.vcr.createComponent(TestCmp);
// Verify that simply creating the component didn't schedule the effect.
TestBed.flushEffects();
expect(log).toEqual([]);
// Running change detection should schedule and run the effect.
fixture.detectChanges();
expect(log).toEqual(['init', 'effect']);
ref.destroy();
});
it('when created in a service provided in a component', () => {
let log: string[] = [];
@Injectable()
class EffectService {
constructor() {
microtaskEffect(() => log.push('effect'));
}
}
@Component({
standalone: true,
selector: 'test-cmp',
template: '',
providers: [EffectService],
})
class TestCmp {
svc = inject(EffectService);
ngOnInit(): void {
log.push('init');
}
}
const fixture = TestBed.createComponent(TestCmp);
TestBed.flushEffects();
expect(log).toEqual([]);
fixture.detectChanges();
expect(log).toEqual(['init', 'effect']);
});
it('if multiple effects are created', () => {
let log: string[] = [];
@Component({
standalone: true,
selector: 'test-cmp',
template: '',
})
class TestCmp {
constructor() {
microtaskEffect(() => log.push('effect a'));
microtaskEffect(() => log.push('effect b'));
microtaskEffect(() => log.push('effect c'));
}
ngOnInit(): void {
log.push('init');
}
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(log[0]).toBe('init');
expect(log).toContain('effect a');
expect(log).toContain('effect b');
expect(log).toContain('effect c');
});
});
describe('should disallow creating an effect context', () => {
it('inside template effect', () => {
@Component({
template: '{{someFn()}}',
})
class Cmp {
someFn() {
microtaskEffect(() => {});
}
}
const fixture = TestBed.createComponent(Cmp);
expect(() => fixture.detectChanges(true)).toThrowError(
/effect\(\) cannot be called from within a reactive context./,
);
});
it('inside computed', () => {
expect(() => {
computed(() => {
microtaskEffect(() => {});
})();
}).toThrowError(/effect\(\) cannot be called from within a reactive context./);
});
it('inside an effect', () => {
@Component({
template: '',
})
class Cmp {
constructor() {
microtaskEffect(() => {
this.someFnThatWillCreateAnEffect();
});
}
someFnThatWillCreateAnEffect() {
microtaskEffect(() => {});
}
}
TestBed.configureTestingModule({
providers: [
{
provide: ErrorHandler,
useClass: class extends ErrorHandler {
override handleError(e: Error) {
throw e;
}
},
},
],
});
const fixture = TestBed.createComponent(Cmp);
expect(() => fixture.detectChanges()).toThrowError(
/effect\(\) cannot be called from within a reactive context./,
);
});
});
});
| {
"end_byte": 17421,
"start_byte": 9650,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/microtask_effect_spec.ts"
} |
angular/packages/core/test/render3/microtask_effect_spec.ts_17423_19814 | escribe('microtask effects in TestBed', () => {
it('created in the constructor should run with detectChanges()', () => {
const log: string[] = [];
@Component({
selector: 'test-cmp',
standalone: true,
template: '',
})
class Cmp {
constructor() {
log.push('Ctor');
microtaskEffect(() => {
log.push('Effect');
});
}
ngDoCheck() {
log.push('DoCheck');
}
}
TestBed.createComponent(Cmp).detectChanges();
expect(log).toEqual([
// The component gets constructed, which creates the effect. Since the effect is created in a
// component, it doesn't get scheduled until the component is first change detected.
'Ctor',
// Next, the first change detection (update pass) happens.
'DoCheck',
// Then the effect runs.
'Effect',
]);
});
it('created in ngOnInit should run with detectChanges()', () => {
const log: string[] = [];
@Component({
selector: 'test-cmp',
standalone: true,
template: '',
})
class Cmp {
private injector = inject(Injector);
constructor() {
log.push('Ctor');
}
ngOnInit() {
microtaskEffect(
() => {
log.push('Effect');
},
{injector: this.injector},
);
}
ngDoCheck() {
log.push('DoCheck');
}
}
TestBed.createComponent(Cmp).detectChanges();
expect(log).toEqual([
// The component gets constructed.
'Ctor',
// Next, the first change detection (update pass) happens, which creates the effect and
// schedules it for execution.
'DoCheck',
// Then the effect runs.
'Effect',
]);
});
it('will flush effects automatically when using autoDetectChanges', async () => {
const val = signal('initial');
let observed = '';
@Component({
selector: 'test-cmp',
standalone: true,
template: '',
})
class Cmp {
constructor() {
microtaskEffect(() => {
observed = val();
});
}
}
const fixture = TestBed.createComponent(Cmp);
fixture.autoDetectChanges();
expect(observed).toBe('initial');
val.set('new');
expect(observed).toBe('initial');
await fixture.whenStable();
expect(observed).toBe('new');
});
});
| {
"end_byte": 19814,
"start_byte": 17423,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/microtask_effect_spec.ts"
} |
angular/packages/core/test/render3/i18n_debug_spec.ts_0_6576 | /**
* @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 {
i18nCreateOpCodesToString,
i18nRemoveOpCodesToString,
i18nUpdateOpCodesToString,
icuCreateOpCodesToString,
} from '@angular/core/src/render3/i18n/i18n_debug';
import {
ELEMENT_MARKER,
I18nCreateOpCode,
I18nCreateOpCodes,
I18nRemoveOpCodes,
I18nUpdateOpCode,
I18nUpdateOpCodes,
ICU_MARKER,
IcuCreateOpCode,
} from '@angular/core/src/render3/interfaces/i18n';
describe('i18n debug', () => {
describe('i18nUpdateOpCodesToString', () => {
it('should print nothing', () => {
expect(i18nUpdateOpCodesToString([] as unknown as I18nUpdateOpCodes)).toEqual([]);
});
it('should print text opCode', () => {
expect(
i18nUpdateOpCodesToString([
0b11,
4,
'pre ',
-4,
' post',
(1 << I18nUpdateOpCode.SHIFT_REF) | I18nUpdateOpCode.Text,
] as unknown as I18nUpdateOpCodes),
).toEqual([
'if (mask & 0b11) { (lView[1] as Text).textContent = `pre ${lView[i-4]} post`; }',
]);
});
it('should print Attribute opCode', () => {
// The `sanitizeFn` is written as actual function, compared to it being an arrow function.
// This is done to make this test less reluctant to build process changes where e.g. an
// arrow function might be transformed to a function declaration in ES5.
const sanitizeFn = function (v: any) {
return v;
};
expect(
i18nUpdateOpCodesToString([
0b01,
8,
'pre ',
-4,
' in ',
-3,
' post',
(1 << I18nUpdateOpCode.SHIFT_REF) | I18nUpdateOpCode.Attr,
'title',
null,
0b10,
8,
'pre ',
-4,
' in ',
-3,
' post',
(1 << I18nUpdateOpCode.SHIFT_REF) | I18nUpdateOpCode.Attr,
'title',
sanitizeFn,
] as unknown as I18nUpdateOpCodes),
).toEqual([
"if (mask & 0b1) { (lView[1] as Element).setAttribute('title', `pre ${lView[i-4]} in ${lView[i-3]} post`); }",
`if (mask & 0b10) { (lView[1] as Element).setAttribute('title', (${sanitizeFn.toString()})(\`pre $\{lView[i-4]} in $\{lView[i-3]} post\`)); }`,
]);
});
it('should print icuSwitch opCode', () => {
expect(
i18nUpdateOpCodesToString([
0b100,
2,
-5,
(12 << I18nUpdateOpCode.SHIFT_REF) | I18nUpdateOpCode.IcuSwitch,
] as unknown as I18nUpdateOpCodes),
).toEqual(['if (mask & 0b100) { icuSwitchCase(12, `${lView[i-5]}`); }']);
});
it('should print icuUpdate opCode', () => {
expect(
i18nUpdateOpCodesToString([
0b1000,
1,
(13 << I18nUpdateOpCode.SHIFT_REF) | I18nUpdateOpCode.IcuUpdate,
] as unknown as I18nUpdateOpCodes),
).toEqual(['if (mask & 0b1000) { icuUpdateCase(13); }']);
});
});
describe('i18nMutateOpCodesToString', () => {
it('should print nothing', () => {
expect(icuCreateOpCodesToString([] as unknown as I18nCreateOpCodes)).toEqual([]);
});
it('should print text AppendChild', () => {
expect(
icuCreateOpCodesToString([
'xyz',
0,
(1 << IcuCreateOpCode.SHIFT_PARENT) |
(0 << IcuCreateOpCode.SHIFT_REF) |
IcuCreateOpCode.AppendChild,
] as unknown as I18nCreateOpCodes),
).toEqual([
'lView[0] = document.createTextNode("xyz")',
'(lView[1] as Element).appendChild(lView[0])',
]);
});
it('should print element AppendChild', () => {
expect(
icuCreateOpCodesToString([
ELEMENT_MARKER,
'xyz',
0,
(1 << IcuCreateOpCode.SHIFT_PARENT) |
(0 << IcuCreateOpCode.SHIFT_REF) |
IcuCreateOpCode.AppendChild,
] as unknown as I18nCreateOpCodes),
).toEqual([
'lView[0] = document.createElement("xyz")',
'(lView[1] as Element).appendChild(lView[0])',
]);
});
it('should print comment AppendChild', () => {
expect(
icuCreateOpCodesToString([
ICU_MARKER,
'xyz',
0,
(1 << IcuCreateOpCode.SHIFT_PARENT) |
(0 << IcuCreateOpCode.SHIFT_REF) |
IcuCreateOpCode.AppendChild,
] as unknown as I18nCreateOpCodes),
).toEqual([
'lView[0] = document.createComment("xyz")',
'(lView[1] as Element).appendChild(lView[0])',
]);
});
it('should print Remove', () => {
expect(i18nRemoveOpCodesToString([123] as unknown as I18nRemoveOpCodes)).toEqual([
'remove(lView[123])',
]);
});
it('should print Attr', () => {
expect(
icuCreateOpCodesToString([
(1 << IcuCreateOpCode.SHIFT_REF) | IcuCreateOpCode.Attr,
'attr',
'value',
] as unknown as I18nCreateOpCodes),
).toEqual(['(lView[1] as Element).setAttribute("attr", "value")']);
});
it('should print RemoveNestedIcu', () => {
expect(i18nRemoveOpCodesToString([~123] as unknown as I18nRemoveOpCodes)).toEqual([
'removeNestedICU(123)',
]);
});
});
describe('i18nCreateOpCodesToString', () => {
it('should print nothing', () => {
expect(i18nCreateOpCodesToString([] as unknown as I18nCreateOpCodes)).toEqual([]);
});
it('should print text/comment creation', () => {
expect(
i18nCreateOpCodesToString([
10 << I18nCreateOpCode.SHIFT,
'text at 10', //
(11 << I18nCreateOpCode.SHIFT) | I18nCreateOpCode.APPEND_EAGERLY,
'text at 11, append', //
(12 << I18nCreateOpCode.SHIFT) | I18nCreateOpCode.COMMENT,
'comment at 12', //
(13 << I18nCreateOpCode.SHIFT) |
I18nCreateOpCode.COMMENT |
I18nCreateOpCode.APPEND_EAGERLY,
'comment at 13, append', //
] as unknown as I18nCreateOpCodes),
).toEqual([
'lView[10] = document.createText("text at 10");',
'lView[11] = document.createText("text at 11, append");',
'parent.appendChild(lView[11]);',
'lView[12] = document.createComment("comment at 12");',
'lView[13] = document.createComment("comment at 13, append");',
'parent.appendChild(lView[13]);',
]);
});
});
});
| {
"end_byte": 6576,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/i18n_debug_spec.ts"
} |
angular/packages/core/test/render3/di_spec.ts_0_6587 | /**
* @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, Self} from '@angular/core';
import {
createLView,
createTView,
getOrCreateTNode,
} from '@angular/core/src/render3/instructions/shared';
import {NodeInjectorOffset} from '@angular/core/src/render3/interfaces/injector';
import {TestBed} from '@angular/core/testing';
import {
bloomAdd,
bloomHashBitOrFactory as bloomHash,
bloomHasToken,
getOrCreateNodeInjectorForNode,
} from '../../src/render3/di';
import {TNodeType} from '../../src/render3/interfaces/node';
import {HEADER_OFFSET, LViewFlags, TVIEW, TViewType} from '../../src/render3/interfaces/view';
import {enterView, leaveView} from '../../src/render3/state';
describe('di', () => {
describe('directive injection', () => {
describe('flags', () => {
it('should check only the current node with @Self even with false positive', () => {
@Directive({selector: '[notOnSelf]', standalone: true})
class DirNotOnSelf {}
@Directive({selector: '[tryInjectFromSelf]', standalone: true})
class DirTryInjectFromSelf {
constructor(@Self() private dir: DirNotOnSelf) {}
}
@Component({
template: `
<div notOnSelf>
<div tryInjectFromSelf></div>
</div>
`,
standalone: true,
imports: [DirNotOnSelf, DirTryInjectFromSelf],
})
class App {}
expect(() => {
TestBed.createComponent(App).detectChanges();
}).toThrowError(
'NG0201: No provider for DirNotOnSelf found in NodeInjector. Find more at https://angular.dev/errors/NG0201',
);
});
});
});
describe('ɵɵinject', () => {
describe('bloom filter', () => {
let mockTView: any;
beforeEach(() => {
mockTView = {data: [0, 0, 0, 0, 0, 0, 0, 0, null], firstCreatePass: true};
});
function bloomState() {
return mockTView.data.slice(0, NodeInjectorOffset.TNODE).reverse();
}
class Dir0 {
/** @internal */ static __NG_ELEMENT_ID__ = 0;
}
class Dir1 {
/** @internal */ static __NG_ELEMENT_ID__ = 1;
}
class Dir33 {
/** @internal */ static __NG_ELEMENT_ID__ = 33;
}
class Dir66 {
/** @internal */ static __NG_ELEMENT_ID__ = 66;
}
class Dir99 {
/** @internal */ static __NG_ELEMENT_ID__ = 99;
}
class Dir132 {
/** @internal */ static __NG_ELEMENT_ID__ = 132;
}
class Dir165 {
/** @internal */ static __NG_ELEMENT_ID__ = 165;
}
class Dir198 {
/** @internal */ static __NG_ELEMENT_ID__ = 198;
}
class Dir231 {
/** @internal */ static __NG_ELEMENT_ID__ = 231;
}
class Dir260 {
/** @internal */ static __NG_ELEMENT_ID__ = 260;
}
it('should add values', () => {
bloomAdd(0, mockTView, Dir0);
expect(bloomState()).toEqual([0, 0, 0, 0, 0, 0, 0, 1]);
bloomAdd(0, mockTView, Dir33);
expect(bloomState()).toEqual([0, 0, 0, 0, 0, 0, 2, 1]);
bloomAdd(0, mockTView, Dir66);
expect(bloomState()).toEqual([0, 0, 0, 0, 0, 4, 2, 1]);
bloomAdd(0, mockTView, Dir99);
expect(bloomState()).toEqual([0, 0, 0, 0, 8, 4, 2, 1]);
bloomAdd(0, mockTView, Dir132);
expect(bloomState()).toEqual([0, 0, 0, 16, 8, 4, 2, 1]);
bloomAdd(0, mockTView, Dir165);
expect(bloomState()).toEqual([0, 0, 32, 16, 8, 4, 2, 1]);
bloomAdd(0, mockTView, Dir198);
expect(bloomState()).toEqual([0, 64, 32, 16, 8, 4, 2, 1]);
bloomAdd(0, mockTView, Dir231);
expect(bloomState()).toEqual([128, 64, 32, 16, 8, 4, 2, 1]);
bloomAdd(0, mockTView, Dir260);
expect(bloomState()).toEqual([128, 64, 32, 16, 8, 4, 2, 17 /* 1 + 2^(260-256) */]);
});
it('should query values', () => {
bloomAdd(0, mockTView, Dir0);
bloomAdd(0, mockTView, Dir33);
bloomAdd(0, mockTView, Dir66);
bloomAdd(0, mockTView, Dir99);
bloomAdd(0, mockTView, Dir132);
bloomAdd(0, mockTView, Dir165);
bloomAdd(0, mockTView, Dir198);
bloomAdd(0, mockTView, Dir231);
bloomAdd(0, mockTView, Dir260);
expect(bloomHasToken(bloomHash(Dir0) as number, 0, mockTView.data)).toEqual(true);
expect(bloomHasToken(bloomHash(Dir1) as number, 0, mockTView.data)).toEqual(false);
expect(bloomHasToken(bloomHash(Dir33) as number, 0, mockTView.data)).toEqual(true);
expect(bloomHasToken(bloomHash(Dir66) as number, 0, mockTView.data)).toEqual(true);
expect(bloomHasToken(bloomHash(Dir99) as number, 0, mockTView.data)).toEqual(true);
expect(bloomHasToken(bloomHash(Dir132) as number, 0, mockTView.data)).toEqual(true);
expect(bloomHasToken(bloomHash(Dir165) as number, 0, mockTView.data)).toEqual(true);
expect(bloomHasToken(bloomHash(Dir198) as number, 0, mockTView.data)).toEqual(true);
expect(bloomHasToken(bloomHash(Dir231) as number, 0, mockTView.data)).toEqual(true);
expect(bloomHasToken(bloomHash(Dir260) as number, 0, mockTView.data)).toEqual(true);
});
});
});
describe('getOrCreateNodeInjector', () => {
it('should handle initial undefined state', () => {
const contentView = createLView(
null,
createTView(TViewType.Component, null, null, 1, 0, null, null, null, null, null, null),
{},
LViewFlags.CheckAlways,
null,
null,
{
rendererFactory: {} as any,
sanitizer: null,
changeDetectionScheduler: null,
},
{} as any,
null,
null,
null,
);
enterView(contentView);
try {
const parentTNode = getOrCreateTNode(
contentView[TVIEW],
HEADER_OFFSET,
TNodeType.Element,
null,
null,
);
// Simulate the situation where the previous parent is not initialized.
// This happens on first bootstrap because we don't init existing values
// so that we have smaller HelloWorld.
(parentTNode as {parent: any}).parent = undefined;
const injector = getOrCreateNodeInjectorForNode(parentTNode, contentView);
expect(injector).not.toEqual(-1);
} finally {
leaveView();
}
});
});
});
| {
"end_byte": 6587,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/di_spec.ts"
} |
angular/packages/core/test/render3/deps_tracker_spec.ts_0_9253 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, Directive, forwardRef, NgModule, Pipe} from '@angular/core';
import {NgModuleDef} from '../../src/r3_symbols';
import {
ComponentType,
NgModuleType,
ɵsetClassDebugInfo,
ɵɵdefineComponent,
} from '../../src/render3';
import {TEST_ONLY} from '../../src/render3/deps_tracker/deps_tracker';
const {DepsTracker} = TEST_ONLY;
describe('runtime dependency tracker', () => {
let depsTracker = new DepsTracker();
beforeEach(() => {
depsTracker = new DepsTracker();
});
describe('getNgModuleScope method', () => {
it('should include empty scope for a module without any import/declarations/exports', () => {
@NgModule({})
class MainModule {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation).toEqual({
directives: new Set(),
pipes: new Set(),
});
expect(ans.exported).toEqual({
directives: new Set(),
pipes: new Set(),
});
});
it('should throw if applied to a non NgModule type', () => {
class RandomClass {}
expect(() => depsTracker.getNgModuleScope(RandomClass as NgModuleType)).toThrow();
});
describe('exports specs', () => {
it('should include the exported components/directives/pipes in exported scope', () => {
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
@Component({
standalone: false,
})
class Component1 {}
// No ɵcmp added yet.
class AsyncComponent {}
@NgModule({
exports: [Directive1, Pipe1, Component1, AsyncComponent],
})
class MainModule {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.exported).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([Directive1, Component1, AsyncComponent]),
});
});
it('should include the exported scope of an exported module in the exported scope and compilation scope', () => {
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
@Component({
standalone: false,
})
class Component1 {}
@NgModule({
exports: [Directive1, Pipe1, Component1],
})
class SubModule {}
@NgModule({
exports: [SubModule],
})
class MainModule {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.exported).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([Directive1, Component1]),
});
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([Directive1, Component1]),
});
});
it('should combine the directly exported elements with the exported scope of exported module in both exported and compilation scopes', () => {
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
@Component({
standalone: false,
})
class Component1 {}
@NgModule({
exports: [Directive1, Pipe1, Component1],
})
class SubModule {}
@Component({
standalone: false,
})
class MainComponent {}
@NgModule({
exports: [SubModule, MainComponent],
})
class MainModule {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.exported).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([Directive1, Component1, MainComponent]),
});
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([Directive1, Component1]),
});
});
});
describe('import specs', () => {
it('should contain the exported scope of an imported module in compilation scope', () => {
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
@Component({
standalone: false,
})
class Component1 {}
@Component({
standalone: false,
})
class PrivateComponent {}
@NgModule({
exports: [Directive1, Component1, Pipe1],
declarations: [PrivateComponent],
})
class SubModule {}
@NgModule({
imports: [SubModule],
})
class MainModule {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation).toEqual({
directives: new Set([Directive1, Component1]),
pipes: new Set([Pipe1]),
});
});
it('should contain imported standalone components/directive/pipes in compilation scope', () => {
@Directive({standalone: true})
class Directive1 {}
@Pipe({name: 'pipe1', standalone: true})
class Pipe1 {}
@Component({standalone: true})
class Component1 {}
@NgModule({
imports: [Directive1, Pipe1, Component1],
})
class MainModule {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation).toEqual({
directives: new Set([Directive1, Component1]),
pipes: new Set([Pipe1]),
});
});
it('should contain the exported scope of a depth-2 transitively imported module in compilation scope', () => {
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
@Component({
standalone: false,
})
class Component1 {}
@Component({
standalone: false,
})
class PrivateComponent {}
@NgModule({
exports: [Directive1, Component1, Pipe1],
declarations: [PrivateComponent],
})
class SubSubModule {}
@NgModule({exports: [SubSubModule]})
class SubModule {}
@NgModule({
imports: [SubModule],
})
class MainModule {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation).toEqual({
directives: new Set([Directive1, Component1]),
pipes: new Set([Pipe1]),
});
});
it('should poison compilation scope if an import is neither a NgModule nor a standalone component', () => {
class RandomClass {}
@NgModule({
imports: [RandomClass],
})
class MainModule {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation.isPoisoned).toBeTrue();
});
});
describe('declarations specs', () => {
it('should include declared components/directives/pipes as part of compilation scope', () => {
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
@Component({
standalone: false,
})
class Component1 {}
// No ɵcmp added yet.
class AsyncComponent {}
@NgModule({
declarations: [Directive1, Pipe1, Component1, AsyncComponent],
})
class MainModule {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([Directive1, Component1, AsyncComponent]),
});
expect(ans.exported).toEqual({
pipes: new Set(),
directives: new Set(),
});
});
it('should poison the compilation scope if a standalone component is declared', () => {
@Component({standalone: true})
class Component1 {}
@NgModule({
declarations: [Component1],
})
class MainModule {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation.isPoisoned).toBeTrue();
});
it('should poison compilation scope if declare a module', () => {
@NgModule({})
class SubModule {}
@NgModule({
declarations: [SubModule],
})
class MainModule {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation.isPoisoned).toBeTrue();
});
});
| {
"end_byte": 9253,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/deps_tracker_spec.ts"
} |
angular/packages/core/test/render3/deps_tracker_spec.ts_9259_10855 | ibe('cache specs', () => {
it('should use cache for re-calculation', () => {
@Component({
standalone: false,
})
class Component1 {}
@NgModule({
declarations: [Component1],
})
class MainModule {}
let ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation).toEqual({
pipes: new Set(),
directives: new Set([Component1]),
});
// Modify the module
(MainModule as NgModuleType).ɵmod.declarations = [];
ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation).toEqual({
pipes: new Set(),
directives: new Set([Component1]),
});
});
it('should bust the cache correctly', () => {
@Component({
standalone: false,
})
class Component1 {}
@NgModule({
declarations: [Component1],
})
class MainModule {}
let ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation).toEqual({
pipes: new Set(),
directives: new Set([Component1]),
});
// Modify the module
(MainModule as NgModuleType).ɵmod.declarations = [];
depsTracker.clearScopeCacheFor(MainModule as NgModuleType);
ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation).toEqual({
pipes: new Set(),
directives: new Set([]),
});
});
});
d | {
"end_byte": 10855,
"start_byte": 9259,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/deps_tracker_spec.ts"
} |
angular/packages/core/test/render3/deps_tracker_spec.ts_10861_19040 | e('forward ref specs', () => {
it('should include the exported scope of a forward ref imported module in the compilation scope when compiling in JIT mode', () => {
@NgModule({imports: [forwardRef(() => SubModule)]})
class MainModule {}
@Component({
standalone: false,
})
class Component1 {}
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
@NgModule({exports: [Component1, Directive1, Pipe1]})
class SubModule {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([Component1, Directive1]),
});
});
it('should include the exported scope of a forward ref imported module in the compilation scope when compiling in AOT mode', () => {
class MainModule {}
(MainModule as NgModuleType).ɵmod = createNgModuleDef({imports: () => [SubModule]});
@Component({
standalone: false,
})
class Component1 {}
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
@NgModule({exports: [Component1, Directive1, Pipe1]})
class SubModule {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([Component1, Directive1]),
});
});
it('should include forward ref imported standalone component in the compilation scope when compiling in JIT mode', () => {
@NgModule({imports: [forwardRef(() => Component1)]})
class MainModule {}
@Component({standalone: true})
class Component1 {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation).toEqual({
pipes: new Set([]),
directives: new Set([Component1]),
});
});
it('should include forward ref imported standalone component in the compilation scope when compiling in AOT mode', () => {
class MainModule {}
(MainModule as NgModuleType).ɵmod = createNgModuleDef({imports: () => [Component1]});
@Component({standalone: true})
class Component1 {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation).toEqual({
pipes: new Set([]),
directives: new Set([Component1]),
});
});
it('should include the forward ref declarations in the compilation scope when compiling in JIT mode', () => {
@NgModule({
declarations: [
forwardRef(() => Component1),
forwardRef(() => Directive1),
forwardRef(() => Pipe1),
],
})
class MainModule {}
@Component({
standalone: false,
})
class Component1 {}
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([Component1, Directive1]),
});
});
it('should include the forward ref declarations in the compilation scope when compiling in AOT mode', () => {
class MainModule {}
(MainModule as NgModuleType).ɵmod = createNgModuleDef({
declarations: () => [Component1, Directive1, Pipe1],
});
@Component({
standalone: false,
})
class Component1 {}
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([Component1, Directive1]),
});
});
it('should include the exported forward ref components/directives/pipes in exported scope when compiling in JIT mode', () => {
@NgModule({
exports: [
forwardRef(() => Component1),
forwardRef(() => Directive1),
forwardRef(() => Pipe1),
],
})
class MainModule {}
@Component({
standalone: false,
})
class Component1 {}
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.exported).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([Component1, Directive1]),
});
});
it('should include the exported forward ref components/directives/pipes in exported scope when compiling in AOT mode', () => {
class MainModule {}
(MainModule as NgModuleType).ɵmod = createNgModuleDef({
exports: () => [Component1, Directive1, Pipe1],
});
@Component({
standalone: false,
})
class Component1 {}
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.exported).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([Component1, Directive1]),
});
});
it('should include the exported scope of an exported forward ref module in the exported and compilation scope when compiling in JIT mode', () => {
@NgModule({exports: [forwardRef(() => SubModule)]})
class MainModule {}
@Component({
standalone: false,
})
class Component1 {}
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
@NgModule({exports: [Component1, Directive1, Pipe1]})
class SubModule {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([Component1, Directive1]),
});
expect(ans.exported).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([Component1, Directive1]),
});
});
it('should include the exported scope of an exported forward ref module in the exported and compilation scopes when compiling in AOT mode', () => {
class MainModule {}
(MainModule as NgModuleType).ɵmod = createNgModuleDef({exports: () => [SubModule]});
@Component({
standalone: false,
})
class Component1 {}
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
@NgModule({exports: [Component1, Directive1, Pipe1]})
class SubModule {}
const ans = depsTracker.getNgModuleScope(MainModule as NgModuleType);
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([Component1, Directive1]),
});
expect(ans.exported).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([Component1, Directive1]),
});
});
});
});
describe | {
"end_byte": 19040,
"start_byte": 10861,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/deps_tracker_spec.ts"
} |
angular/packages/core/test/render3/deps_tracker_spec.ts_19044_27832 | tStandaloneComponentScope method', () => {
it('should only include the component itself in the compilation scope when there is no imports', () => {
class MainComponent {}
const ans = depsTracker.getStandaloneComponentScope(MainComponent as ComponentType<any>, []);
expect(ans.compilation).toEqual({
pipes: new Set([]),
directives: new Set([MainComponent]),
ngModules: new Set([]),
});
});
it('should include the imported standalone component/directive/pipes in the compilation scope', () => {
@Component({standalone: true})
class Component1 {}
@Directive({standalone: true})
class Directive1 {}
@Pipe({name: 'pipe1', standalone: true})
class Pipe1 {}
class MainComponent {}
const ans = depsTracker.getStandaloneComponentScope(MainComponent as ComponentType<any>, [
Component1,
Directive1,
Pipe1,
]);
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([MainComponent, Component1, Directive1]),
ngModules: new Set([]),
});
});
it('should include the imported standalone component/directive/pipes in the compilation scope - nested array case', () => {
@Component({standalone: true})
class Component1 {}
@Directive({standalone: true})
class Directive1 {}
@Pipe({name: 'pipe1', standalone: true})
class Pipe1 {}
class MainComponent {}
const ans = depsTracker.getStandaloneComponentScope(MainComponent as ComponentType<any>, [
[[Component1], Directive1],
[[[Pipe1]]],
]);
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([MainComponent, Component1, Directive1]),
ngModules: new Set([]),
});
});
it('should poison the compilation scope if an import is not standalone', () => {
@Component({
standalone: false,
})
class Component1 {}
class MainComponent {}
const ans = depsTracker.getStandaloneComponentScope(MainComponent as ComponentType<any>, [
Component1,
]);
expect(ans.compilation.isPoisoned).toBeTrue();
});
it('should include the imported module and its exported scope in the compilation scope', () => {
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
@Component({
standalone: false,
})
class Component1 {}
@Component({
standalone: false,
})
class PrivateComponent {}
@NgModule({
exports: [Directive1, Component1, Pipe1],
declarations: [PrivateComponent],
})
class SubSubModule {}
class MainComponent {}
const ans = depsTracker.getStandaloneComponentScope(MainComponent as ComponentType<any>, [
SubSubModule,
]);
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([MainComponent, Component1, Directive1]),
ngModules: new Set([SubSubModule]),
});
});
it('should include the imported module and its exported scope in the compilation scope - case of nested array imports', () => {
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
@Component({
standalone: false,
})
class Component1 {}
@Component({
standalone: false,
})
class PrivateComponent {}
@NgModule({
exports: [Directive1, Component1, Pipe1],
declarations: [PrivateComponent],
})
class SubSubModule {}
class MainComponent {}
const ans = depsTracker.getStandaloneComponentScope(MainComponent as ComponentType<any>, [
[SubSubModule],
]);
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([MainComponent, Component1, Directive1]),
ngModules: new Set([SubSubModule]),
});
});
it('should resolve the imported forward refs and include them in the compilation scope', () => {
@Component({standalone: true})
class Component1 {}
@Directive({standalone: true})
class Directive1 {}
@Pipe({name: 'pipe1', standalone: true})
class Pipe1 {}
@Component({
standalone: false,
})
class SubModuleComponent {}
@Directive({
standalone: false,
})
class SubModuleDirective {}
@Pipe({
name: 'submodule pipe',
standalone: false,
})
class SubModulePipe {}
@NgModule({exports: [SubModuleComponent, SubModulePipe, SubModuleDirective]})
class SubModule {}
class MainComponent {}
const ans = depsTracker.getStandaloneComponentScope(MainComponent as ComponentType<any>, [
forwardRef(() => Component1),
forwardRef(() => Directive1),
forwardRef(() => Pipe1),
forwardRef(() => SubModule),
]);
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1, SubModulePipe]),
directives: new Set([
MainComponent,
Component1,
Directive1,
SubModuleComponent,
SubModuleDirective,
]),
ngModules: new Set([SubModule]),
});
});
it('should resolve the imported forward refs and include them in the compilation scope - case of nested array imports', () => {
@Component({standalone: true})
class Component1 {}
@Directive({standalone: true})
class Directive1 {}
@Pipe({name: 'pipe1', standalone: true})
class Pipe1 {}
@Component({
standalone: false,
})
class SubModuleComponent {}
@Directive({
standalone: false,
})
class SubModuleDirective {}
@Pipe({
name: 'submodule pipe',
standalone: false,
})
class SubModulePipe {}
@NgModule({exports: [SubModuleComponent, SubModulePipe, SubModuleDirective]})
class SubModule {}
class MainComponent {}
const ans = depsTracker.getStandaloneComponentScope(MainComponent as ComponentType<any>, [
[forwardRef(() => Component1)],
[forwardRef(() => Directive1)],
[forwardRef(() => Pipe1)],
[forwardRef(() => SubModule)],
]);
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1, SubModulePipe]),
directives: new Set([
MainComponent,
Component1,
Directive1,
SubModuleComponent,
SubModuleDirective,
]),
ngModules: new Set([SubModule]),
});
});
it('should cache the computed scopes', () => {
@Component({standalone: true})
class Component1 {}
@Directive({standalone: true})
class Directive1 {}
@Pipe({name: 'pipe1', standalone: true})
class Pipe1 {}
class MainComponent {}
let ans = depsTracker.getStandaloneComponentScope(MainComponent as ComponentType<any>, [
Component1,
Directive1,
Pipe1,
]);
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([MainComponent, Component1, Directive1]),
ngModules: new Set([]),
});
ans = depsTracker.getStandaloneComponentScope(MainComponent as ComponentType<any>, []);
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([MainComponent, Component1, Directive1]),
ngModules: new Set([]),
});
});
it('should clear the cache correctly', () => {
@Component({standalone: true})
class Component1 {}
@Directive({standalone: true})
class Directive1 {}
@Pipe({name: 'pipe1', standalone: true})
class Pipe1 {}
@Component({
standalone: false,
})
class MainComponent {}
let ans = depsTracker.getStandaloneComponentScope(MainComponent as ComponentType<any>, [
Component1,
Directive1,
Pipe1,
]);
expect(ans.compilation).toEqual({
pipes: new Set([Pipe1]),
directives: new Set([MainComponent, Component1, Directive1]),
ngModules: new Set([]),
});
depsTracker.clearScopeCacheFor(MainComponent as ComponentType<any>);
ans = depsTracker.getStandaloneComponentScope(MainComponent as ComponentType<any>, []);
expect(ans.compilation).toEqual({
pipes: new Set([]),
directives: new Set([MainComponent]),
ngModules: new Set([]),
});
});
});
describe | {
"end_byte": 27832,
"start_byte": 19044,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/deps_tracker_spec.ts"
} |
angular/packages/core/test/render3/deps_tracker_spec.ts_27836_37376 | tComponentDependencies method', () => {
describe('for non-standalone component', () => {
it('should include the compilation scope of the declaring module', () => {
@Component({
standalone: false,
})
class Component1 {}
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
@Component({
standalone: false,
})
class MainComponent {}
@NgModule({
declarations: [MainComponent, Component1, Directive1, Pipe1],
})
class MainModule {}
depsTracker.registerNgModule(MainModule as NgModuleType, {});
const ans = depsTracker.getComponentDependencies(MainComponent as ComponentType<any>);
expect(ans.dependencies).toEqual(
jasmine.arrayWithExactContents([MainComponent, Component1, Directive1, Pipe1]),
);
});
it('should include the compilation scope of the declaring module when it is forward referenced', () => {
@Component({
standalone: false,
})
class Component1 {}
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
@Component({
standalone: false,
})
class MainComponent {}
class MainModule {}
(MainModule as NgModuleType).ɵmod = createNgModuleDef({
declarations: () => [MainComponent, Component1, Directive1, Pipe1],
});
depsTracker.registerNgModule(MainModule as NgModuleType, {});
const ans = depsTracker.getComponentDependencies(MainComponent as ComponentType<any>);
expect(ans.dependencies).toEqual(
jasmine.arrayWithExactContents([MainComponent, Component1, Directive1, Pipe1]),
);
});
it('should return empty dependencies if component has no registered module', () => {
@Component({
standalone: false,
})
class MainComponent {}
ɵsetClassDebugInfo(MainComponent, {
className: 'MainComponent',
filePath: 'main.ts',
lineNumber: 11,
});
const ans = depsTracker.getComponentDependencies(MainComponent as ComponentType<any>);
expect(ans.dependencies).toEqual([]);
});
it('should return empty deps if the compilation scope of the declaring module is corrupted', () => {
class RandomClass {}
@Component({
standalone: false,
})
class MainComponent {}
class MainModule {}
(MainModule as NgModuleType).ɵmod = createNgModuleDef({
declarations: [MainComponent],
// Importing an invalid class makes the compilation scope corrupted.
imports: [RandomClass],
});
depsTracker.registerNgModule(MainModule as NgModuleType, {});
const ans = depsTracker.getComponentDependencies(MainComponent as ComponentType<any>);
expect(ans.dependencies).toEqual([]);
});
});
describe('for standalone component', () => {
it('should always return self (even if component has empty imports)', () => {
@Component({standalone: true})
class MainComponent {}
const ans = depsTracker.getComponentDependencies(MainComponent as ComponentType<any>);
expect(ans.dependencies).toEqual([MainComponent]);
});
it('should include imported standalone component/directive/pipe', () => {
@Component({standalone: true})
class Component1 {}
@Directive({standalone: true})
class Directive1 {}
@Pipe({name: 'pipe1', standalone: true})
class Pipe1 {}
@Component({standalone: true})
class MainComponent {}
const ans = depsTracker.getComponentDependencies(MainComponent as ComponentType<any>, [
Component1,
Directive1,
Pipe1,
]);
expect(ans.dependencies).toEqual(
jasmine.arrayWithExactContents([MainComponent, Component1, Directive1, Pipe1]),
);
});
it('should include imported forward ref standalone component/directive/pipe', () => {
@Component({standalone: true})
class Component1 {}
@Directive({standalone: true})
class Directive1 {}
@Pipe({name: 'pipe1', standalone: true})
class Pipe1 {}
@Component({standalone: true})
class MainComponent {}
const ans = depsTracker.getComponentDependencies(MainComponent as ComponentType<any>, [
forwardRef(() => Component1),
forwardRef(() => Directive1),
forwardRef(() => Pipe1),
]);
expect(ans.dependencies).toEqual(
jasmine.arrayWithExactContents([MainComponent, Component1, Directive1, Pipe1]),
);
});
it('should ignore imported non-standalone component/directive/pipe', () => {
@Component({
standalone: false,
})
class Component1 {}
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
@Component({standalone: true})
class MainComponent {}
const ans = depsTracker.getComponentDependencies(MainComponent as ComponentType<any>, [
Component1,
Directive1,
Pipe1,
]);
expect(ans.dependencies).toEqual([]);
});
it('should include the imported module and its exported scope', () => {
@Component({
standalone: false,
})
class Component1 {}
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
@NgModule({
exports: [Component1, Directive1, Pipe1],
})
class SubModule {}
@Component({standalone: true})
class MainComponent {}
const ans = depsTracker.getComponentDependencies(MainComponent as ComponentType<any>, [
SubModule,
]);
expect(ans.dependencies).toEqual(
jasmine.arrayWithExactContents([MainComponent, Component1, Directive1, Pipe1, SubModule]),
);
});
it('should include the imported forward ref module and its exported scope', () => {
@Component({
standalone: false,
})
class Component1 {}
@Directive({
standalone: false,
})
class Directive1 {}
@Pipe({
name: 'pipe1',
standalone: false,
})
class Pipe1 {}
@NgModule({
exports: [Component1, Directive1, Pipe1],
})
class SubModule {}
@Component({standalone: true})
class MainComponent {}
const ans = depsTracker.getComponentDependencies(MainComponent as ComponentType<any>, [
forwardRef(() => SubModule),
]);
expect(ans.dependencies).toEqual(
jasmine.arrayWithExactContents([MainComponent, Component1, Directive1, Pipe1, SubModule]),
);
});
it('should use cache for re-calculation', () => {
@Component({standalone: true})
class Component1 {}
@Component({standalone: true})
class MainComponent {}
let ans = depsTracker.getComponentDependencies(MainComponent as ComponentType<any>, [
Component1,
]);
expect(ans.dependencies).toEqual(
jasmine.arrayWithExactContents([MainComponent, Component1]),
);
ans = depsTracker.getComponentDependencies(MainComponent as ComponentType<any>, [
Component1,
]);
expect(ans.dependencies).toEqual(
jasmine.arrayWithExactContents([MainComponent, Component1]),
);
});
});
});
describe('isOrphanComponent method', () => {
it('should return true for non-standalone component without NgModule', () => {
@Component({
standalone: false,
})
class MainComponent {}
expect(depsTracker.isOrphanComponent(MainComponent as ComponentType<any>)).toBeTrue();
});
it('should return false for standalone component', () => {
@Component({
standalone: true,
})
class MainComponent {}
expect(depsTracker.isOrphanComponent(MainComponent as ComponentType<any>)).toBeFalse();
});
it('should return false for non-standalone component with its NgModule', () => {
@Component({
standalone: false,
})
class MainComponent {}
@NgModule({
declarations: [MainComponent],
})
class MainModule {}
depsTracker.registerNgModule(MainModule as NgModuleType, {});
expect(depsTracker.isOrphanComponent(MainComponent as ComponentType<any>)).toBeFalse();
});
it('should return false for class which is not a component', () => {
class RandomClass {}
expect(depsTracker.isOrphanComponent(RandomClass as ComponentType<any>)).toBeFalse();
});
});
});
function createNgModuleDef(data: Partial<NgModuleDef<any>>): NgModuleDef<any> {
return {
bootstrap: [],
declarations: [],
exports: [],
imports: [],
...data,
} as NgModuleDef<any>;
}
| {
"end_byte": 37376,
"start_byte": 27836,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/deps_tracker_spec.ts"
} |
angular/packages/core/test/render3/load_domino.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
*/
// Needed to run animation tests
import '@angular/compiler'; // For JIT mode. Must be in front of any other @angular/* imports.
import {ɵgetDOM as getDOM} from '@angular/common';
import {DominoAdapter} from '@angular/platform-server/src/domino_adapter';
if (typeof window == 'undefined') {
const domino = require('../../../platform-server/src/bundled-domino');
DominoAdapter.makeCurrent();
(global as any).document = getDOM().getDefaultDocument();
// For animation tests, see
// https://github.com/angular/angular/blob/main/packages/animations/browser/src/render/shared.ts#L140
(global as any).Element = domino.impl.Element;
(global as any).isBrowser = false;
(global as any).isNode = true;
(global as any).Event = domino.impl.Event;
}
| {
"end_byte": 963,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/load_domino.ts"
} |
angular/packages/core/test/render3/component_ref_spec.ts_0_3116 | /**
* @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 {ComponentRef} from '@angular/core';
import {ComponentFactoryResolver} from '@angular/core/src/render3/component_ref';
import {Renderer} from '@angular/core/src/render3/interfaces/renderer';
import {RElement} from '@angular/core/src/render3/interfaces/renderer_dom';
import {TestBed} from '@angular/core/testing';
import {
ChangeDetectionStrategy,
Component,
Injector,
Input,
NgModuleRef,
OnChanges,
Output,
RendererType2,
SimpleChanges,
ViewChild,
ViewContainerRef,
ViewEncapsulation,
} from '../../src/core';
import {ComponentFactory} from '../../src/linker/component_factory';
import {RendererFactory2} from '../../src/render/api';
import {Sanitizer} from '../../src/sanitization/sanitizer';
import {MockRendererFactory} from './instructions/mock_renderer_factory';
const THROWING_RENDERER_FACTOR2_PROVIDER = {
provide: RendererFactory2,
useValue: {
createRenderer: () => {
throw new Error('Incorrect injector for Renderer2');
},
},
};
describe('ComponentFactory', () => {
const cfr = new ComponentFactoryResolver();
describe('constructor()', () => {
it('should correctly populate default properties', () => {
@Component({
selector: 'test[foo], bar',
standalone: true,
template: '',
})
class TestComponent {}
const cf = cfr.resolveComponentFactory(TestComponent);
expect(cf.selector).toBe('test[foo],bar');
expect(cf.componentType).toBe(TestComponent);
expect(cf.ngContentSelectors).toEqual([]);
expect(cf.inputs).toEqual([]);
expect(cf.outputs).toEqual([]);
});
it('should correctly populate defined properties', () => {
function transformFn() {}
@Component({
selector: 'test[foo], bar',
standalone: true,
template: `
<ng-content></ng-content>
<ng-content select="a"></ng-content>
<ng-content select="b"></ng-content>
`,
})
class TestComponent {
@Input() in1: unknown;
@Input('input-attr-2') in2: unknown;
@Input({alias: 'input-attr-3', transform: transformFn}) in3: unknown;
@Output() out1: unknown;
@Output('output-attr-2') out2: unknown;
}
const cf = cfr.resolveComponentFactory(TestComponent);
expect(cf.componentType).toBe(TestComponent);
expect(cf.ngContentSelectors).toEqual(['*', 'a', 'b']);
expect(cf.selector).toBe('test[foo],bar');
expect(cf.inputs).toEqual([
{propName: 'in1', templateName: 'in1', isSignal: false},
{propName: 'in2', templateName: 'input-attr-2', isSignal: false},
{propName: 'in3', templateName: 'input-attr-3', transform: transformFn, isSignal: false},
]);
expect(cf.outputs).toEqual([
{propName: 'out1', templateName: 'out1'},
{propName: 'out2', templateName: 'output-attr-2'},
]);
});
}); | {
"end_byte": 3116,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/component_ref_spec.ts"
} |
angular/packages/core/test/render3/component_ref_spec.ts_3120_10604 | describe('create()', () => {
let rendererFactorySpy = new MockRendererFactory();
let cf: ComponentFactory<any>;
beforeEach(() => {
@Component({
selector: 'test',
template: '...',
host: {
'class': 'HOST_COMPONENT',
},
encapsulation: ViewEncapsulation.None,
standalone: false,
})
class TestComponent {}
cf = cfr.resolveComponentFactory(TestComponent);
});
describe('(when `ngModuleRef` is not provided)', () => {
it('should retrieve `RendererFactory2` from the specified injector', () => {
const injector = Injector.create({
providers: [{provide: RendererFactory2, useValue: rendererFactorySpy}],
});
cf.create(injector);
expect(rendererFactorySpy.wasCalled).toBeTrue();
});
it('should retrieve `Sanitizer` from the specified injector', () => {
const sanitizerFactorySpy = jasmine.createSpy('sanitizerFactory').and.returnValue({});
const injector = Injector.create({
providers: [
{provide: RendererFactory2, useValue: rendererFactorySpy},
{provide: Sanitizer, useFactory: sanitizerFactorySpy, deps: []},
],
});
cf.create(injector);
expect(sanitizerFactorySpy).toHaveBeenCalled();
});
});
describe('(when `ngModuleRef` is provided)', () => {
it('should retrieve `RendererFactory2` from the specified injector first', () => {
const injector = Injector.create({
providers: [{provide: RendererFactory2, useValue: rendererFactorySpy}],
});
const mInjector = Injector.create({providers: [THROWING_RENDERER_FACTOR2_PROVIDER]});
cf.create(injector, undefined, undefined, {injector: mInjector} as NgModuleRef<any>);
expect(rendererFactorySpy.wasCalled).toBeTrue();
});
it('should retrieve `RendererFactory2` from the `ngModuleRef` if not provided by the injector', () => {
const injector = Injector.create({providers: []});
const mInjector = Injector.create({
providers: [{provide: RendererFactory2, useValue: rendererFactorySpy}],
});
cf.create(injector, undefined, undefined, {injector: mInjector} as NgModuleRef<any>);
expect(rendererFactorySpy.wasCalled).toBeTrue();
});
it('should retrieve `Sanitizer` from the specified injector first', () => {
const iSanitizerFactorySpy = jasmine
.createSpy('Injector#sanitizerFactory')
.and.returnValue({});
const injector = Injector.create({
providers: [{provide: Sanitizer, useFactory: iSanitizerFactorySpy, deps: []}],
});
const mSanitizerFactorySpy = jasmine
.createSpy('NgModuleRef#sanitizerFactory')
.and.returnValue({});
const mInjector = Injector.create({
providers: [
{provide: RendererFactory2, useValue: rendererFactorySpy},
{provide: Sanitizer, useFactory: mSanitizerFactorySpy, deps: []},
],
});
cf.create(injector, undefined, undefined, {injector: mInjector} as NgModuleRef<any>);
expect(iSanitizerFactorySpy).toHaveBeenCalled();
expect(mSanitizerFactorySpy).not.toHaveBeenCalled();
});
it('should retrieve `Sanitizer` from the `ngModuleRef` if not provided by the injector', () => {
const injector = Injector.create({providers: []});
const mSanitizerFactorySpy = jasmine
.createSpy('NgModuleRef#sanitizerFactory')
.and.returnValue({});
const mInjector = Injector.create({
providers: [
{provide: RendererFactory2, useValue: rendererFactorySpy},
{provide: Sanitizer, useFactory: mSanitizerFactorySpy, deps: []},
],
});
cf.create(injector, undefined, undefined, {injector: mInjector} as NgModuleRef<any>);
expect(mSanitizerFactorySpy).toHaveBeenCalled();
});
});
describe('(when the factory is bound to a `ngModuleRef`)', () => {
it('should retrieve `RendererFactory2` from the specified injector first', () => {
const injector = Injector.create({
providers: [{provide: RendererFactory2, useValue: rendererFactorySpy}],
});
(cf as any).ngModule = {
injector: Injector.create({providers: [THROWING_RENDERER_FACTOR2_PROVIDER]}),
};
cf.create(injector);
expect(rendererFactorySpy.wasCalled).toBeTrue();
});
it('should retrieve `RendererFactory2` from the `ngModuleRef` if not provided by the injector', () => {
const injector = Injector.create({providers: []});
(cf as any).ngModule = {
injector: Injector.create({
providers: [{provide: RendererFactory2, useValue: rendererFactorySpy}],
}),
};
cf.create(injector);
expect(rendererFactorySpy.wasCalled).toBeTrue();
});
it('should retrieve `Sanitizer` from the specified injector first', () => {
const iSanitizerFactorySpy = jasmine
.createSpy('Injector#sanitizerFactory')
.and.returnValue({});
const injector = Injector.create({
providers: [
{provide: RendererFactory2, useValue: rendererFactorySpy},
{provide: Sanitizer, useFactory: iSanitizerFactorySpy, deps: []},
],
});
const mSanitizerFactorySpy = jasmine
.createSpy('NgModuleRef#sanitizerFactory')
.and.returnValue({});
(cf as any).ngModule = {
injector: Injector.create({
providers: [{provide: Sanitizer, useFactory: mSanitizerFactorySpy, deps: []}],
}),
};
cf.create(injector);
expect(iSanitizerFactorySpy).toHaveBeenCalled();
expect(mSanitizerFactorySpy).not.toHaveBeenCalled();
});
it('should retrieve `Sanitizer` from the `ngModuleRef` if not provided by the injector', () => {
const injector = Injector.create({providers: []});
const mSanitizerFactorySpy = jasmine
.createSpy('NgModuleRef#sanitizerFactory')
.and.returnValue({});
(cf as any).ngModule = {
injector: Injector.create({
providers: [
{provide: RendererFactory2, useValue: rendererFactorySpy},
{provide: Sanitizer, useFactory: mSanitizerFactorySpy, deps: []},
],
}),
};
cf.create(injector);
expect(mSanitizerFactorySpy).toHaveBeenCalled();
});
});
it('should ensure that rendererFactory is called after initial styling is set', () => {
class TestMockRendererFactory extends MockRendererFactory {
override createRenderer(
hostElement: RElement | null,
rendererType: RendererType2 | null,
): Renderer {
if (hostElement) {
hostElement.classList.add('HOST_RENDERER');
}
return super.createRenderer(hostElement, rendererType);
}
}
const injector = Injector.create({
providers: [
{provide: RendererFactory2, useFactory: () => new TestMockRendererFactory(), deps: []},
],
});
const hostNode = document.createElement('div');
const componentRef = cf.create(injector, undefined, hostNode);
expect(hostNode.className).toEqual('HOST_COMPONENT HOST_RENDERER');
});
}); | {
"end_byte": 10604,
"start_byte": 3120,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/component_ref_spec.ts"
} |
angular/packages/core/test/render3/component_ref_spec.ts_10608_15735 | describe('setInput', () => {
it('should allow setting inputs on the ComponentRef', () => {
const inputChangesLog: string[] = [];
@Component({template: `{{in}}`, standalone: false})
class DynamicCmp implements OnChanges {
ngOnChanges(changes: SimpleChanges): void {
const inChange = changes['in'];
inputChangesLog.push(
`${inChange.previousValue}:${inChange.currentValue}:${inChange.firstChange}`,
);
}
@Input() in: string | undefined;
}
const fixture = TestBed.createComponent(DynamicCmp);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('');
expect(inputChangesLog).toEqual([]);
fixture.componentRef.setInput('in', 'first');
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('first');
expect(inputChangesLog).toEqual(['undefined:first:true']);
fixture.componentRef.setInput('in', 'second');
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('second');
expect(inputChangesLog).toEqual(['undefined:first:true', 'first:second:false']);
});
it('should allow setting mapped inputs on the ComponentRef', () => {
@Component({template: `{{in}}`, standalone: false})
class DynamicCmp {
@Input('publicName') in: string | undefined;
}
const fixture = TestBed.createComponent(DynamicCmp);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('');
fixture.componentRef.setInput('publicName', 'in value');
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('in value');
fixture.componentRef.setInput('in', 'should not change');
fixture.detectChanges();
// The value doesn't change, since `in` is an internal name of the input.
expect(fixture.nativeElement.textContent).toBe('in value');
});
it('should log or throw error on unknown inputs', () => {
@Component({template: ``, standalone: false})
class NoInputsCmp {}
const fixture = TestBed.createComponent(NoInputsCmp);
fixture.detectChanges();
spyOn(console, 'error');
fixture.componentRef.setInput('doesNotExist', '');
const msgL1 = `NG0303: Can't set value of the 'doesNotExist' input on the 'NoInputsCmp' component. `;
const msgL2 = `Make sure that the 'doesNotExist' property is annotated with @Input() or a mapped @Input('doesNotExist') exists.`;
expect(console.error).toHaveBeenCalledWith(msgL1 + msgL2);
});
it('should mark components for check when setting an input on a ComponentRef', () => {
@Component({
template: `{{in}}`,
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
class DynamicCmp {
@Input() in: string | undefined;
}
const fixture = TestBed.createComponent(DynamicCmp);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('');
fixture.componentRef.setInput('in', 'pushed');
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('pushed');
});
it('should not set input if value is the same as the previous', () => {
let log: string[] = [];
@Component({
template: `{{in}}`,
standalone: true,
})
class DynamicCmp {
@Input()
set in(v: string) {
log.push(v);
}
}
const fixture = TestBed.createComponent(DynamicCmp);
fixture.componentRef.setInput('in', '1');
fixture.detectChanges();
fixture.componentRef.setInput('in', '1');
fixture.detectChanges();
fixture.componentRef.setInput('in', '2');
fixture.detectChanges();
expect(log).toEqual(['1', '2']);
});
it('marks parents dirty so component is not "shielded" by a non-dirty OnPush parent', () => {
@Component({
template: `{{input}}`,
standalone: true,
selector: 'dynamic',
})
class DynamicCmp {
@Input() input?: string;
}
@Component({
template: '<ng-template #template></ng-template>',
standalone: true,
imports: [DynamicCmp],
changeDetection: ChangeDetectionStrategy.OnPush,
})
class Wrapper {
@ViewChild('template', {read: ViewContainerRef}) template?: ViewContainerRef;
componentRef?: ComponentRef<DynamicCmp>;
create() {
this.componentRef = this.template!.createComponent(DynamicCmp);
}
setInput(value: string) {
this.componentRef!.setInput('input', value);
}
}
const fixture = TestBed.createComponent(Wrapper);
fixture.detectChanges();
fixture.componentInstance.create();
fixture.componentInstance.setInput('1');
fixture.detectChanges();
expect(fixture.nativeElement.innerText).toBe('1');
fixture.componentInstance.setInput('2');
fixture.detectChanges();
expect(fixture.nativeElement.innerText).toBe('2');
});
});
}); | {
"end_byte": 15735,
"start_byte": 10608,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/component_ref_spec.ts"
} |
angular/packages/core/test/render3/node_selector_matcher_spec.ts_0_1336 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {createTNode} from '@angular/core/src/render3/instructions/shared';
import {AttributeMarker} from '../../src/render3/interfaces/attribute_marker';
import {TAttributes, TNode, TNodeType} from '../../src/render3/interfaces/node';
import {CssSelector, CssSelectorList, SelectorFlags} from '../../src/render3/interfaces/projection';
import {
extractAttrsAndClassesFromSelector,
getProjectAsAttrValue,
isNodeMatchingSelector,
isNodeMatchingSelectorList,
stringifyCSSSelectorList,
} from '../../src/render3/node_selector_matcher';
function testLStaticData(tagName: string, attrs: TAttributes | null): TNode {
return createTNode(null!, null, TNodeType.Element, 0, tagName, attrs);
}
describe('css selector matching', () => {
function isMatching(
tagName: string,
attrsOrTNode: TAttributes | TNode | null,
selector: CssSelector,
): boolean {
const tNode =
!attrsOrTNode || Array.isArray(attrsOrTNode)
? createTNode(null!, null, TNodeType.Element, 0, tagName, attrsOrTNode as TAttributes)
: (attrsOrTNode as TNode);
return isNodeMatchingSelector(tNode, selector, true);
} | {
"end_byte": 1336,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/node_selector_matcher_spec.ts"
} |
angular/packages/core/test/render3/node_selector_matcher_spec.ts_1340_9841 | describe('isNodeMatchingSimpleSelector', () => {
describe('element matching', () => {
it('should match element name only if names are the same', () => {
expect(isMatching('span', null, ['span'])).toBeTruthy(
`Selector 'span' should match <span>`,
);
expect(isMatching('span', null, ['div'])).toBeFalsy(
`Selector 'div' should NOT match <span>`,
);
});
/**
* We assume that compiler will lower-case tag names both in node
* and in a selector.
*/
it('should match element name case-sensitively', () => {
expect(isMatching('span', null, ['SPAN'])).toBeFalsy(
`Selector 'SPAN' should NOT match <span>`,
);
expect(isMatching('SPAN', null, ['span'])).toBeFalsy(
`Selector 'span' should NOT match <SPAN>'`,
);
});
it('should never match empty string selector', () => {
expect(isMatching('span', null, [''])).toBeFalsy(`Selector '' should NOT match <span>`);
});
});
describe('attributes matching', () => {
// TODO: do we need to differentiate no value and empty value? that is: title vs. title="" ?
it('should match single attribute without value', () => {
expect(isMatching('span', ['title', ''], ['', 'title', ''])).toBeTruthy(
`Selector '[title]' should match <span title>`,
);
expect(isMatching('span', ['title', 'my title'], ['', 'title', ''])).toBeTruthy(
`Selector '[title]' should match <span title="my title">`,
);
expect(isMatching('span', ['name', 'name'], ['', 'title', ''])).toBeFalsy(
`Selector '[title]' should NOT match <span name="name">`,
);
expect(isMatching('span', null, ['', 'title', ''])).toBeFalsy(
`Selector '[title]' should NOT match <span>`,
);
expect(isMatching('span', ['title', ''], ['', 'other', ''])).toBeFalsy(
`Selector '[other]' should NOT match <span title="">'`,
);
});
// TODO: this case will not work, need more discussion
// https://github.com/angular/angular/pull/34625#discussion_r401791275
xit('should match namespaced attributes', () => {
expect(
isMatching(
'span',
[AttributeMarker.NamespaceURI, 'http://some/uri', 'title', 'name'],
['', 'title', ''],
),
).toBeTruthy();
});
it('should match selector with one attribute without value when element has several attributes', () => {
expect(
isMatching('span', ['id', 'my_id', 'title', 'test_title'], ['', 'title', '']),
).toBeTruthy(`Selector '[title]' should match <span id="my_id" title="test_title">`);
});
/**
* We assume that compiler will lower-case all selectors when generating code
*/
it('should match single attribute with value', () => {
expect(isMatching('span', ['title', 'My Title'], ['', 'title', 'my title'])).toBeTruthy(
`Selector '[title="My Title"]' should match <span title="My Title">'`,
);
expect(isMatching('span', ['title', 'My Title'], ['', 'title', 'other title'])).toBeFalsy(
`Selector '[title="Other Title"]' should NOT match <span title="My Title">`,
);
});
it('should not match attribute when element name does not match', () => {
expect(isMatching('span', ['title', 'My Title'], ['div', 'title', ''])).toBeFalsy(
`Selector 'div[title]' should NOT match <span title="My Title">`,
);
expect(isMatching('span', ['title', 'My Title'], ['div', 'title', 'my title'])).toBeFalsy(
`Selector 'div[title="My Title"]' should NOT match <span title="My Title">`,
);
});
it('should match multiple attributes', () => {
// selector: '[title=title][name=name]'
const selector = ['', 'title', 'title', 'name', 'name'];
// <span title="title" name="name">
expect(isMatching('span', ['title', 'title', 'name', 'name'], selector)).toBeTruthy(
`Selector '[title=title][name=name]' should NOT match <span title="title" name="name">`,
);
// <span title="title">
expect(isMatching('span', ['title', 'title'], selector)).toBeFalsy(
`Selector '[title=title][name=name]' should NOT match <span title="title">`,
);
// <span name="name">
expect(isMatching('span', ['name', 'name'], selector)).toBeFalsy(
`Selector '[title=title][name=name]' should NOT match <span name="name">`,
);
});
it('should handle attribute values that match attribute names', () => {
// selector: [name=name]
const selector = ['', 'name', 'name'];
// <span title="name">
expect(isMatching('span', ['title', 'name'], selector)).toBeFalsy(
`Selector '[name=name]' should NOT match <span title="name">`,
);
// <span title="name" name="name">
expect(isMatching('span', ['title', 'name', 'name', 'name'], selector)).toBeTruthy(
`Selector '[name=name]' should match <span title="name" name="name">`,
);
});
/**
* We assume that compiler will lower-case all selectors and attribute names when generating
* code
*/
it('should match attribute name case-sensitively', () => {
expect(isMatching('span', ['foo', ''], ['', 'foo', ''])).toBeTruthy(
`Selector '[foo]' should match <span foo>`,
);
expect(isMatching('span', ['foo', ''], ['', 'Foo', ''])).toBeFalsy(
`Selector '[Foo]' should NOT match <span foo>`,
);
});
it('should match attribute values case-insensitively', () => {
expect(isMatching('span', ['foo', 'Bar'], ['', 'foo', 'bar'])).toBeTruthy(
`Selector '[foo="bar"]' should match <span foo="Bar">`,
);
});
it('should match class as an attribute', () => {
expect(isMatching('span', ['class', 'foo'], ['', 'class', ''])).toBeTruthy(
`Selector '[class]' should match <span class="foo">`,
);
expect(isMatching('span', ['class', 'foo'], ['', 'class', 'foo'])).toBeTruthy(
`Selector '[class="foo"]' should match <span class="foo">`,
);
});
it('should take optional binding attribute names into account', () => {
expect(
isMatching('span', [AttributeMarker.Bindings, 'directive'], ['', 'directive', '']),
).toBeTruthy(`Selector '[directive]' should match <span [directive]="exp">`);
});
it('should not match optional binding attribute names if attribute selector has value', () => {
expect(
isMatching('span', [AttributeMarker.Bindings, 'directive'], ['', 'directive', 'value']),
).toBeFalsy(`Selector '[directive=value]' should not match <span [directive]="exp">`);
});
it('should not match optional binding attribute names if attribute selector has value and next name equals to value', () => {
expect(
isMatching(
'span',
[AttributeMarker.Bindings, 'directive', 'value'],
['', 'directive', 'value'],
),
).toBeFalsy(
`Selector '[directive=value]' should not match <span [directive]="exp" [value]="otherExp">`,
);
});
it('should match bound attributes that come after classes', () => {
expect(
isMatching(
'span',
[
AttributeMarker.Classes,
'my-class',
'other-class',
AttributeMarker.Bindings,
'title',
'directive',
],
['', 'directive', ''],
),
).toBeTruthy(
`Selector '[directive]' should match <span class="my-class other-class" [title]="title" [directive]="exp">`,
);
});
it('should match NOT match classes when looking for directives', () => {
expect(
isMatching(
'span',
[
AttributeMarker.Classes,
'directive',
'other-class',
AttributeMarker.Bindings,
'title',
],
['', 'directive', ''],
),
).toBeFalsy(
`Selector '[directive]' should NOT match <span class="directive other-class" [title]="title">`,
);
});
}); | {
"end_byte": 9841,
"start_byte": 1340,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/node_selector_matcher_spec.ts"
} |
angular/packages/core/test/render3/node_selector_matcher_spec.ts_9847_14043 | describe('class matching', () => {
it('should match with a class selector when an element has multiple classes', () => {
expect(
isMatching('span', ['class', 'foo bar'], ['', SelectorFlags.CLASS, 'foo']),
).toBeTruthy(`Selector '.foo' should match <span class="foo bar">`);
expect(
isMatching('span', ['class', 'foo bar'], ['', SelectorFlags.CLASS, 'bar']),
).toBeTruthy(`Selector '.bar' should match <span class="foo bar">`);
expect(
isMatching('span', ['class', 'foo bar'], ['', SelectorFlags.CLASS, 'baz']),
).toBeFalsy(`Selector '.baz' should NOT match <span class="foo bar">`);
});
it('should not match on partial class name', () => {
expect(isMatching('span', ['class', 'foobar'], ['', SelectorFlags.CLASS, 'foo'])).toBeFalsy(
`Selector '.foo' should NOT match <span class="foobar">`,
);
expect(isMatching('span', ['class', 'foobar'], ['', SelectorFlags.CLASS, 'bar'])).toBeFalsy(
`Selector '.bar' should NOT match <span class="foobar">`,
);
expect(isMatching('span', ['class', 'foobar'], ['', SelectorFlags.CLASS, 'ob'])).toBeFalsy(
`Selector '.ob' should NOT match <span class="foobar">`,
);
expect(
isMatching('span', ['class', 'foobar'], ['', SelectorFlags.CLASS, 'foobar']),
).toBeTruthy(`Selector '.foobar' should match <span class="foobar">`);
});
it('should support selectors with multiple classes', () => {
expect(
isMatching('span', ['class', 'foo bar'], ['', SelectorFlags.CLASS, 'foo', 'bar']),
).toBeTruthy(`Selector '.foo.bar' should match <span class="foo bar">`);
expect(
isMatching('span', ['class', 'foo'], ['', SelectorFlags.CLASS, 'foo', 'bar']),
).toBeFalsy(`Selector '.foo.bar' should NOT match <span class="foo">`);
expect(
isMatching('span', ['class', 'bar'], ['', SelectorFlags.CLASS, 'foo', 'bar']),
).toBeFalsy(`Selector '.foo.bar' should NOT match <span class="bar">`);
});
it('should support selectors with multiple classes regardless of class name order', () => {
expect(
isMatching('span', ['class', 'foo bar'], ['', SelectorFlags.CLASS, 'bar', 'foo']),
).toBeTruthy(`Selector '.bar.foo' should match <span class="foo bar">`);
expect(
isMatching('span', ['class', 'bar foo'], ['', SelectorFlags.CLASS, 'foo', 'bar']),
).toBeTruthy(`Selector '.foo.bar' should match <span class="bar foo">`);
expect(
isMatching('span', ['class', 'bar foo'], ['', SelectorFlags.CLASS, 'bar', 'foo']),
).toBeTruthy(`Selector '.bar.foo' should match <span class="bar foo">`);
});
/**
* We assume that compiler will lower-case all selectors when generating code
*/
it('should match class name case-insensitively', () => {
expect(isMatching('span', ['class', 'Foo'], ['', SelectorFlags.CLASS, 'foo'])).toBeTruthy(
`Selector '.Foo' should match <span class="Foo">`,
);
});
it('should work without a class attribute', () => {
// selector: '.foo'
const selector = ['', SelectorFlags.CLASS, 'foo'];
// <div title="title">
expect(isMatching('div', ['title', 'title'], selector)).toBeFalsy(
`Selector '.foo' should NOT match <div title="title">`,
);
// <div>
expect(isMatching('div', null, selector)).toBeFalsy(
`Selector '.foo' should NOT match <div>`,
);
});
it('should work with elements, attributes, and classes', () => {
// selector: 'div.foo[title=title]'
const selector = ['div', 'title', 'title', SelectorFlags.CLASS, 'foo'];
// <div class="foo" title="title">
expect(isMatching('div', ['class', 'foo', 'title', 'title'], selector)).toBeTruthy();
// <div title="title">
expect(isMatching('div', ['title', 'title'], selector)).toBeFalsy();
// <div class="foo">
expect(isMatching('div', ['class', 'foo'], selector)).toBeFalsy();
});
});
}); | {
"end_byte": 14043,
"start_byte": 9847,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/node_selector_matcher_spec.ts"
} |
angular/packages/core/test/render3/node_selector_matcher_spec.ts_14047_20576 | describe('negations', () => {
it('should match when negation part is null', () => {
expect(isMatching('span', null, ['span'])).toBeTruthy(`Selector 'span' should match <span>`);
});
it('should not match when negation part does not match', () => {
expect(
isMatching('span', ['foo', ''], ['', SelectorFlags.NOT | SelectorFlags.ELEMENT, 'span']),
).toBeFalsy(`Selector ':not(span)' should NOT match <span foo="">`);
expect(
isMatching(
'span',
['foo', ''],
['span', SelectorFlags.NOT | SelectorFlags.ATTRIBUTE, 'foo', ''],
),
).toBeFalsy(`Selector 'span:not([foo])' should NOT match <span foo="">`);
});
it('should not match negative selector with tag name and attributes', () => {
// selector: ':not(span[foo])'
const selector = ['', SelectorFlags.NOT | SelectorFlags.ELEMENT, 'span', 'foo', ''];
// <span foo="">
expect(isMatching('span', ['foo', ''], selector)).toBeFalsy();
// <span bar="">
expect(isMatching('span', ['bar', ''], selector)).toBeTruthy();
});
it('should not match negative classes', () => {
// selector: ':not(.foo.bar)'
const selector = ['', SelectorFlags.NOT | SelectorFlags.CLASS, 'foo', 'bar'];
// <span class="foo bar">
expect(isMatching('span', ['class', 'foo bar'], selector)).toBeFalsy();
// <span class="foo">
expect(isMatching('span', ['class', 'foo'], selector)).toBeTruthy();
// <span class="bar">
expect(isMatching('span', ['class', 'bar'], selector)).toBeTruthy();
});
it('should not match negative selector with classes and attributes', () => {
// selector: ':not(.baz[title])
const selector = [
'',
SelectorFlags.NOT | SelectorFlags.ATTRIBUTE,
'title',
'',
SelectorFlags.CLASS,
'baz',
];
// <div class="baz">
expect(isMatching('div', ['class', 'baz'], selector)).toBeTruthy();
// <div title="title">
expect(isMatching('div', ['title', 'title'], selector)).toBeTruthy();
// <div class="baz" title="title">
expect(isMatching('div', ['class', 'baz', 'title', 'title'], selector)).toBeFalsy();
});
it('should not match negative selector with attribute selector after', () => {
// selector: ':not(.baz[title]):not([foo])'
const selector = [
'',
SelectorFlags.NOT | SelectorFlags.ATTRIBUTE,
'title',
'',
SelectorFlags.CLASS,
'baz',
SelectorFlags.NOT | SelectorFlags.ATTRIBUTE,
'foo',
'',
];
// <div class="baz">
expect(isMatching('div', ['class', 'baz'], selector)).toBeTruthy();
// <div class="baz" title="">
expect(isMatching('div', ['class', 'baz', 'title', ''], selector)).toBeFalsy();
// <div class="baz" foo="">
expect(isMatching('div', ['class', 'baz', 'foo', ''], selector)).toBeFalsy();
});
it('should not match with multiple negative selectors', () => {
// selector: ':not(span):not([foo])'
const selector = [
'',
SelectorFlags.NOT | SelectorFlags.ELEMENT,
'span',
SelectorFlags.NOT | SelectorFlags.ATTRIBUTE,
'foo',
'',
];
// <div foo="">
expect(isMatching('div', ['foo', ''], selector)).toBeFalsy();
// <span bar="">
expect(isMatching('span', ['bar', ''], selector)).toBeFalsy();
// <div bar="">
expect(isMatching('div', ['bar', ''], selector)).toBeTruthy();
});
it('should evaluate complex selector with negative selectors', () => {
// selector: 'div.foo.bar[name=name]:not(.baz):not([title])'
const selector = [
'div',
'name',
'name',
SelectorFlags.CLASS,
'foo',
'bar',
SelectorFlags.NOT | SelectorFlags.ATTRIBUTE,
'title',
'',
SelectorFlags.NOT | SelectorFlags.CLASS,
'baz',
];
// <div name="name" class="foo bar">
expect(isMatching('div', ['name', 'name', 'class', 'foo bar'], selector)).toBeTruthy();
// <div name="name" class="foo bar baz">
expect(isMatching('div', ['name', 'name', 'class', 'foo bar baz'], selector)).toBeFalsy();
// <div name="name" title class="foo bar">
expect(
isMatching('div', ['name', 'name', 'title', '', 'class', 'foo bar'], selector),
).toBeFalsy();
});
});
describe('isNodeMatchingSelectorList', () => {
function isAnyMatching(
tagName: string,
attrs: string[] | null,
selector: CssSelectorList,
): boolean {
return isNodeMatchingSelectorList(testLStaticData(tagName, attrs), selector, false);
}
it('should match when there is only one simple selector without negations', () => {
expect(isAnyMatching('span', null, [['span']])).toBeTruthy(
`Selector 'span' should match <span>`,
);
expect(isAnyMatching('span', null, [['div']])).toBeFalsy(
`Selector 'div' should NOT match <span>`,
);
});
it('should match when there are multiple parts and only one is matching', () => {
expect(isAnyMatching('span', ['foo', 'bar'], [['div'], ['', 'foo', 'bar']])).toBeTruthy(
`Selector 'div, [foo=bar]' should match <span foo="bar">`,
);
});
it('should not match when there are multiple parts and none is matching', () => {
expect(isAnyMatching('span', ['foo', 'bar'], [['div'], ['', 'foo', 'baz']])).toBeFalsy(
`Selector 'div, [foo=baz]' should NOT match <span foo="bar">`,
);
});
});
describe('reading the ngProjectAs attribute value', function () {
function testTNode(attrs: TAttributes | null) {
return testLStaticData('tag', attrs);
}
it('should get ngProjectAs value if present', function () {
expect(
getProjectAsAttrValue(testTNode([AttributeMarker.ProjectAs, ['tag', 'foo', 'bar']])),
).toEqual(['tag', 'foo', 'bar']);
});
it('should return null if there are no attributes', function () {
expect(getProjectAsAttrValue(testTNode(null))).toBe(null);
});
it('should return if ngProjectAs is not present', function () {
expect(getProjectAsAttrValue(testTNode(['foo', 'bar']))).toBe(null);
});
it('should not accidentally identify ngProjectAs in attribute values', function () {
expect(getProjectAsAttrValue(testTNode(['foo', AttributeMarker.ProjectAs]))).toBe(null);
});
});
}); | {
"end_byte": 20576,
"start_byte": 14047,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/node_selector_matcher_spec.ts"
} |
angular/packages/core/test/render3/node_selector_matcher_spec.ts_20578_26019 | describe('stringifyCSSSelectorList', () => {
it('should stringify selector with a tag name only', () => {
expect(stringifyCSSSelectorList([['button']])).toBe('button');
});
it('should stringify selector with attributes', () => {
expect(stringifyCSSSelectorList([['', 'id', '']])).toBe('[id]');
expect(stringifyCSSSelectorList([['button', 'id', '']])).toBe('button[id]');
expect(stringifyCSSSelectorList([['button', 'id', 'value']])).toBe('button[id="value"]');
expect(stringifyCSSSelectorList([['button', 'id', 'value', 'title', 'other']])).toBe(
'button[id="value"][title="other"]',
);
});
it('should stringify selector with class names', () => {
expect(stringifyCSSSelectorList([['', SelectorFlags.CLASS, 'foo']])).toBe('.foo');
expect(stringifyCSSSelectorList([['button', SelectorFlags.CLASS, 'foo']])).toBe('button.foo');
expect(stringifyCSSSelectorList([['button', SelectorFlags.CLASS, 'foo', 'bar']])).toBe(
'button.foo.bar',
);
expect(
stringifyCSSSelectorList([
['button', 'id', 'value', 'title', 'other', SelectorFlags.CLASS, 'foo', 'bar'],
]),
).toBe('button[id="value"][title="other"].foo.bar');
});
it('should stringify selector with `:not()` rules', () => {
expect(
stringifyCSSSelectorList([['', SelectorFlags.CLASS | SelectorFlags.NOT, 'foo', 'bar']]),
).toBe(':not(.foo.bar)');
expect(
stringifyCSSSelectorList([
['button', SelectorFlags.ATTRIBUTE | SelectorFlags.NOT, 'foo', 'bar'],
]),
).toBe('button:not([foo="bar"])');
expect(stringifyCSSSelectorList([['', SelectorFlags.ELEMENT | SelectorFlags.NOT, 'foo']])).toBe(
':not(foo)',
);
expect(
stringifyCSSSelectorList([
['span', SelectorFlags.CLASS, 'foo', SelectorFlags.CLASS | SelectorFlags.NOT, 'bar', 'baz'],
]),
).toBe('span.foo:not(.bar.baz)');
expect(
stringifyCSSSelectorList([
['span', 'id', 'value', SelectorFlags.ATTRIBUTE | SelectorFlags.NOT, 'title', 'other'],
]),
).toBe('span[id="value"]:not([title="other"])');
expect(
stringifyCSSSelectorList([
[
'',
SelectorFlags.CLASS,
'bar',
SelectorFlags.ATTRIBUTE | SelectorFlags.NOT,
'foo',
'',
SelectorFlags.ELEMENT | SelectorFlags.NOT,
'div',
],
]),
).toBe('.bar:not([foo]):not(div)');
expect(
stringifyCSSSelectorList([
[
'div',
SelectorFlags.ATTRIBUTE | SelectorFlags.NOT,
'foo',
'',
SelectorFlags.CLASS,
'bar',
SelectorFlags.CLASS | SelectorFlags.NOT,
'baz',
],
]),
).toBe('div:not([foo].bar):not(.baz)');
expect(
stringifyCSSSelectorList([
[
'div',
SelectorFlags.ELEMENT | SelectorFlags.NOT,
'p',
SelectorFlags.CLASS,
'bar',
SelectorFlags.CLASS | SelectorFlags.NOT,
'baz',
],
]),
).toBe('div:not(p.bar):not(.baz)');
});
it('should stringify multiple comma-separated selectors', () => {
expect(
stringifyCSSSelectorList([
['', 'id', ''],
['button', 'id', 'value'],
]),
).toBe('[id],button[id="value"]');
expect(
stringifyCSSSelectorList([
['', 'id', ''],
['button', 'id', 'value'],
['div', SelectorFlags.ATTRIBUTE | SelectorFlags.NOT, 'foo', ''],
]),
).toBe('[id],button[id="value"],div:not([foo])');
expect(
stringifyCSSSelectorList([
['', 'id', ''],
['button', 'id', 'value'],
['div', SelectorFlags.ATTRIBUTE | SelectorFlags.NOT, 'foo', ''],
[
'div',
SelectorFlags.ELEMENT | SelectorFlags.NOT,
'p',
SelectorFlags.CLASS,
'bar',
SelectorFlags.CLASS | SelectorFlags.NOT,
'baz',
],
]),
).toBe('[id],button[id="value"],div:not([foo]),div:not(p.bar):not(.baz)');
});
});
describe('extractAttrsAndClassesFromSelector', () => {
const cases = [
[['div', '', ''], [], []],
[
['div', 'attr-a', 'a', 'attr-b', 'b', 'attr-c', ''],
['attr-a', 'a', 'attr-b', 'b', 'attr-c', ''],
[],
],
[
['div', 'attr-a', 'a', SelectorFlags.CLASS, 'class-a', 'class-b', 'class-c'],
['attr-a', 'a'],
['class-a', 'class-b', 'class-c'],
],
[
['', 'attr-a', 'a', SelectorFlags.CLASS, 'class-a', SelectorFlags.ATTRIBUTE, 'attr-b', 'b'],
['attr-a', 'a', 'attr-b', 'b'],
['class-a'],
],
[
[
'',
'',
'',
SelectorFlags.ATTRIBUTE,
'attr-a',
'a',
SelectorFlags.CLASS | SelectorFlags.NOT,
'class-b',
],
['attr-a', 'a'],
[],
],
[
[
'',
'',
'',
SelectorFlags.CLASS | SelectorFlags.NOT,
'class-a',
SelectorFlags.ATTRIBUTE | SelectorFlags.NOT,
'attr-b',
'b',
],
[],
[],
],
];
cases.forEach(([selector, attrs, classes]) => {
it(`should process ${JSON.stringify(selector)} selector`, () => {
const extracted = extractAttrsAndClassesFromSelector(selector);
expect(extracted.attrs).toEqual(attrs as string[]);
expect(extracted.classes).toEqual(classes as string[]);
});
});
}); | {
"end_byte": 26019,
"start_byte": 20578,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/node_selector_matcher_spec.ts"
} |
angular/packages/core/test/render3/instructions/mock_renderer_factory.ts_0_3196 | /**
* @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 {RendererStyleFlags2, RendererType2} from '@angular/core';
import {Renderer, RendererFactory} from '@angular/core/src/render3/interfaces/renderer';
import {RElement} from '@angular/core/src/render3/interfaces/renderer_dom';
export class MockRendererFactory implements RendererFactory {
wasCalled = false;
createRenderer(hostElement: RElement | null, rendererType: RendererType2 | null): Renderer {
this.wasCalled = true;
return new MockRenderer();
}
}
class MockRenderer implements Renderer {
data = {};
destroyNode: ((node: any) => void) | null = null;
destroy(): void {}
createComment(value: string): Comment {
return document.createComment(value);
}
createElement(name: string, namespace?: string | null): RElement {
return namespace
? (document.createElementNS(namespace, name) as unknown as RElement)
: document.createElement(name);
}
createText(value: string): Text {
return document.createTextNode(value);
}
appendChild(parent: RElement, newChild: Node): void {
parent.appendChild(newChild);
}
insertBefore(parent: Node, newChild: Node, refChild: Node | null): void {
parent.insertBefore(newChild, refChild);
}
removeChild(_parent: RElement | null, oldChild: RElement): void {
oldChild.remove();
}
selectRootElement(selectorOrNode: string | any): RElement {
return typeof selectorOrNode === 'string'
? document.querySelector(selectorOrNode)
: selectorOrNode;
}
parentNode(node: Node): RElement | null {
return node.parentNode as RElement | null;
}
nextSibling(node: Node): Node | null {
return node.nextSibling;
}
setAttribute(el: RElement, name: string, value: string, namespace?: string | null): void {
// set all synthetic attributes as properties
if (name[0] === '@') {
this.setProperty(el, name, value);
} else {
el.setAttribute(name, value);
}
}
removeAttribute(el: RElement, name: string, namespace?: string | null): void {}
addClass(el: RElement, name: string): void {
el.classList.add(name);
}
removeClass(el: RElement, name: string): void {
el.classList.remove(name);
}
setStyle(el: RElement, style: string, value: any, flags: RendererStyleFlags2): void {
if (flags & (RendererStyleFlags2.DashCase | RendererStyleFlags2.Important)) {
el.style.setProperty(style, value, flags & RendererStyleFlags2.Important ? 'important' : '');
} else {
el.style.setProperty(style, value);
}
}
removeStyle(el: RElement, style: string, flags?: RendererStyleFlags2): void {
el.style.removeProperty(style);
}
setProperty(el: RElement, name: string, value: any): void {
(el as any)[name] = value;
}
setValue(node: Text, value: string): void {
node.textContent = value;
}
// TODO: Deprecate in favor of addEventListener/removeEventListener
listen(target: Node, eventName: string, callback: (event: any) => boolean | void): () => void {
return () => {};
}
}
| {
"end_byte": 3196,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/instructions/mock_renderer_factory.ts"
} |
angular/packages/core/test/render3/instructions/shared_spec.ts_0_2341 | /**
* @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 {createLView, createTNode, createTView} from '@angular/core/src/render3/instructions/shared';
import {TNodeType} from '@angular/core/src/render3/interfaces/node';
import {
HEADER_OFFSET,
LViewFlags,
TVIEW,
TViewType,
} from '@angular/core/src/render3/interfaces/view';
import {
enterView,
getBindingRoot,
getLView,
setBindingIndex,
setSelectedIndex,
} from '@angular/core/src/render3/state';
import {MockRendererFactory} from './mock_renderer_factory';
/**
* Setups a simple `LView` so that it is possible to do unit tests on instructions.
*
* ```
* describe('styling', () => {
* beforeEach(enterViewWithOneDiv);
* afterEach(leaveView);
*
* it('should ...', () => {
* expect(getLView()).toBeDefined();
* const div = getNativeByIndex(1, getLView());
* });
* });
* ```
*/
export function enterViewWithOneDiv() {
const rendererFactory = new MockRendererFactory();
const renderer = rendererFactory.createRenderer(null, null);
const div = renderer.createElement('div');
const consts = 1;
const vars = 60; // Space for directive expando, template, component + 3 directives if we assume
// that each consume 10 slots.
const tView = createTView(
TViewType.Component,
null,
emptyTemplate,
consts,
vars,
null,
null,
null,
null,
null,
null,
);
// Just assume that the expando starts after 10 initial bindings.
tView.expandoStartIndex = HEADER_OFFSET + 10;
const tNode = (tView.firstChild = createTNode(tView, null!, TNodeType.Element, 0, 'div', null));
const lView = createLView(
null,
tView,
null,
LViewFlags.CheckAlways,
null,
null,
{
rendererFactory,
sanitizer: null,
changeDetectionScheduler: null,
},
renderer,
null,
null,
null,
);
lView[HEADER_OFFSET] = div;
tView.data[HEADER_OFFSET] = tNode;
enterView(lView);
setSelectedIndex(HEADER_OFFSET);
}
export function clearFirstUpdatePass() {
getLView()[TVIEW].firstUpdatePass = false;
}
export function rewindBindingIndex() {
setBindingIndex(getBindingRoot());
}
function emptyTemplate() {}
| {
"end_byte": 2341,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/instructions/shared_spec.ts"
} |
angular/packages/core/test/render3/instructions/styling_spec.ts_0_5097 | /**
* @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 {AttributeMarker, DirectiveDef} from '@angular/core/src/render3';
import {ɵɵdefineDirective} from '@angular/core/src/render3/definition';
import {
classStringParser,
styleStringParser,
toStylingKeyValueArray,
ɵɵclassProp,
ɵɵstyleMap,
ɵɵstyleProp,
} from '@angular/core/src/render3/instructions/styling';
import {TAttributes} from '@angular/core/src/render3/interfaces/node';
import {
getTStylingRangeNext,
getTStylingRangeNextDuplicate,
getTStylingRangePrev,
getTStylingRangePrevDuplicate,
setTStylingRangeNext,
setTStylingRangePrev,
StylingRange,
toTStylingRange,
TStylingKey,
TStylingRange,
} from '@angular/core/src/render3/interfaces/styling';
import {HEADER_OFFSET, TVIEW} from '@angular/core/src/render3/interfaces/view';
import {getLView, leaveView, setBindingRootForHostBindings} from '@angular/core/src/render3/state';
import {getNativeByIndex} from '@angular/core/src/render3/util/view_utils';
import {keyValueArraySet} from '@angular/core/src/util/array_utils';
import {ngDevModeResetPerfCounters} from '@angular/core/src/util/ng_dev_mode';
import {getElementClasses, getElementStyles} from '@angular/core/testing/src/styling';
import {clearFirstUpdatePass, enterViewWithOneDiv, rewindBindingIndex} from './shared_spec';
describe('styling', () => {
beforeEach(enterViewWithOneDiv);
afterEach(leaveView);
let div!: HTMLElement;
beforeEach(() => (div = getNativeByIndex(HEADER_OFFSET, getLView()) as HTMLElement));
it('should do set basic style', () => {
ɵɵstyleProp('color', 'red');
expectStyle(div).toEqual({color: 'red'});
});
it('should search across multiple instructions backwards', () => {
ɵɵstyleProp('color', 'red');
ɵɵstyleProp('color', undefined);
ɵɵstyleProp('color', 'blue');
expectStyle(div).toEqual({color: 'blue'});
clearFirstUpdatePass();
rewindBindingIndex();
ɵɵstyleProp('color', 'red');
ɵɵstyleProp('color', undefined);
ɵɵstyleProp('color', undefined);
expectStyle(div).toEqual({color: 'red'});
});
it('should search across multiple instructions forwards', () => {
ɵɵstyleProp('color', 'red');
ɵɵstyleProp('color', 'green');
ɵɵstyleProp('color', 'blue');
expectStyle(div).toEqual({color: 'blue'});
clearFirstUpdatePass();
rewindBindingIndex();
ɵɵstyleProp('color', 'white');
expectStyle(div).toEqual({color: 'blue'});
});
it('should set style based on priority', () => {
ngDevModeResetPerfCounters();
ɵɵstyleProp('color', 'red');
ɵɵstyleProp('color', 'blue'); // Higher priority, should win.
expectStyle(div).toEqual({color: 'blue'});
// The intermediate value has to set since it does not know if it is last one.
expect(ngDevMode!.rendererSetStyle).toEqual(2);
ngDevModeResetPerfCounters();
clearFirstUpdatePass();
rewindBindingIndex();
ɵɵstyleProp('color', 'red'); // no change
ɵɵstyleProp('color', 'green'); // change to green
expectStyle(div).toEqual({color: 'green'});
expect(ngDevMode!.rendererSetStyle).toEqual(1);
ngDevModeResetPerfCounters();
rewindBindingIndex();
ɵɵstyleProp('color', 'black'); // First binding update
expectStyle(div).toEqual({color: 'green'}); // Green still has priority.
expect(ngDevMode!.rendererSetStyle).toEqual(0);
ngDevModeResetPerfCounters();
rewindBindingIndex();
ɵɵstyleProp('color', 'black'); // no change
ɵɵstyleProp('color', undefined); // Clear second binding
expectStyle(div).toEqual({color: 'black'}); // default to first binding
expect(ngDevMode!.rendererSetStyle).toEqual(1);
ngDevModeResetPerfCounters();
rewindBindingIndex();
ɵɵstyleProp('color', null);
expectStyle(div).toEqual({}); // default to first binding
expect(ngDevMode!.rendererSetStyle).toEqual(0);
expect(ngDevMode!.rendererRemoveStyle).toEqual(1);
});
it('should set class based on priority', () => {
ngDevModeResetPerfCounters();
ɵɵclassProp('foo', false);
ɵɵclassProp('foo', true); // Higher priority, should win.
expectClass(div).toEqual({foo: true});
expect(ngDevMode!.rendererAddClass).toEqual(1);
ngDevModeResetPerfCounters();
clearFirstUpdatePass();
rewindBindingIndex();
ɵɵclassProp('foo', false); // no change
ɵɵclassProp('foo', undefined); // change (have no opinion)
expectClass(div).toEqual({});
expect(ngDevMode!.rendererAddClass).toEqual(0);
expect(ngDevMode!.rendererRemoveClass).toEqual(1);
ngDevModeResetPerfCounters();
rewindBindingIndex();
ɵɵclassProp('foo', false); // no change
ɵɵclassProp('foo', 'truthy' as any);
expectClass(div).toEqual({foo: true});
rewindBindingIndex();
ɵɵclassProp('foo', true); // change
ɵɵclassProp('foo', undefined); // change
expectClass(div).toEqual({foo: true});
});
describe('styleMap', () => {
it('should work with maps | {
"end_byte": 5097,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/instructions/styling_spec.ts"
} |
angular/packages/core/test/render3/instructions/styling_spec.ts_5101_9064 | ) => {
ngDevModeResetPerfCounters();
ɵɵstyleMap({});
expectStyle(div).toEqual({});
expect(ngDevMode!.rendererSetStyle).toEqual(0);
expect(ngDevMode!.rendererRemoveStyle).toEqual(0);
ngDevModeResetPerfCounters();
clearFirstUpdatePass();
rewindBindingIndex();
ɵɵstyleMap({color: 'blue'});
expectStyle(div).toEqual({color: 'blue'});
expect(ngDevMode!.rendererSetStyle).toEqual(1);
expect(ngDevMode!.rendererRemoveStyle).toEqual(0);
ngDevModeResetPerfCounters();
rewindBindingIndex();
ɵɵstyleMap({color: 'red'});
expectStyle(div).toEqual({color: 'red'});
expect(ngDevMode!.rendererSetStyle).toEqual(1);
expect(ngDevMode!.rendererRemoveStyle).toEqual(0);
ngDevModeResetPerfCounters();
rewindBindingIndex();
ɵɵstyleMap({color: null, width: '100px'});
expectStyle(div).toEqual({width: '100px'});
expect(ngDevMode!.rendererSetStyle).toEqual(1);
expect(ngDevMode!.rendererRemoveStyle).toEqual(1);
ngDevModeResetPerfCounters();
});
it('should work with object literal and strings', () => {
ngDevModeResetPerfCounters();
ɵɵstyleMap('');
expectStyle(div).toEqual({});
expect(ngDevMode!.rendererSetStyle).toEqual(0);
expect(ngDevMode!.rendererRemoveStyle).toEqual(0);
ngDevModeResetPerfCounters();
clearFirstUpdatePass();
rewindBindingIndex();
ɵɵstyleMap('color: blue');
expectStyle(div).toEqual({color: 'blue'});
expect(ngDevMode!.rendererSetStyle).toEqual(1);
expect(ngDevMode!.rendererRemoveStyle).toEqual(0);
ngDevModeResetPerfCounters();
rewindBindingIndex();
ɵɵstyleMap('color: red');
expectStyle(div).toEqual({color: 'red'});
expect(ngDevMode!.rendererSetStyle).toEqual(1);
expect(ngDevMode!.rendererRemoveStyle).toEqual(0);
ngDevModeResetPerfCounters();
rewindBindingIndex();
ɵɵstyleMap('width: 100px');
expectStyle(div).toEqual({width: '100px'});
expect(ngDevMode!.rendererSetStyle).toEqual(1);
expect(ngDevMode!.rendererRemoveStyle).toEqual(1);
ngDevModeResetPerfCounters();
});
it('should collaborate with properties', () => {
ɵɵstyleProp('color', 'red');
ɵɵstyleMap({color: 'blue', width: '100px'});
expectStyle(div).toEqual({color: 'blue', width: '100px'});
clearFirstUpdatePass();
rewindBindingIndex();
ɵɵstyleProp('color', 'red');
ɵɵstyleMap({width: '200px'});
expectStyle(div).toEqual({color: 'red', width: '200px'});
});
it('should collaborate with other maps', () => {
ɵɵstyleMap('color: red');
ɵɵstyleMap({color: 'blue', width: '100px'});
expectStyle(div).toEqual({color: 'blue', width: '100px'});
clearFirstUpdatePass();
rewindBindingIndex();
ɵɵstyleMap('color: red');
ɵɵstyleMap({width: '200px'});
expectStyle(div).toEqual({color: 'red', width: '200px'});
});
describe('suffix', () => {
it('should append suffix', () => {
ɵɵstyleProp('width', 200, 'px');
ɵɵstyleProp('width', 100, 'px');
expectStyle(div).toEqual({width: '100px'});
clearFirstUpdatePass();
rewindBindingIndex();
ɵɵstyleProp('width', 200, 'px');
ɵɵstyleProp('width', undefined, 'px');
expectStyle(div).toEqual({width: '200px'});
});
it('should append suffix and non-suffix bindings', () => {
ɵɵstyleProp('width', 200, 'px');
ɵɵstyleProp('width', '100px');
expectStyle(div).toEqual({width: '100px'});
clearFirstUpdatePass();
rewindBindingIndex();
ɵɵstyleProp('width', 200, 'px');
ɵɵstyleProp('width', undefined, 'px');
expectStyle(div).toEqual({width: '200px'});
});
});
});
describe('static', () => {
describe('template only', () => {
it('should capture static values in | {
"end_byte": 9064,
"start_byte": 5101,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/instructions/styling_spec.ts"
} |
angular/packages/core/test/render3/instructions/styling_spec.ts_9068_16380 | ylingKey', () => {
givenTemplateAttrs([AttributeMarker.Styles, 'content', '"TEMPLATE"']);
ɵɵstyleProp('content', '"dynamic"');
expectTStylingKeys('style').toEqual([
['', 'content', 'content', '"TEMPLATE"'],
'prev', // contains statics
null, // residual
]);
expectStyle(div).toEqual({content: '"dynamic"'});
ɵɵstyleProp('content', undefined);
expectTStylingKeys('style').toEqual([
['', 'content', 'content', '"TEMPLATE"'],
'both', // contains statics
'content',
'prev', // Making sure that second instruction does not have statics again.
null, // residual
]);
expectStyle(div).toEqual({content: '"dynamic"'});
});
});
describe('directives only', () => {
it('should update residual on second directive', () => {
givenDirectiveAttrs([
[AttributeMarker.Styles, 'content', '"lowest"'], // 0
[AttributeMarker.Styles, 'content', '"middle"'], // 1
]);
expectStyle(div).toEqual({content: '"middle"'});
activateHostBindings(0);
ɵɵstyleProp('content', '"dynamic"');
expectTStylingKeys('style').toEqual([
['', 'content', 'content', '"lowest"'],
'both', // 1: contains statics
['content', '"middle"'], // residual
]);
expectStyle(div).toEqual({content: '"middle"'});
// second binding should not get statics
ɵɵstyleProp('content', '"dynamic2"');
expectTStylingKeys('style').toEqual([
['', 'content', 'content', '"lowest"'],
'both', // 1: contains statics
'content',
'both', // 1: Should not get statics
['content', '"middle"'], // residual
]);
expectStyle(div).toEqual({content: '"middle"'});
activateHostBindings(1);
ɵɵstyleProp('content', '"dynamic3"');
expectTStylingKeys('style').toEqual([
['', 'content', 'content', '"lowest"'],
'both', // 1: contains statics
'content',
'both', // 1: Should not get statics
['', 'content', 'content', '"middle"'],
'prev', // 0: contains statics
null, // residual
]);
expectStyle(div).toEqual({content: '"dynamic3"'});
});
});
describe('template and directives', () => {
it('should combine property and map', () => {
givenDirectiveAttrs([
[AttributeMarker.Styles, 'content', '"lowest"', 'color', 'blue'], // 0
[AttributeMarker.Styles, 'content', '"middle"', 'width', '100px'], // 1
]);
givenTemplateAttrs([AttributeMarker.Styles, 'content', '"TEMPLATE"', 'color', 'red']);
// TEMPLATE
ɵɵstyleProp('content', undefined);
expectTStylingKeys('style').toEqual([
// TEMPLATE
['', 'content', 'color', 'red', 'content', '"TEMPLATE"', 'width', '100px'],
'prev',
// RESIDUAL
null,
]);
expectStyle(div).toEqual({content: '"TEMPLATE"', color: 'red', width: '100px'});
// Directive 0
activateHostBindings(0);
ɵɵstyleMap('color: red; width: 0px; height: 50px');
expectTStylingKeys('style').toEqual([
// Host Binding 0
['', null, 'color', 'blue', 'content', '"lowest"'],
'both',
// TEMPLATE
['', 'content', 'color', 'red', 'content', '"TEMPLATE"', 'width', '100px'],
'prev',
// RESIDUAL
null,
]);
expectStyle(div).toEqual({
content: '"TEMPLATE"',
color: 'red',
width: '100px',
height: '50px',
});
// Directive 1
activateHostBindings(1);
ɵɵstyleMap('color: red; width: 0px; height: 50px');
expectTStylingKeys('style').toEqual([
// Host Binding 0
['', null, 'color', 'blue', 'content', '"lowest"'],
'both',
// Host Binding 1
['', null, 'content', '"middle"', 'width', '100px'],
'both',
// TEMPLATE
['', 'content', 'color', 'red', 'content', '"TEMPLATE"'],
'prev',
// RESIDUAL
null,
]);
expectStyle(div).toEqual({
content: '"TEMPLATE"',
color: 'red',
width: '0px',
height: '50px',
});
});
it('should read value from residual', () => {
givenDirectiveAttrs([
[AttributeMarker.Styles, 'content', '"lowest"', 'color', 'blue'], // 0
[AttributeMarker.Styles, 'content', '"middle"', 'width', '100px'], // 1
]);
givenTemplateAttrs([AttributeMarker.Styles, 'content', '"TEMPLATE"', 'color', 'red']);
// Directive 1
activateHostBindings(1);
ɵɵstyleProp('color', 'white');
expectTStylingKeys('style').toEqual([
// Host Binding 0 + 1
['', 'color', 'color', 'blue', 'content', '"middle"', 'width', '100px'],
'both',
// RESIDUAL
['color', 'red', 'content', '"TEMPLATE"'],
]);
expectStyle(div).toEqual({content: '"TEMPLATE"', color: 'red', width: '100px'});
});
});
});
describe('toStylingArray', () => {
describe('falsy', () => {
it('should return empty KeyValueArray', () => {
expect(toStylingKeyValueArray(keyValueArraySet, null!, '')).toEqual([] as any);
expect(toStylingKeyValueArray(keyValueArraySet, null!, null)).toEqual([] as any);
expect(toStylingKeyValueArray(keyValueArraySet, null!, undefined)).toEqual([] as any);
expect(toStylingKeyValueArray(keyValueArraySet, null!, [])).toEqual([] as any);
expect(toStylingKeyValueArray(keyValueArraySet, null!, {})).toEqual([] as any);
});
describe('string', () => {
it('should parse classes', () => {
expect(toStylingKeyValueArray(keyValueArraySet, classStringParser, ' ')).toEqual(
[] as any,
);
expect(toStylingKeyValueArray(keyValueArraySet, classStringParser, ' X A ')).toEqual([
'A',
true,
'X',
true,
] as any);
});
it('should parse styles', () => {
expect(toStylingKeyValueArray(keyValueArraySet, styleStringParser, ' ')).toEqual(
[] as any,
);
expect(toStylingKeyValueArray(keyValueArraySet, styleStringParser, 'B:b;A:a')).toEqual([
'A',
'a',
'B',
'b',
] as any);
});
});
describe('array', () => {
it('should parse', () => {
expect(toStylingKeyValueArray(keyValueArraySet, null!, ['X', 'A'])).toEqual([
'A',
true,
'X',
true,
] as any);
});
});
describe('object', () => {
it('should parse', () => {
expect(toStylingKeyValueArray(keyValueArraySet, null!, {X: 'x', A: 'a'})).toEqual([
'A',
'a',
'X',
'x',
] as any);
});
});
});
});
describe('TStylingRange', () => {
const MAX_VALUE = StylingRange.UNSIGNED_MASK;
it('should throw on negative values | {
"end_byte": 16380,
"start_byte": 9068,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/instructions/styling_spec.ts"
} |
angular/packages/core/test/render3/instructions/styling_spec.ts_16384_21093 | ) => {
expect(() => toTStylingRange(0, -1)).toThrow();
expect(() => toTStylingRange(-1, 0)).toThrow();
});
it('should throw on overflow', () => {
expect(() => toTStylingRange(0, MAX_VALUE + 1)).toThrow();
expect(() => toTStylingRange(MAX_VALUE + 1, 0)).toThrow();
});
it('should retrieve the same value which went in just below overflow', () => {
const range = toTStylingRange(MAX_VALUE, MAX_VALUE);
expect(getTStylingRangePrev(range)).toEqual(MAX_VALUE);
expect(getTStylingRangeNext(range)).toEqual(MAX_VALUE);
});
it('should correctly increment', () => {
let range = toTStylingRange(0, 0);
for (let i = 0; i <= MAX_VALUE; i++) {
range = setTStylingRangeNext(range, i);
range = setTStylingRangePrev(range, i);
expect(getTStylingRangeNext(range)).toEqual(i);
expect(getTStylingRangePrev(range)).toEqual(i);
if (i == 10) {
// Skip the boring stuff in the middle.
i = MAX_VALUE - 10;
}
}
});
});
});
function expectStyle(element: HTMLElement) {
return expect(getElementStyles(element));
}
function expectClass(element: HTMLElement) {
return expect(getElementClasses(element));
}
function givenTemplateAttrs(tAttrs: TAttributes) {
const tNode = getTNode();
tNode.attrs = tAttrs;
applyTAttributes(tAttrs);
}
function getTNode() {
return getLView()[TVIEW].firstChild!;
}
function getTData() {
return getLView()[TVIEW].data;
}
class MockDir {}
function givenDirectiveAttrs(tAttrs: TAttributes[]) {
const tNode = getTNode();
const tData = getTData();
tNode.directiveStart = getTDataIndexFromDirectiveIndex(0);
tNode.directiveEnd = getTDataIndexFromDirectiveIndex(tAttrs.length);
for (let i = 0; i < tAttrs.length; i++) {
const tAttr = tAttrs[i];
const directiveDef = ɵɵdefineDirective({type: MockDir, hostAttrs: tAttr}) as DirectiveDef<any>;
applyTAttributes(directiveDef.hostAttrs);
tData[getTDataIndexFromDirectiveIndex(i)] = directiveDef;
}
}
function applyTAttributes(attrs: TAttributes | null) {
if (attrs === null) return;
const div: HTMLElement = getLView()[HEADER_OFFSET];
let mode: AttributeMarker = AttributeMarker.ImplicitAttributes;
for (let i = 0; i < attrs.length; i++) {
const item = attrs[i];
if (typeof item === 'number') {
mode = item;
} else if (typeof item === 'string') {
if (mode == AttributeMarker.ImplicitAttributes) {
div.setAttribute(item, attrs[++i] as string);
} else if (mode == AttributeMarker.Classes) {
div.classList.add(item);
} else if (mode == AttributeMarker.Styles) {
div.style.setProperty(item, attrs[++i] as string);
}
}
}
}
function activateHostBindings(directiveIndex: number) {
const bindingRootIndex = getBindingRootIndexFromDirectiveIndex(directiveIndex);
const currentDirectiveIndex = getTDataIndexFromDirectiveIndex(directiveIndex);
setBindingRootForHostBindings(bindingRootIndex, currentDirectiveIndex);
}
function getBindingRootIndexFromDirectiveIndex(index: number) {
// For simplicity assume that each directive has 10 vars.
// We need to offset 1 for template, and 1 for expando.
return HEADER_OFFSET + (index + 2) * 10;
}
function getTDataIndexFromDirectiveIndex(index: number) {
return HEADER_OFFSET + index + 10; // offset to give template bindings space.
}
function expectTStylingKeys(styling: 'style' | 'class') {
const tNode = getTNode();
const tData = getTData();
const isClassBased = styling === 'class';
const headIndex = getTStylingRangePrev(isClassBased ? tNode.classBindings : tNode.styleBindings);
const tStylingKeys: (string | (null | string)[] | null)[] = [];
let index = headIndex;
let prevIndex = index;
// rewind to beginning of list.
while ((prevIndex = getTStylingRangePrev(tData[index + 1] as TStylingRange)) !== 0) {
index = prevIndex;
}
// insert into array.
while (index !== 0) {
const tStylingKey = tData[index] as TStylingKey;
const prevDup = getTStylingRangePrevDuplicate(tData[index + 1] as TStylingRange);
const nextDup = getTStylingRangeNextDuplicate(tData[index + 1] as TStylingRange);
tStylingKeys.push(tStylingKey as string[] | string | null);
tStylingKeys.push(prevDup ? (nextDup ? 'both' : 'prev') : nextDup ? 'next' : '');
index = getTStylingRangeNext(tData[index + 1] as TStylingRange);
}
tStylingKeys.push(
(isClassBased ? tNode.residualClasses : tNode.residualStyles) as null | string[],
);
return expect(tStylingKeys);
}
| {
"end_byte": 21093,
"start_byte": 16384,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/instructions/styling_spec.ts"
} |
angular/packages/core/test/render3/ivy/jit_spec.ts_0_928 | /**
* @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,
ContentChild,
ContentChildren,
Directive,
ElementRef,
forwardRef,
getNgModuleById,
HostBinding,
HostListener,
Input,
NgModule,
Pipe,
QueryList,
ViewChild,
ViewChildren,
ɵNgModuleDef as NgModuleDef,
ɵɵngDeclareComponent as ngDeclareComponent,
} from '@angular/core';
import {Injectable} from '@angular/core/src/di/injectable';
import {setCurrentInjector, ɵɵinject} from '@angular/core/src/di/injector_compatibility';
import {ɵɵdefineInjectable, ɵɵInjectorDef} from '@angular/core/src/di/interface/defs';
import {FactoryFn} from '@angular/core/src/render3/definition_factory';
import {ComponentDef, PipeDef} from '@angular/core/src/render3/interfaces/definition';
describ | {
"end_byte": 928,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/ivy/jit_spec.ts"
} |
angular/packages/core/test/render3/ivy/jit_spec.ts_930_8614 | 'render3 jit', () => {
let injector: any;
beforeAll(() => {
injector = setCurrentInjector(null);
});
afterAll(() => {
setCurrentInjector(injector);
});
it('compiles a component', () => {
@Component({
template: 'test',
selector: 'test-cmp',
standalone: false,
})
class SomeCmp {}
const SomeCmpAny = SomeCmp as any;
expect(SomeCmpAny.ɵcmp).toBeDefined();
expect(SomeCmpAny.ɵfac() instanceof SomeCmp).toBe(true);
});
it('compiles a partially compiled component with split dependencies', () => {
@Component({
selector: 'inner-cmp',
template: 'Inner!',
standalone: false,
})
class InnerCmp {}
class OuterCmp {
static ɵcmp = ngDeclareComponent({
template: '<inner-cmp></inner-cmp>',
version: '18.0.0',
type: OuterCmp,
components: [
{
type: InnerCmp,
selector: 'inner-cmp',
},
],
});
}
const rawDirectiveDefs = (OuterCmp.ɵcmp as ComponentDef<OuterCmp>).directiveDefs;
expect(rawDirectiveDefs).not.toBeNull();
const directiveDefs =
rawDirectiveDefs! instanceof Function ? rawDirectiveDefs!() : rawDirectiveDefs!;
expect(directiveDefs.length).toBe(1);
expect(directiveDefs[0].type).toBe(InnerCmp);
});
it('compiles a partially compiled component with unified dependencies', () => {
@Component({
selector: 'inner-cmp',
template: 'Inner!',
standalone: false,
})
class InnerCmp {}
class OuterCmp {
static ɵcmp = ngDeclareComponent({
template: '<inner-cmp></inner-cmp>',
type: OuterCmp,
version: '18.0.0',
dependencies: [
{
kind: 'component',
type: InnerCmp,
selector: 'inner-cmp',
},
],
});
}
const rawDirectiveDefs = (OuterCmp.ɵcmp as ComponentDef<OuterCmp>).directiveDefs;
expect(rawDirectiveDefs).not.toBeNull();
const directiveDefs =
rawDirectiveDefs! instanceof Function ? rawDirectiveDefs!() : rawDirectiveDefs!;
expect(directiveDefs.length).toBe(1);
expect(directiveDefs[0].type).toBe(InnerCmp);
});
it('compiles an injectable with a type provider', () => {
@Injectable({providedIn: 'root'})
class Service {}
const ServiceAny = Service as any;
expect(ServiceAny.ɵprov).toBeDefined();
expect(ServiceAny.ɵprov.providedIn).toBe('root');
expect(ɵɵinject(Service) instanceof Service).toBe(true);
});
it('compiles an injectable with a useValue provider', () => {
@Injectable({providedIn: 'root', useValue: 'test'})
class Service {}
expect(ɵɵinject(Service)).toBe('test');
});
it('compiles an injectable with a useExisting provider', () => {
@Injectable({providedIn: 'root', useValue: 'test'})
class Existing {}
@Injectable({providedIn: 'root', useExisting: Existing})
class Service {}
expect(ɵɵinject(Service)).toBe('test');
});
it('compiles an injectable with a useFactory provider, without deps', () => {
@Injectable({providedIn: 'root', useFactory: () => 'test'})
class Service {}
expect(ɵɵinject(Service)).toBe('test');
});
it('compiles an injectable with a useFactory provider, with deps', () => {
@Injectable({providedIn: 'root', useValue: 'test'})
class Existing {}
@Injectable({providedIn: 'root', useFactory: (existing: any) => existing, deps: [Existing]})
class Service {}
expect(ɵɵinject(Service)).toBe('test');
});
it('compiles an injectable with a useClass provider, with deps', () => {
@Injectable({providedIn: 'root', useValue: 'test'})
class Existing {}
class Other {
constructor(public value: any) {}
}
@Injectable({providedIn: 'root', useClass: Other, deps: [Existing]})
class Service {
get value(): any {
return null;
}
}
const ServiceAny = Service as any;
expect(ɵɵinject(Service).value).toBe('test');
});
it('compiles an injectable with a useClass provider, without deps', () => {
let _value = 1;
@Injectable({providedIn: 'root'})
class Existing {
readonly value = _value++;
}
@Injectable({providedIn: 'root', useClass: Existing})
class Service {
get value(): number {
return 0;
}
}
expect(ɵɵinject(Existing).value).toBe(1);
const injected = ɵɵinject(Service);
expect(injected instanceof Existing).toBe(true);
expect(injected.value).toBe(2);
});
it('compiles an injectable with an inherited constructor', () => {
@Injectable({providedIn: 'root'})
class Dep {}
@Injectable()
class Base {
constructor(readonly dep: Dep) {}
}
@Injectable({providedIn: 'root'})
class Child extends Base {}
expect(ɵɵinject(Child).dep instanceof Dep).toBe(true);
});
it('compiles a module to a definition', () => {
@Component({
template: 'foo',
selector: 'foo',
standalone: false,
})
class Cmp {}
@NgModule({
declarations: [Cmp],
})
class Module {}
const moduleDef: NgModuleDef<Module> = (Module as any).ɵmod;
expect(moduleDef).toBeDefined();
if (!Array.isArray(moduleDef.declarations)) {
return fail('Expected an array');
}
expect(moduleDef.declarations.length).toBe(1);
expect(moduleDef.declarations[0]).toBe(Cmp);
});
it('compiles a module with forwardRef', () => {
@NgModule({
declarations: [forwardRef(() => Cmp)],
})
class Module {}
@Component({
template: 'foo',
selector: 'foo',
standalone: false,
})
class Cmp {}
const componentDef: ComponentDef<Module> = (Cmp as any).ɵcmp;
expect(componentDef).toBeDefined();
expect(componentDef.schemas).toBeInstanceOf(Array);
});
it('compiles a module with an id and registers it correctly', () => {
@NgModule({
id: 'test',
})
class Module {}
const moduleDef: NgModuleDef<Module> = (Module as any).ɵmod;
expect(moduleDef).toBeDefined();
if (!Array.isArray(moduleDef.declarations)) {
return fail('Expected an array');
}
expect(moduleDef.id).toBe('test');
expect(getNgModuleById('test')).toBe(Module);
});
it('compiles a module to an ɵinj with the providers', () => {
class Token {
static ɵprov = ɵɵdefineInjectable({
token: Token,
providedIn: 'root',
factory: () => 'default',
});
}
@NgModule({
providers: [{provide: Token, useValue: 'test'}],
})
class Module {
constructor(public token: Token) {}
}
const factory: FactoryFn<Module> = (Module as any).ɵfac;
const instance = factory();
// Since the instance was created outside of an injector using the module, the
// injection will use the default provider, not the provider from the module.
expect(instance.token).toBe('default');
const injectorDef: ɵɵInjectorDef<Module> = (Module as any).ɵinj;
expect(injectorDef.providers).toEqual([{provide: Token, useValue: 'test'}]);
});
it('patches a module onto the component', () => {
@Component({
template: 'foo',
selector: 'foo',
standalone: false,
})
class Cmp {}
const cmpDef: ComponentDef<Cmp> = (Cmp as any).ɵcmp;
expect(cmpDef.directiveDefs).toBeNull();
@NgModule({
declarations: [Cmp],
})
class Module {}
const moduleDef: NgModuleDef<Module> = (Module as any).ɵmod;
// directive defs are still null, since no directives were in that component
expect(cmpDef.directiveDefs).toBeNull();
});
it('should add hostbindings and hostlistener | {
"end_byte": 8614,
"start_byte": 930,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/ivy/jit_spec.ts"
} |
angular/packages/core/test/render3/ivy/jit_spec.ts_8618_14309 | () => {
@Component({
template: 'foo',
selector: 'foo',
host: {
'[class.red]': 'isRed',
'(click)': 'onClick()',
},
standalone: false,
})
class Cmp {
@HostBinding('class.green') green: boolean = false;
@HostListener('change', ['$event'])
onChange(event: any): void {}
}
const cmpDef = (Cmp as any).ɵcmp as ComponentDef<Cmp>;
expect(cmpDef.hostBindings).toBeDefined();
expect(cmpDef.hostBindings!.length).toBe(2);
});
it('should compile @Pipes without errors', () => {
@Pipe({
name: 'test-pipe',
pure: false,
standalone: false,
})
class P {}
const pipeDef = (P as any).ɵpipe as PipeDef<P>;
const pipeFactory = (P as any).ɵfac as FactoryFn<P>;
expect(pipeDef.name).toBe('test-pipe');
expect(pipeDef.pure).toBe(false, 'pipe should not be pure');
expect(pipeFactory() instanceof P).toBe(
true,
'factory() should create an instance of the pipe',
);
});
it('should default @Pipe to pure: true', () => {
@Pipe({
name: 'test-pipe',
standalone: false,
})
class P {}
const pipeDef = (P as any).ɵpipe as PipeDef<P>;
expect(pipeDef.pure).toBe(true, 'pipe should be pure');
});
it('should add @Input properties to a component', () => {
@Component({
selector: 'input-comp',
template: 'test',
standalone: false,
})
class InputComp {
@Input('publicName') privateName = 'name1';
}
const InputCompAny = InputComp as any;
expect(InputCompAny.ɵcmp.inputs).toEqual({publicName: 'privateName'});
expect(InputCompAny.ɵcmp.declaredInputs).toEqual({publicName: 'privateName'});
});
it('should add @Input properties to a directive', () => {
@Directive({
selector: '[dir]',
standalone: false,
})
class InputDir {
@Input('publicName') privateName = 'name1';
}
const InputDirAny = InputDir as any;
expect(InputDirAny.ɵdir.inputs).toEqual({publicName: 'privateName'});
expect(InputDirAny.ɵdir.declaredInputs).toEqual({publicName: 'privateName'});
});
it('should compile ContentChildren query with string predicate on a directive', () => {
@Directive({
selector: '[test]',
standalone: false,
})
class TestDirective {
@ContentChildren('foo') foos: QueryList<ElementRef> | undefined;
}
expect((TestDirective as any).ɵdir.contentQueries).not.toBeNull();
});
it('should compile ContentChild query with string predicate on a directive', () => {
@Directive({
selector: '[test]',
standalone: false,
})
class TestDirective {
@ContentChild('foo') foo: ElementRef | undefined;
}
expect((TestDirective as any).ɵdir.contentQueries).not.toBeNull();
});
it('should compile ContentChildren query with type predicate on a directive', () => {
class SomeDir {}
@Directive({
selector: '[test]',
standalone: false,
})
class TestDirective {
@ContentChildren(SomeDir) dirs: QueryList<SomeDir> | undefined;
}
expect((TestDirective as any).ɵdir.contentQueries).not.toBeNull();
});
it('should compile ContentChild query with type predicate on a directive', () => {
class SomeDir {}
@Directive({
selector: '[test]',
standalone: false,
})
class TestDirective {
@ContentChild(SomeDir) dir: SomeDir | undefined;
}
expect((TestDirective as any).ɵdir.contentQueries).not.toBeNull();
});
it('should compile ViewChild query on a component', () => {
@Component({
selector: 'test',
template: '',
standalone: false,
})
class TestComponent {
@ViewChild('foo') foo: ElementRef | undefined;
}
expect((TestComponent as any).ɵcmp.foo).not.toBeNull();
});
it('should compile ViewChildren query on a component', () => {
@Component({
selector: 'test',
template: '',
standalone: false,
})
class TestComponent {
@ViewChildren('foo') foos: QueryList<ElementRef> | undefined;
}
expect((TestComponent as any).ɵcmp.viewQuery).not.toBeNull();
});
describe('invalid parameters', () => {
it('should error when creating an @Injectable that extends a class with a faulty parameter', () => {
@Injectable({providedIn: 'root'})
class Legit {}
@Injectable()
class Base {
constructor(first: Legit, second: any) {}
}
@Injectable({providedIn: 'root'})
class Service extends Base {}
const ServiceAny = Service as any;
expect(ServiceAny.ɵprov).toBeDefined();
expect(ServiceAny.ɵprov.providedIn).toBe('root');
expect(() => ɵɵinject(Service)).toThrowError(
/constructor is not compatible with Angular Dependency Injection because its dependency at index 1 of the parameter list is invalid/,
);
});
it('should error when creating an @Directive that extends an undecorated class with parameters', () => {
@Injectable({providedIn: 'root'})
class Legit {}
class BaseDir {
constructor(first: Legit) {}
}
@Directive({
selector: 'test',
standalone: false,
})
class TestDir extends BaseDir {}
const TestDirAny = TestDir as any;
expect(TestDirAny.ɵfac).toBeDefined();
expect(() => TestDirAny.ɵfac()).toThrowError(
/constructor is not compatible with Angular Dependency Injection because its dependency at index 0 of the parameter list is invalid/,
);
});
});
});
it('ensure at least one spec exists', () => {});
| {
"end_byte": 14309,
"start_byte": 8618,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/ivy/jit_spec.ts"
} |
angular/packages/core/test/render3/ivy/BUILD.bazel_0_544 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "ivy_lib",
testonly = True,
srcs = glob(["**/*.ts"]),
deps = [
"//packages:types",
"//packages/core",
"//packages/core/src/di/interface",
],
)
jasmine_node_test(
name = "ivy",
bootstrap = [
"//packages/core/test/render3:domino",
"//tools/testing:node",
],
deps = [
":ivy_lib",
"//packages/zone.js/lib",
],
)
| {
"end_byte": 544,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/ivy/BUILD.bazel"
} |
angular/packages/core/test/render3/util/stringify_util_spec.ts_0_1602 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ɵsetClassDebugInfo, ɵɵdefineComponent} from '@angular/core/src/render3';
import {debugStringifyTypeForError} from '@angular/core/src/render3/util/stringify_utils';
describe('stringify utils', () => {
describe('stringifyTypeForError util', () => {
it('should include the file path and line number for component if debug info includes them', () => {
class Comp {
static ɵcmp = ɵɵdefineComponent({type: Comp, decls: 0, vars: 0, template: () => ''});
}
ɵsetClassDebugInfo(Comp, {
className: 'Comp',
filePath: 'comp.ts',
lineNumber: 11,
});
expect(debugStringifyTypeForError(Comp)).toBe('Comp (at comp.ts:11)');
});
it('should include only the class name if debug info does not contain file path', () => {
class Comp {
static ɵcmp = ɵɵdefineComponent({type: Comp, decls: 0, vars: 0, template: () => ''});
}
ɵsetClassDebugInfo(Comp, {
className: 'Comp',
lineNumber: 11,
});
expect(debugStringifyTypeForError(Comp)).toBe('Comp');
});
it('should default to showing just the class name for component if debug info is not available', () => {
class Comp {
static ɵcmp = ɵɵdefineComponent({type: Comp, decls: 0, vars: 0, template: () => ''});
}
expect(debugStringifyTypeForError(Comp)).toBe('Comp');
});
});
});
| {
"end_byte": 1602,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/util/stringify_util_spec.ts"
} |
angular/packages/core/test/render3/util/attr_util_spec.ts_0_5416 | /**
* @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 {AttributeMarker} from '@angular/core/src/render3';
import {TAttributes} from '@angular/core/src/render3/interfaces/node';
import {mergeHostAttribute, mergeHostAttrs} from '@angular/core/src/render3/util/attrs_utils';
describe('attr_util', () => {
describe('mergeHostAttribute', () => {
it('should add new attributes', () => {
const attrs: TAttributes = [];
mergeHostAttribute(attrs, -1, 'Key', null, 'value');
expect(attrs).toEqual(['Key', 'value']);
mergeHostAttribute(attrs, -1, 'A', null, 'a');
expect(attrs).toEqual(['Key', 'value', 'A', 'a']);
mergeHostAttribute(attrs, -1, 'X', null, 'x');
expect(attrs).toEqual(['Key', 'value', 'A', 'a', 'X', 'x']);
mergeHostAttribute(attrs, -1, 'Key', null, 'new');
expect(attrs).toEqual(['Key', 'new', 'A', 'a', 'X', 'x']);
});
it('should add new classes', () => {
const attrs: TAttributes = [];
mergeHostAttribute(attrs, AttributeMarker.Classes, 'CLASS', null, null);
expect(attrs).toEqual([AttributeMarker.Classes, 'CLASS']);
mergeHostAttribute(attrs, AttributeMarker.Classes, 'A', null, null);
expect(attrs).toEqual([AttributeMarker.Classes, 'CLASS', 'A']);
mergeHostAttribute(attrs, AttributeMarker.Classes, 'X', null, null);
expect(attrs).toEqual([AttributeMarker.Classes, 'CLASS', 'A', 'X']);
mergeHostAttribute(attrs, AttributeMarker.Classes, 'CLASS', null, null);
expect(attrs).toEqual([AttributeMarker.Classes, 'CLASS', 'A', 'X']);
});
it('should add new styles', () => {
const attrs: TAttributes = [];
mergeHostAttribute(attrs, AttributeMarker.Styles, 'Style', null, 'v1');
expect(attrs).toEqual([AttributeMarker.Styles, 'Style', 'v1']);
mergeHostAttribute(attrs, AttributeMarker.Styles, 'A', null, 'v2');
expect(attrs).toEqual([AttributeMarker.Styles, 'Style', 'v1', 'A', 'v2']);
mergeHostAttribute(attrs, AttributeMarker.Styles, 'X', null, 'v3');
expect(attrs).toEqual([AttributeMarker.Styles, 'Style', 'v1', 'A', 'v2', 'X', 'v3']);
mergeHostAttribute(attrs, AttributeMarker.Styles, 'Style', null, 'new');
expect(attrs).toEqual([AttributeMarker.Styles, 'Style', 'new', 'A', 'v2', 'X', 'v3']);
});
it('should keep different types together', () => {
const attrs: TAttributes = [];
mergeHostAttribute(attrs, -1, 'Key', null, 'value');
expect(attrs).toEqual(['Key', 'value']);
mergeHostAttribute(attrs, AttributeMarker.Classes, 'CLASS', null, null);
expect(attrs).toEqual(['Key', 'value', AttributeMarker.Classes, 'CLASS']);
mergeHostAttribute(attrs, AttributeMarker.Styles, 'Style', null, 'v1');
expect(attrs).toEqual([
'Key',
'value',
AttributeMarker.Classes,
'CLASS',
AttributeMarker.Styles,
'Style',
'v1',
]);
mergeHostAttribute(attrs, -1, 'Key2', null, 'value2');
expect(attrs).toEqual([
'Key',
'value',
'Key2',
'value2',
AttributeMarker.Classes,
'CLASS',
AttributeMarker.Styles,
'Style',
'v1',
]);
mergeHostAttribute(attrs, AttributeMarker.Classes, 'CLASS2', null, null);
expect(attrs).toEqual([
'Key',
'value',
'Key2',
'value2',
AttributeMarker.Classes,
'CLASS',
'CLASS2',
AttributeMarker.Styles,
'Style',
'v1',
]);
mergeHostAttribute(attrs, AttributeMarker.Styles, 'Style2', null, 'v2');
expect(attrs).toEqual([
'Key',
'value',
'Key2',
'value2',
AttributeMarker.Classes,
'CLASS',
'CLASS2',
AttributeMarker.Styles,
'Style',
'v1',
'Style2',
'v2',
]);
mergeHostAttribute(attrs, AttributeMarker.NamespaceURI, 'uri', 'key', 'value');
expect(attrs).toEqual([
'Key',
'value',
'Key2',
'value2',
AttributeMarker.NamespaceURI,
'uri',
'key',
'value',
AttributeMarker.Classes,
'CLASS',
'CLASS2',
AttributeMarker.Styles,
'Style',
'v1',
'Style2',
'v2',
]);
mergeHostAttribute(attrs, AttributeMarker.NamespaceURI, 'uri', 'key', 'new value');
expect(attrs).toEqual([
'Key',
'value',
'Key2',
'value2',
AttributeMarker.NamespaceURI,
'uri',
'key',
'new value',
AttributeMarker.Classes,
'CLASS',
'CLASS2',
AttributeMarker.Styles,
'Style',
'v1',
'Style2',
'v2',
]);
});
});
describe('mergeHostAttrs', () => {
it('should ignore nulls/empty', () => {
expect(mergeHostAttrs(null, null)).toEqual(null);
expect(mergeHostAttrs([], null)).toEqual([]);
expect(mergeHostAttrs(null, [])).toEqual(null);
});
it('should copy if dst is null', () => {
expect(mergeHostAttrs(null, ['K', 'v'])).toEqual(['K', 'v']);
expect(mergeHostAttrs(['K', '', 'X', 'x'], ['K', 'v'])).toEqual(['K', 'v', 'X', 'x']);
});
});
});
| {
"end_byte": 5416,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/util/attr_util_spec.ts"
} |
angular/packages/core/test/render3/jit/declare_factory_spec.ts_0_2962 | /**
* @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 {
Injector,
ɵcreateInjector,
ɵInjectorProfilerContext,
ɵsetInjectorProfilerContext,
ɵɵFactoryTarget,
ɵɵngDeclareFactory,
} from '@angular/core';
import {ɵɵdefineInjector} from '@angular/core/src/di';
import {setCurrentInjector} from '@angular/core/src/di/injector_compatibility';
describe('Factory declaration jit compilation', () => {
let previousInjector: Injector | null | undefined;
let previousInjectorProfilerContext: ɵInjectorProfilerContext;
beforeEach(() => {
const injector = ɵcreateInjector(TestInjector);
previousInjector = setCurrentInjector(injector);
previousInjectorProfilerContext = ɵsetInjectorProfilerContext({injector, token: null});
});
afterEach(() => {
setCurrentInjector(previousInjector);
previousInjectorProfilerContext = ɵsetInjectorProfilerContext(previousInjectorProfilerContext);
});
it('should compile a simple factory declaration', () => {
const factory = TestClass.ɵfac as Function;
expect(factory.name).toEqual('TestClass_Factory');
const instance = factory();
expect(instance).toBeInstanceOf(TestClass);
});
it('should compile a factory declaration with dependencies', () => {
const factory = DependingClass.ɵfac as Function;
expect(factory.name).toEqual('DependingClass_Factory');
const instance = factory();
expect(instance).toBeInstanceOf(DependingClass);
expect(instance.testClass).toBeInstanceOf(TestClass);
});
it('should compile a factory declaration that has inheritance', () => {
const factory = ChildClass.ɵfac as Function;
const instance = factory();
expect(instance).toBeInstanceOf(ChildClass);
expect(instance.testClass).toBeInstanceOf(TestClass);
});
it('should compile a factory declaration with an invalid dependency', () => {
const factory = InvalidDepsClass.ɵfac as Function;
expect(() => factory()).toThrowError(/not compatible/);
});
});
class TestClass {
static ɵfac = ɵɵngDeclareFactory({type: TestClass, deps: [], target: ɵɵFactoryTarget.Injectable});
}
class DependingClass {
constructor(readonly testClass: TestClass) {}
static ɵfac = ɵɵngDeclareFactory({
type: DependingClass,
deps: [{token: TestClass}],
target: ɵɵFactoryTarget.Injectable,
});
}
class ChildClass extends DependingClass {
static override ɵfac = ɵɵngDeclareFactory({
type: ChildClass,
deps: null,
target: ɵɵFactoryTarget.Injectable,
});
}
class InvalidDepsClass {
static ɵfac = ɵɵngDeclareFactory({
type: InvalidDepsClass,
deps: 'invalid',
target: ɵɵFactoryTarget.Injectable,
});
}
class TestInjector {
static ɵinj = ɵɵdefineInjector({
providers: [TestClass, DependingClass, ChildClass],
});
}
| {
"end_byte": 2962,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/jit/declare_factory_spec.ts"
} |
angular/packages/core/test/render3/jit/declare_classmetadata_spec.ts_0_2300 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Injectable, Input, Type, ɵɵngDeclareClassMetadata} from '@angular/core';
interface Decorator {
type: any;
args?: any[];
}
interface CtorParameter {
type: any;
decorators?: Decorator[];
}
interface WithMetadata extends Type<any> {
decorators?: Decorator[];
ctorParameters?: () => CtorParameter[];
propDecorators?: {[field: string]: Decorator[]};
}
describe('class metadata declaration jit compilation', () => {
it('should attach class decorators', () => {
const TestClass: WithMetadata = class TestClass {};
ɵɵngDeclareClassMetadata({
type: TestClass,
decorators: [
{
type: Injectable,
args: [],
},
],
});
expect(TestClass.decorators!.length).toBe(1);
expect(TestClass.decorators![0].type).toBe(Injectable);
expect(TestClass.propDecorators).toBeUndefined();
expect(TestClass.ctorParameters).toBeUndefined();
});
it('should attach property decorators', () => {
const TestClass: WithMetadata = class TestClass {};
ɵɵngDeclareClassMetadata({
type: TestClass,
decorators: [
{
type: Injectable,
args: [],
},
],
propDecorators: {
test: [{type: Input, args: []}],
},
});
expect(TestClass.decorators!.length).toBe(1);
expect(TestClass.decorators![0].type).toBe(Injectable);
expect(TestClass.propDecorators).toEqual({
test: [{type: Input, args: []}],
});
expect(TestClass.ctorParameters).toBeUndefined();
});
it('should attach constructor parameters', () => {
const TestClass: WithMetadata = class TestClass {};
ɵɵngDeclareClassMetadata({
type: TestClass,
decorators: [
{
type: Injectable,
args: [],
},
],
ctorParameters: () => [{type: String}],
});
expect(TestClass.decorators!.length).toBe(1);
expect(TestClass.decorators![0].type).toBe(Injectable);
expect(TestClass.propDecorators).toBeUndefined();
expect(TestClass.ctorParameters!()).toEqual([{type: String}]);
});
});
| {
"end_byte": 2300,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/jit/declare_classmetadata_spec.ts"
} |
angular/packages/core/test/render3/jit/directive_spec.ts_0_5814 | /**
* @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 {Directive, HostListener, Input} from '@angular/core';
import {
convertToR3QueryMetadata,
directiveMetadata,
extendsDirectlyFromObject,
} from '../../../src/render3/jit/directive';
import {setClassMetadata} from '../../../src/render3/metadata';
describe('jit directive helper functions', () => {
describe('extendsDirectlyFromObject', () => {
// Inheritance Example using Classes
class Parent {}
class Child extends Parent {}
// Inheritance Example using Function
const Parent5 = function Parent5() {} as any as {new (): {}};
const Child5 = function Child5() {} as any as {new (): {}};
Child5.prototype = new Parent5();
Child5.prototype.constructor = Child5;
it('should correctly behave with instanceof', () => {
expect(new Child() instanceof Object).toBeTruthy();
expect(new Child() instanceof Parent).toBeTruthy();
expect(new Parent() instanceof Child).toBeFalsy();
expect(new Child5() instanceof Object).toBeTruthy();
expect(new Child5() instanceof Parent5).toBeTruthy();
expect(new Parent5() instanceof Child5).toBeFalsy();
});
it('should detect direct inheritance form Object', () => {
expect(extendsDirectlyFromObject(Parent)).toBeTruthy();
expect(extendsDirectlyFromObject(Child)).toBeFalsy();
expect(extendsDirectlyFromObject(Parent5)).toBeTruthy();
expect(extendsDirectlyFromObject(Child5)).toBeFalsy();
});
});
describe('convertToR3QueryMetadata', () => {
it('should convert decorator with a single string selector', () => {
expect(
convertToR3QueryMetadata('propName', {
selector: 'localRef',
descendants: false,
first: false,
isViewQuery: false,
read: undefined,
static: false,
emitDistinctChangesOnly: false,
}),
).toEqual({
propertyName: 'propName',
predicate: ['localRef'],
descendants: false,
first: false,
read: null,
static: false,
emitDistinctChangesOnly: false,
isSignal: false,
});
});
it('should convert decorator with multiple string selectors', () => {
expect(
convertToR3QueryMetadata('propName', {
selector: 'foo, bar,baz',
descendants: true,
first: true,
isViewQuery: true,
read: undefined,
static: false,
emitDistinctChangesOnly: false,
}),
).toEqual({
propertyName: 'propName',
predicate: ['foo', 'bar', 'baz'],
descendants: true,
first: true,
read: null,
static: false,
emitDistinctChangesOnly: false,
isSignal: false,
});
});
it('should convert decorator with type selector and read option', () => {
class Directive {}
const converted = convertToR3QueryMetadata('propName', {
selector: Directive,
descendants: true,
first: true,
isViewQuery: true,
read: Directive,
static: false,
emitDistinctChangesOnly: false,
});
expect(converted.predicate).toEqual(Directive);
expect(converted.read).toEqual(Directive);
});
});
describe('directiveMetadata', () => {
it('should not inherit propMetadata from super class', () => {
class SuperDirective {}
setClassMetadata(SuperDirective, [{type: Directive, args: []}], null, {
handleClick: [{type: HostListener, args: ['click']}],
});
class SubDirective extends SuperDirective {}
setClassMetadata(SubDirective, [{type: Directive, args: []}], null, null);
expect(directiveMetadata(SuperDirective, {}).propMetadata['handleClick']).toBeTruthy();
expect(directiveMetadata(SubDirective, {}).propMetadata['handleClick']).toBeFalsy();
});
it('should not inherit propMetadata from grand super class', () => {
class SuperSuperDirective {}
setClassMetadata(SuperSuperDirective, [{type: Directive, args: []}], null, {
handleClick: [{type: HostListener, args: ['click']}],
});
class SuperDirective {}
setClassMetadata(SuperDirective, [{type: Directive, args: []}], null, null);
class SubDirective extends SuperDirective {}
setClassMetadata(SubDirective, [{type: Directive, args: []}], null, null);
expect(directiveMetadata(SuperSuperDirective, {}).propMetadata['handleClick']).toBeTruthy();
expect(directiveMetadata(SuperDirective, {}).propMetadata['handleClick']).toBeFalsy();
expect(directiveMetadata(SubDirective, {}).propMetadata['handleClick']).toBeFalsy();
});
it('should not inherit propMetadata from super class when sub class has its own propMetadata', () => {
class SuperDirective {}
setClassMetadata(SuperDirective, [{type: Directive}], null, {
someInput: [{type: Input}],
handleClick: [{type: HostListener, args: ['click', ['$event']]}],
});
class SubDirective extends SuperDirective {}
setClassMetadata(SubDirective, [{type: Directive}], null, {someOtherInput: [{type: Input}]});
const superPropMetadata = directiveMetadata(SuperDirective, {}).propMetadata;
const subPropMetadata = directiveMetadata(SubDirective, {}).propMetadata;
expect(superPropMetadata['handleClick']).toBeTruthy();
expect(superPropMetadata['someInput']).toBeTruthy();
expect(subPropMetadata['handleClick']).toBeFalsy();
expect(subPropMetadata['someInput']).toBeFalsy();
expect(subPropMetadata['someOtherInput']).toBeTruthy();
});
});
});
| {
"end_byte": 5814,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/jit/directive_spec.ts"
} |
angular/packages/core/test/render3/jit/declare_injector_spec.ts_0_1440 | /**
* @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 {InjectionToken, ɵɵInjectorDef, ɵɵngDeclareInjector} from '@angular/core';
describe('Injector declaration jit compilation', () => {
it('should compile a minimal Injector declaration', () => {
const def = ɵɵngDeclareInjector({type: TestClass}) as ɵɵInjectorDef<TestClass>;
expect(def.providers).toEqual([]);
expect(def.imports).toEqual([]);
});
it('should compile an Injector declaration with providers', () => {
class OtherClass {}
const TestToken = new InjectionToken('TestToken');
const testTokenValue = {};
const def = ɵɵngDeclareInjector({
type: TestClass,
providers: [OtherClass, {provide: TestToken, useValue: testTokenValue}],
}) as ɵɵInjectorDef<TestClass>;
expect(def.providers).toEqual([OtherClass, {provide: TestToken, useValue: testTokenValue}]);
expect(def.imports).toEqual([]);
});
it('should compile an Injector declaration with imports', () => {
const OtherInjector: any = {};
const def = ɵɵngDeclareInjector({
type: TestClass,
imports: [OtherInjector],
}) as ɵɵInjectorDef<TestClass>;
expect(def.providers).toEqual([]);
expect(def.imports).toEqual([OtherInjector]);
});
});
class TestClass {}
| {
"end_byte": 1440,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/jit/declare_injector_spec.ts"
} |
angular/packages/core/test/render3/jit/declare_component_spec.ts_0_646 | /**
* @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 {InputFlags} from '@angular/compiler/src/core';
import {
ChangeDetectionStrategy,
Component,
Directive,
ElementRef,
forwardRef,
Pipe,
Type,
ViewEncapsulation,
ɵɵngDeclareComponent,
} from '@angular/core';
import {
AttributeMarker,
ComponentDef,
ɵɵInheritDefinitionFeature,
ɵɵInputTransformsFeature,
ɵɵNgOnChangesFeature,
} from '../../../src/render3';
import {functionContaining} from './matcher';
descri | {
"end_byte": 646,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/jit/declare_component_spec.ts"
} |
angular/packages/core/test/render3/jit/declare_component_spec.ts_648_8302 | ('component declaration jit compilation', () => {
it('should compile a minimal component declaration', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: `<div></div>`,
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
template: functionContaining([/element[^(]*\(0,'div'\)/]),
});
});
it('should compile a selector', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div></div>',
selector: '[dir], test',
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
selectors: [['', 'dir', ''], ['test']],
});
});
it('should compile inputs and outputs', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div></div>',
inputs: {
minifiedProperty: 'property',
minifiedClassProperty: ['bindingName', 'classProperty'],
},
outputs: {
minifiedEventName: 'eventBindingName',
},
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
inputs: {
'property': 'minifiedProperty',
'bindingName': 'minifiedClassProperty',
},
declaredInputs: {
'property': 'property',
'bindingName': 'classProperty',
},
outputs: {
'eventBindingName': 'minifiedEventName',
},
});
});
it('should compile input with a transform function', () => {
const transformFn = () => 1;
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div></div>',
inputs: {
minifiedClassProperty: ['bindingName', 'classProperty', transformFn],
},
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
inputs: {
'bindingName': ['minifiedClassProperty', InputFlags.HasDecoratorInputTransform],
},
inputTransforms: {
'minifiedClassProperty': transformFn,
},
declaredInputs: {
'bindingName': 'classProperty',
},
features: [ɵɵInputTransformsFeature],
});
});
it('should compile exportAs', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div></div>',
exportAs: ['a', 'b'],
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
exportAs: ['a', 'b'],
});
});
it('should compile providers', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div></div>',
providers: [{provide: 'token', useValue: 123}],
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
features: [jasmine.any(Function)],
providersResolver: jasmine.any(Function),
});
});
it('should compile view providers', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div></div>',
viewProviders: [{provide: 'token', useValue: 123}],
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
features: [jasmine.any(Function)],
providersResolver: jasmine.any(Function),
});
});
it('should compile content queries', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div></div>',
queries: [
{
propertyName: 'byRef',
predicate: ['ref'],
},
{
propertyName: 'byToken',
predicate: String,
descendants: true,
static: true,
first: true,
read: ElementRef,
emitDistinctChangesOnly: false,
},
],
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
contentQueries: functionContaining([
// "byRef" should use `contentQuery` with `0` (`QueryFlags.none`) for query flag
// without a read token, and bind to the full query result.
/contentQuery[^(]*\(dirIndex,_c0,4\)/,
'(ctx.byRef = _t)',
// "byToken" should use `staticContentQuery` with `3`
// (`QueryFlags.descendants|QueryFlags.isStatic`) for query flag and `ElementRef` as
// read token, and bind to the first result in the query result.
/contentQuery[^(]*\(dirIndex,[^,]*String[^,]*,3,[^)]*ElementRef[^)]*\)/,
'(ctx.byToken = _t.first)',
]),
});
});
it('should compile view queries', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div></div>',
viewQueries: [
{
propertyName: 'byRef',
predicate: ['ref'],
},
{
propertyName: 'byToken',
predicate: String,
descendants: true,
static: true,
first: true,
read: ElementRef,
emitDistinctChangesOnly: false,
},
],
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
viewQuery: functionContaining([
// "byRef" should use `viewQuery` with `0` (`QueryFlags.none`) for query flag without a read
// token, and bind to the full query result.
/viewQuery[^(]*\(_c0,4\)/,
'(ctx.byRef = _t)',
// "byToken" should use `viewQuery` with `3`
// (`QueryFlags.descendants|QueryFlags.isStatic`) for query flag and `ElementRef` as
// read token, and bind to the first result in the query result.
/viewQuery[^(]*\([^,]*String[^,]*,3,[^)]*ElementRef[^)]*\)/,
'(ctx.byToken = _t.first)',
]),
});
});
it('should compile host bindings', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div></div>',
host: {
attributes: {
'attr': 'value',
},
listeners: {
'event': 'handleEvent($event)',
},
properties: {
'foo': 'foo.prop',
'attr.bar': 'bar.prop',
},
classAttribute: 'foo bar',
styleAttribute: 'width: 100px;',
},
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
hostAttrs: [
'attr',
'value',
AttributeMarker.Classes,
'foo',
'bar',
AttributeMarker.Styles,
'width',
'100px',
],
hostBindings: functionContaining([
'return ctx.handleEvent($event)',
/hostProperty[^(]*\('foo',ctx\.foo\.prop\)/,
/attribute[^(]*\('bar',ctx\.bar\.prop\)/,
]),
hostVars: 2,
});
});
it('should compile components with inheritance', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div></div>',
usesInheritance: true,
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
features: [ɵɵInheritDefinitionFeature],
});
});
it('should compile components with onChanges lifecycle hook', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div></div>',
usesOnChanges: true,
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
features: [ɵɵNgOnChangesFeature],
});
});
it('should compile components with OnPush change detection strategy', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div></div>',
changeDetection: ChangeDetectionStrategy.OnPush,
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
onPush: true,
});
});
it('should compile components with s | {
"end_byte": 8302,
"start_byte": 648,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/jit/declare_component_spec.ts"
} |
angular/packages/core/test/render3/jit/declare_component_spec.ts_8306_15201 | s', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div></div>',
styles: ['div {}'],
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
styles: ['div[_ngcontent-%COMP%] {}'],
encapsulation: ViewEncapsulation.Emulated,
});
});
it('should compile components with view encapsulation', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div></div>',
styles: ['div {}'],
encapsulation: ViewEncapsulation.ShadowDom,
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
styles: ['div {}'],
encapsulation: ViewEncapsulation.ShadowDom,
});
});
it('should compile components with animations', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div></div>',
animations: [{type: 'trigger'}],
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
data: {
animation: [{type: 'trigger'}],
},
});
});
it('should honor preserveWhitespaces', () => {
const template = '<div> Foo </div>';
const whenTrue = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template,
preserveWhitespaces: true,
}) as ComponentDef<TestClass>;
const whenOmitted = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template,
}) as ComponentDef<TestClass>;
expectComponentDef(whenTrue, {
template: functionContaining([
/elementStart[^(]*\(0,'div'\)/,
/text[^(]*\(1,' Foo '\)/,
]),
});
expectComponentDef(whenOmitted, {
template: functionContaining([/elementStart[^(]*\(0,'div'\)/, /text[^(]*\(1,' Foo '\)/]),
});
});
it('should honor custom interpolation config', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '{% foo %}',
interpolation: ['{%', '%}'],
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
template: functionContaining([/textInterpolate[^(]*\(ctx.foo\)/]),
});
});
it('should compile used components', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<cmp></cmp>',
components: [
{
type: TestCmp,
selector: 'cmp',
},
],
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
directives: [TestCmp],
});
});
it('should compile used directives', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div dir></div>',
directives: [
{
type: TestDir,
selector: '[dir]',
},
],
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
directives: [TestDir],
});
});
it('should compile used directives together with used components', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<cmp dir></cmp>',
components: [
{
type: TestCmp,
selector: 'cmp',
},
],
directives: [
{
type: TestDir,
selector: '[dir]',
},
],
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
directives: [TestCmp, TestDir],
});
});
it('should compile forward declared directives', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div forward></div>',
directives: [
{
type: forwardRef(function () {
return ForwardDir;
}),
selector: '[forward]',
},
],
}) as ComponentDef<TestClass>;
@Directive({
selector: '[forward]',
standalone: false,
})
class ForwardDir {}
expectComponentDef(def, {
directives: [ForwardDir],
});
});
it('should compile mixed forward and direct declared directives', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '<div dir forward></div>',
directives: [
{
type: TestDir,
selector: '[dir]',
},
{
type: forwardRef(function () {
return ForwardDir;
}),
selector: '[forward]',
},
],
}) as ComponentDef<TestClass>;
@Directive({
selector: '[forward]',
standalone: false,
})
class ForwardDir {}
expectComponentDef(def, {
directives: [TestDir, ForwardDir],
});
});
it('should compile used pipes', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '{{ expr | test }}',
pipes: {
'test': TestPipe,
},
}) as ComponentDef<TestClass>;
expectComponentDef(def, {
pipes: [TestPipe],
});
});
it('should compile forward declared pipes', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '{{ expr | forward }}',
pipes: {
'forward': forwardRef(function () {
return ForwardPipe;
}),
},
}) as ComponentDef<TestClass>;
@Pipe({
name: 'forward',
standalone: false,
})
class ForwardPipe {}
expectComponentDef(def, {
pipes: [ForwardPipe],
});
});
it('should compile mixed forward and direct declared pipes', () => {
const def = ɵɵngDeclareComponent({
version: '18.0.0',
type: TestClass,
template: '{{ expr | forward | test }}',
pipes: {
'test': TestPipe,
'forward': forwardRef(function () {
return ForwardPipe;
}),
},
}) as ComponentDef<TestClass>;
@Pipe({
name: 'forward',
standalone: false,
})
class ForwardPipe {}
expectComponentDef(def, {
pipes: [TestPipe, ForwardPipe],
});
});
});
type ComponentDefExpectations = jasmine.Expected<
Pick<
ComponentDef<unknown>,
| 'selectors'
| 'template'
| 'inputs'
| 'declaredInputs'
| 'outputs'
| 'features'
| 'hostAttrs'
| 'hostBindings'
| 'hostVars'
| 'contentQueries'
| 'viewQuery'
| 'exportAs'
| 'providersResolver'
| 'encapsulation'
| 'onPush'
| 'styles'
| 'data'
| 'inputTransforms'
>
> & {
directives: Type<unknown>[] | null;
pipes: Type<unknown>[] | null;
};
/**
* Asserts that the provided component definition is according to the provided expectation.
* Definition fields for which no expectation is present are verified to be initialized to their
* default value.
*/
function expectComponentDef(
actual: ComponentDef<unknown>,
exp | {
"end_byte": 15201,
"start_byte": 8306,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/jit/declare_component_spec.ts"
} |
angular/packages/core/test/render3/jit/declare_component_spec.ts_15202_18524 | cted: Partial<ComponentDefExpectations>,
): void {
const expectation: ComponentDefExpectations = {
selectors: [],
template: jasmine.any(Function),
inputs: {},
declaredInputs: {},
inputTransforms: null,
outputs: {},
features: null,
hostAttrs: null,
hostBindings: null,
hostVars: 0,
contentQueries: null,
viewQuery: null,
exportAs: null,
providersResolver: null,
// Although the default view encapsulation is `Emulated`, the default expected view
// encapsulation is `None` as this is chosen when no styles are present.
encapsulation: ViewEncapsulation.None,
onPush: false,
styles: [],
directives: [],
pipes: [],
data: {},
...expected,
};
expect(actual.type).toBe(TestClass);
expect(actual.selectors).withContext('selectors').toEqual(expectation.selectors);
expect(actual.template).withContext('template').toEqual(expectation.template);
expect(actual.inputs).withContext('inputs').toEqual(expectation.inputs);
expect(actual.declaredInputs).withContext('declaredInputs').toEqual(expectation.declaredInputs);
expect(actual.inputTransforms)
.withContext('inputTransforms')
.toEqual(expectation.inputTransforms);
expect(actual.outputs).withContext('outputs').toEqual(expectation.outputs);
expect(actual.features).withContext('features').toEqual(expectation.features);
expect(actual.hostAttrs).withContext('hostAttrs').toEqual(expectation.hostAttrs);
expect(actual.hostBindings).withContext('hostBindings').toEqual(expectation.hostBindings);
expect(actual.hostVars).withContext('hostVars').toEqual(expectation.hostVars);
expect(actual.contentQueries).withContext('contentQueries').toEqual(expectation.contentQueries);
expect(actual.viewQuery).withContext('viewQuery').toEqual(expectation.viewQuery);
expect(actual.exportAs).withContext('exportAs').toEqual(expectation.exportAs);
expect(actual.providersResolver)
.withContext('providersResolver')
.toEqual(expectation.providersResolver);
expect(actual.encapsulation).withContext('encapsulation').toEqual(expectation.encapsulation);
expect(actual.onPush).withContext('onPush').toEqual(expectation.onPush);
expect(actual.styles).withContext('styles').toEqual(expectation.styles);
expect(actual.data).withContext('data').toEqual(expectation.data);
const convertNullToEmptyArray = <T extends Type<any>[] | null>(arr: T): T =>
arr ?? ([] as unknown as T);
const directiveDefs =
typeof actual.directiveDefs === 'function' ? actual.directiveDefs() : actual.directiveDefs;
const directiveTypes = directiveDefs !== null ? directiveDefs.map((def) => def.type) : null;
expect(convertNullToEmptyArray(directiveTypes)).toEqual(expectation.directives);
const pipeDefs = typeof actual.pipeDefs === 'function' ? actual.pipeDefs() : actual.pipeDefs;
const pipeTypes = pipeDefs !== null ? pipeDefs.map((def) => def.type) : null;
expect(convertNullToEmptyArray(pipeTypes)).toEqual(expectation.pipes);
}
class TestClass {}
@Directive({
selector: '[dir]',
standalone: false,
})
class TestDir {}
@Component({
selector: 'cmp',
template: '',
standalone: false,
})
class TestCmp {}
@Pipe({
name: 'test',
standalone: false,
})
class TestPipe {}
| {
"end_byte": 18524,
"start_byte": 15202,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/jit/declare_component_spec.ts"
} |
angular/packages/core/test/render3/jit/declare_ng_module_spec.ts_0_4794 | /**
* @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 {
NO_ERRORS_SCHEMA,
SchemaMetadata,
Type,
ɵNgModuleDef,
ɵɵngDeclareNgModule,
} from '@angular/core';
describe('NgModule declaration jit compilation', () => {
it('should compile a minimal NgModule declaration', () => {
const def = ɵɵngDeclareNgModule({type: TestClass}) as ɵNgModuleDef<TestClass>;
expectNgModuleDef(def, {});
});
it('should compile an NgModule declaration with bootstrap classes', () => {
const def = ɵɵngDeclareNgModule({
type: TestClass,
bootstrap: [TestComponent],
}) as ɵNgModuleDef<TestClass>;
expectNgModuleDef(def, {bootstrap: [TestComponent]});
});
it('should compile an NgModule declaration with forward referenced bootstrap classes', () => {
const def = ɵɵngDeclareNgModule({
type: TestClass,
bootstrap: () => [ForwardRef],
}) as ɵNgModuleDef<TestClass>;
class ForwardRef {}
expectNgModuleDef(def, {bootstrap: [ForwardRef]});
});
it('should compile an NgModule declaration with declarations classes', () => {
const def = ɵɵngDeclareNgModule({
type: TestClass,
declarations: [TestComponent],
}) as ɵNgModuleDef<TestClass>;
expectNgModuleDef(def, {declarations: [TestComponent]});
});
it('should compile an NgModule declaration with forward referenced declarations classes', () => {
const def = ɵɵngDeclareNgModule({
type: TestClass,
declarations: () => [TestComponent],
}) as ɵNgModuleDef<TestClass>;
expectNgModuleDef(def, {declarations: [TestComponent]});
});
it('should compile an NgModule declaration with imports classes', () => {
const def = ɵɵngDeclareNgModule({
type: TestClass,
imports: [TestModule],
}) as ɵNgModuleDef<TestClass>;
expectNgModuleDef(def, {imports: [TestModule]});
});
it('should compile an NgModule declaration with forward referenced imports classes', () => {
const def = ɵɵngDeclareNgModule({
type: TestClass,
imports: () => [TestModule],
}) as ɵNgModuleDef<TestClass>;
expectNgModuleDef(def, {imports: [TestModule]});
});
it('should compile an NgModule declaration with exports classes', () => {
const def = ɵɵngDeclareNgModule({
type: TestClass,
exports: [TestComponent, TestModule],
}) as ɵNgModuleDef<TestClass>;
expectNgModuleDef(def, {exports: [TestComponent, TestModule]});
});
it('should compile an NgModule declaration with forward referenced exports classes', () => {
const def = ɵɵngDeclareNgModule({
type: TestClass,
exports: () => [TestComponent, TestModule],
}) as ɵNgModuleDef<TestClass>;
expectNgModuleDef(def, {exports: [TestComponent, TestModule]});
});
it('should compile an NgModule declaration with schemas', () => {
const def = ɵɵngDeclareNgModule({
type: TestClass,
schemas: [NO_ERRORS_SCHEMA],
}) as ɵNgModuleDef<TestClass>;
expectNgModuleDef(def, {schemas: [NO_ERRORS_SCHEMA]});
});
it('should compile an NgModule declaration with an id expression', () => {
const id = 'ModuleID';
const def = ɵɵngDeclareNgModule({type: TestClass, id}) as ɵNgModuleDef<TestClass>;
expectNgModuleDef(def, {id: 'ModuleID'});
});
});
class TestClass {}
class TestComponent {}
class TestModule {}
type NgModuleDefExpectations = jasmine.Expected<{
schemas: SchemaMetadata[] | null;
id: string | null;
bootstrap: Type<unknown>[];
declarations: Type<unknown>[];
imports: Type<unknown>[];
exports: Type<unknown>[];
}>;
/**
* Asserts that the provided NgModule definition is according to the provided expectation.
* Definition fields for which no expectation is present are verified to be initialized to their
* default value.
*/
function expectNgModuleDef(
actual: ɵNgModuleDef<unknown>,
expected: Partial<NgModuleDefExpectations>,
): void {
const expectation: NgModuleDefExpectations = {
bootstrap: [],
declarations: [],
imports: [],
exports: [],
schemas: null,
id: null,
...expected,
};
expect(actual.type).toBe(TestClass);
expect(unwrap(actual.bootstrap)).toEqual(expectation.bootstrap);
expect(unwrap(actual.declarations)).toEqual(expectation.declarations);
expect(unwrap(actual.imports)).toEqual(expectation.imports);
expect(unwrap(actual.exports)).toEqual(expectation.exports);
expect(actual.schemas).toEqual(expectation.schemas);
expect(actual.id).toEqual(expectation.id);
}
function unwrap(values: Type<any>[] | (() => Type<any>[])): Type<any>[] {
return typeof values === 'function' ? values() : values;
}
| {
"end_byte": 4794,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/jit/declare_ng_module_spec.ts"
} |
angular/packages/core/test/render3/jit/declare_pipe_spec.ts_0_1695 | /**
* @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 {ɵɵngDeclarePipe} from '@angular/core';
import {PipeDef} from '../../../src/render3';
describe('Pipe declaration jit compilation', () => {
it('should compile a named Pipe declaration', () => {
const def = ɵɵngDeclarePipe({
type: TestClass,
name: 'foo',
version: '18.0.0',
}) as PipeDef<TestClass>;
expect(def.type).toBe(TestClass);
expect(def.name).toEqual('foo');
expect(def.pure).toEqual(true);
expect(def.standalone).toEqual(false);
});
it('should compile an impure Pipe declaration', () => {
const def = ɵɵngDeclarePipe({
type: TestClass,
name: 'foo',
pure: false,
version: '18.0.0',
}) as PipeDef<TestClass>;
expect(def.type).toBe(TestClass);
expect(def.name).toEqual('foo');
expect(def.pure).toEqual(false);
});
it('should compile 0.0.0 pipe as standalone', () => {
const def = ɵɵngDeclarePipe({
type: TestClass,
name: 'foo',
version: '0.0.0-PLACEHOLDER',
}) as PipeDef<TestClass>;
expect(def.type).toBe(TestClass);
expect(def.name).toEqual('foo');
expect(def.standalone).toEqual(true);
});
it('should compile v19+ pipe as standalone', () => {
const def = ɵɵngDeclarePipe({
type: TestClass,
name: 'foo',
version: '19.0.0',
}) as PipeDef<TestClass>;
expect(def.type).toBe(TestClass);
expect(def.name).toEqual('foo');
expect(def.standalone).toEqual(true);
});
});
class TestClass {}
| {
"end_byte": 1695,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/jit/declare_pipe_spec.ts"
} |
angular/packages/core/test/render3/jit/matcher.ts_0_1652 | /**
* @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
*/
/**
* Jasmine matcher to verify that a function contains the provided code fragments.
*/
export function functionContaining(
expectedFragments: Array<string | RegExp>,
): jasmine.AsymmetricMatcher<Function> {
let _actual: Function | null = null;
const matches = (code: string, fragment: string | RegExp): boolean => {
if (typeof fragment === 'string') {
return code.includes(fragment);
} else {
return fragment.test(code);
}
};
return {
asymmetricMatch(actual: Function): boolean {
_actual = actual;
if (typeof actual !== 'function') {
return false;
}
const code = actual.toString();
for (const fragment of expectedFragments) {
if (!matches(code, fragment)) {
return false;
}
}
return true;
},
jasmineToString(pp: (value: any) => string): string {
if (typeof _actual !== 'function') {
return `Expected function to contain code fragments ${pp(expectedFragments)} but got ${pp(
_actual,
)}`;
}
const errors: string[] = [];
const code = _actual.toString();
errors.push(
`The actual function with code:\n${code}\n\ndid not contain the following fragments:`,
);
for (const fragment of expectedFragments) {
if (!matches(code, fragment)) {
errors.push(`- ${fragment}`);
}
}
return errors.join('\n');
},
};
}
| {
"end_byte": 1652,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/jit/matcher.ts"
} |
angular/packages/core/test/render3/jit/declare_directive_spec.ts_0_7383 | /**
* @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 {ElementRef, forwardRef, ɵɵngDeclareDirective} from '@angular/core';
import {
AttributeMarker,
DirectiveDef,
ɵɵInheritDefinitionFeature,
ɵɵNgOnChangesFeature,
} from '../../../src/render3';
import {functionContaining} from './matcher';
describe('directive declaration jit compilation', () => {
it('should compile a minimal directive declaration', () => {
const def = ɵɵngDeclareDirective({
version: '18.0.0',
type: TestClass,
}) as DirectiveDef<TestClass>;
expectDirectiveDef(def, {});
});
it('should compile a selector', () => {
const def = ɵɵngDeclareDirective({
version: '18.0.0',
type: TestClass,
selector: '[dir], test',
}) as DirectiveDef<TestClass>;
expectDirectiveDef(def, {
selectors: [['', 'dir', ''], ['test']],
});
});
it('should compile inputs and outputs', () => {
const def = ɵɵngDeclareDirective({
version: '18.0.0',
type: TestClass,
inputs: {
minifiedProperty: 'property',
minifiedClassProperty: ['bindingName', 'classProperty'],
},
outputs: {
minifiedEventName: 'eventBindingName',
},
}) as DirectiveDef<TestClass>;
expectDirectiveDef(def, {
inputs: {
'property': 'minifiedProperty',
'bindingName': 'minifiedClassProperty',
},
declaredInputs: {
'property': 'property',
'bindingName': 'classProperty',
},
outputs: {
'eventBindingName': 'minifiedEventName',
},
});
});
it('should compile exportAs', () => {
const def = ɵɵngDeclareDirective({
version: '18.0.0',
type: TestClass,
exportAs: ['a', 'b'],
}) as DirectiveDef<TestClass>;
expectDirectiveDef(def, {
exportAs: ['a', 'b'],
});
});
it('should compile providers', () => {
const def = ɵɵngDeclareDirective({
version: '18.0.0',
type: TestClass,
providers: [{provide: 'token', useValue: 123}],
}) as DirectiveDef<TestClass>;
expectDirectiveDef(def, {
features: [jasmine.any(Function)],
providersResolver: jasmine.any(Function),
});
});
it('should compile content queries', () => {
const def = ɵɵngDeclareDirective({
version: '18.0.0',
type: TestClass,
queries: [
{
propertyName: 'byRef',
predicate: ['ref'],
},
{
propertyName: 'byToken',
predicate: String,
descendants: true,
static: true,
first: true,
read: ElementRef,
emitDistinctChangesOnly: false,
},
],
}) as DirectiveDef<TestClass>;
expectDirectiveDef(def, {
contentQueries: functionContaining([
// "byRef" should use `contentQuery` with `0` (`QueryFlags.descendants|QueryFlags.isStatic`)
// for query flag without a read token, and bind to the full query result.
/contentQuery[^(]*\(dirIndex,_c0,4\)/,
'(ctx.byRef = _t)',
// "byToken" should use `viewQuery` with `3` (`QueryFlags.static|QueryFlags.descendants`)
// for query flag and `ElementRef` as read token, and bind to the first result in the
// query result.
/contentQuery[^(]*\([^,]*dirIndex,[^,]*String[^,]*,3,[^)]*ElementRef[^)]*\)/,
'(ctx.byToken = _t.first)',
]),
});
});
it('should compile content queries with forwardRefs', () => {
const def = ɵɵngDeclareDirective({
version: '18.0.0',
type: TestClass,
queries: [
{
propertyName: 'byRef',
predicate: forwardRef(() => Child),
},
],
}) as DirectiveDef<TestClass>;
class Child {}
expectDirectiveDef(def, {
contentQueries: functionContaining([
/contentQuery[^(]*\(dirIndex,[^,]*resolveForwardRef[^,]*forward_ref[^,]*,[\s]*4\)/,
'(ctx.byRef = _t)',
]),
});
});
it('should compile view queries', () => {
const def = ɵɵngDeclareDirective({
version: '18.0.0',
type: TestClass,
viewQueries: [
{
propertyName: 'byRef',
predicate: ['ref'],
},
{
propertyName: 'byToken',
predicate: String,
descendants: true,
static: true,
first: true,
read: ElementRef,
emitDistinctChangesOnly: false,
},
],
}) as DirectiveDef<TestClass>;
expectDirectiveDef(def, {
viewQuery: functionContaining([
// "byRef" should use `viewQuery` with`0` (`QueryFlags.none`) for query flag without a read
// token, and bind to the full query result.
/viewQuery[^(]*\(_c0,4\)/,
'(ctx.byRef = _t)',
// "byToken" should use `viewQuery` with `3` (`QueryFlags.static|QueryFlags.descendants`)
// for query flag and `ElementRef` as read token, and bind to the first result in the
// query result.
/viewQuery[^(]*\([^,]*String[^,]*,3,[^)]*ElementRef[^)]*\)/,
'(ctx.byToken = _t.first)',
]),
});
});
it('should compile view queries with forwardRefs', () => {
const def = ɵɵngDeclareDirective({
version: '18.0.0',
type: TestClass,
viewQueries: [
{
propertyName: 'byRef',
predicate: forwardRef(() => Child),
},
],
}) as DirectiveDef<TestClass>;
class Child {}
expectDirectiveDef(def, {
viewQuery: functionContaining([
/viewQuery[^(]*\([^,]*resolveForwardRef[^,]*forward_ref[^,]*,[\s]*4\)/,
'(ctx.byRef = _t)',
]),
});
});
it('should compile host bindings', () => {
const def = ɵɵngDeclareDirective({
version: '18.0.0',
type: TestClass,
host: {
attributes: {
'attr': 'value',
},
listeners: {
'event': 'handleEvent($event)',
},
properties: {
'foo': 'foo.prop',
'attr.bar': 'bar.prop',
},
classAttribute: 'foo bar',
styleAttribute: 'width: 100px;',
},
}) as DirectiveDef<TestClass>;
expectDirectiveDef(def, {
hostAttrs: [
'attr',
'value',
AttributeMarker.Classes,
'foo',
'bar',
AttributeMarker.Styles,
'width',
'100px',
],
hostBindings: functionContaining([
'return ctx.handleEvent($event)',
/hostProperty[^(]*\('foo',ctx\.foo\.prop\)/,
/attribute[^(]*\('bar',ctx\.bar\.prop\)/,
]),
hostVars: 2,
});
});
it('should compile directives with inheritance', () => {
const def = ɵɵngDeclareDirective({
version: '18.0.0',
type: TestClass,
usesInheritance: true,
}) as DirectiveDef<TestClass>;
expectDirectiveDef(def, {
features: [ɵɵInheritDefinitionFeature],
});
});
it('should compile directives with onChanges lifecycle hook', () => {
const def = ɵɵngDeclareDirective({
version: '18.0.0',
type: TestClass,
usesOnChanges: true,
}) as DirectiveDef<TestClass>;
expectDirectiveDef(def, {
features: [ɵɵNgOnChangesFeature],
});
});
it('should compile host direct | {
"end_byte": 7383,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/jit/declare_directive_spec.ts"
} |
angular/packages/core/test/render3/jit/declare_directive_spec.ts_7387_11298 | ', () => {
class One {}
class Two {}
const def = ɵɵngDeclareDirective({
version: '18.0.0',
type: TestClass,
hostDirectives: [
{
directive: One,
inputs: ['firstInput', 'firstInput', 'secondInput', 'secondInputAlias'],
outputs: ['firstOutput', 'firstOutput', 'secondOutput', 'secondOutputAlias'],
},
{
directive: Two,
},
],
}) as DirectiveDef<TestClass>;
expectDirectiveDef(def, {
features: [jasmine.any(Function)],
hostDirectives: [
{
directive: One,
inputs: {
'firstInput': 'firstInput',
'secondInput': 'secondInputAlias',
},
outputs: {
'firstOutput': 'firstOutput',
'secondOutput': 'secondOutputAlias',
},
},
{
directive: Two,
inputs: {},
outputs: {},
},
],
});
});
it('should declare a 0.0.0 directive as standalone', () => {
const def = ɵɵngDeclareDirective({
version: '0.0.0-PLACEHOLDER',
type: TestClass,
}) as DirectiveDef<TestClass>;
expectDirectiveDef(def, {
standalone: true,
});
});
it('should declare a v19+ directive as standalone', () => {
const def = ɵɵngDeclareDirective({
version: '19.0.0',
type: TestClass,
}) as DirectiveDef<TestClass>;
expectDirectiveDef(def, {
standalone: true,
});
});
});
type DirectiveDefExpectations = jasmine.Expected<
Pick<
DirectiveDef<unknown>,
| 'selectors'
| 'inputs'
| 'declaredInputs'
| 'outputs'
| 'features'
| 'hostAttrs'
| 'hostBindings'
| 'hostVars'
| 'contentQueries'
| 'viewQuery'
| 'exportAs'
| 'providersResolver'
| 'hostDirectives'
| 'standalone'
>
>;
/**
* Asserts that the provided directive definition is according to the provided expectation.
* Definition fields for which no expectation is present are verified to be initialized to their
* default value.
*/
function expectDirectiveDef(
actual: DirectiveDef<unknown>,
expected: Partial<DirectiveDefExpectations>,
): void {
const expectation: DirectiveDefExpectations = {
selectors: [],
inputs: {},
declaredInputs: {},
outputs: {},
features: null,
hostAttrs: null,
hostBindings: null,
hostVars: 0,
contentQueries: null,
viewQuery: null,
exportAs: null,
providersResolver: null,
hostDirectives: null,
standalone: false,
...expected,
};
expect(actual.type).toBe(TestClass);
expect(actual.selectors).withContext('selectors').toEqual(expectation.selectors);
expect(actual.inputs).withContext('inputs').toEqual(expectation.inputs);
expect(actual.declaredInputs).withContext('declaredInputs').toEqual(expectation.declaredInputs);
expect(actual.outputs).withContext('outputs').toEqual(expectation.outputs);
expect(actual.features).withContext('features').toEqual(expectation.features);
expect(actual.hostAttrs).withContext('hostAttrs').toEqual(expectation.hostAttrs);
expect(actual.hostBindings).withContext('hostBindings').toEqual(expectation.hostBindings);
expect(actual.hostVars).withContext('hostVars').toEqual(expectation.hostVars);
expect(actual.contentQueries).withContext('contentQueries').toEqual(expectation.contentQueries);
expect(actual.viewQuery).withContext('viewQuery').toEqual(expectation.viewQuery);
expect(actual.exportAs).withContext('exportAs').toEqual(expectation.exportAs);
expect(actual.providersResolver)
.withContext('providersResolver')
.toEqual(expectation.providersResolver);
expect(actual.hostDirectives).withContext('hostDirectives').toEqual(expectation.hostDirectives);
expect(actual.standalone).withContext('standalone').toEqual(expectation.standalone);
}
class TestClass {}
| {
"end_byte": 11298,
"start_byte": 7387,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/jit/declare_directive_spec.ts"
} |
angular/packages/core/test/render3/jit/declare_injectable_spec.ts_0_6052 | /**
* @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 {
forwardRef,
InjectionToken,
Injector,
ɵcreateInjector,
ɵInjectorProfilerContext,
ɵsetCurrentInjector,
ɵsetInjectorProfilerContext,
ɵɵdefineInjector,
ɵɵInjectableDeclaration,
ɵɵngDeclareInjectable,
ɵɵngDeclareInjector,
ɵɵngDeclareNgModule,
} from '@angular/core';
describe('Injectable declaration jit compilation', () => {
let previousInjector: Injector | null | undefined;
let previousInjectorProfilerContext: ɵInjectorProfilerContext;
beforeEach(() => {
const injector = ɵcreateInjector(TestInjector);
previousInjector = ɵsetCurrentInjector(injector);
previousInjectorProfilerContext = ɵsetInjectorProfilerContext({injector, token: null});
});
afterEach(() => {
ɵsetCurrentInjector(previousInjector);
previousInjectorProfilerContext = ɵsetInjectorProfilerContext(previousInjectorProfilerContext);
});
it('should compile a minimal injectable declaration that delegates to `ɵfac`', () => {
const provider = Minimal.ɵprov as ɵɵInjectableDeclaration<Minimal>;
expect((provider.token as any).name).toEqual('Minimal');
expect(provider.factory).toBe(Minimal.ɵfac);
const instance = provider.factory();
expect(instance).toBeInstanceOf(Minimal);
});
it('should compile a simple `useClass` injectable declaration', () => {
const provider = UseClass.ɵprov as ɵɵInjectableDeclaration<UseClass>;
expect((provider.token as any).name).toEqual('UseClass');
const instance = provider.factory();
expect(instance).toBeInstanceOf(UseClass);
});
it('should compile a simple `useFactory` injectable declaration', () => {
const provider = UseFactory.ɵprov as ɵɵInjectableDeclaration<UseFactory>;
expect((provider.token as any).name).toEqual('UseFactory');
const instance = provider.factory();
expect(instance).toBeInstanceOf(UseFactory);
expect(instance.msg).toEqual('from factory');
});
it('should compile a simple `useValue` injectable declaration', () => {
const provider = UseValue.ɵprov as ɵɵInjectableDeclaration<string>;
expect((provider.token as any).name).toEqual('UseValue');
const instance = provider.factory();
expect(instance).toEqual('a value');
});
it('should compile a simple `useExisting` injectable declaration', () => {
const provider = UseExisting.ɵprov as ɵɵInjectableDeclaration<string>;
expect((provider.token as any).name).toEqual('UseExisting');
const instance = provider.factory();
expect(instance).toEqual('existing');
});
it('should compile a `useClass` injectable declaration with dependencies', () => {
const provider = DependingClass.ɵprov as ɵɵInjectableDeclaration<DependingClass>;
expect((provider.token as any).name).toEqual('DependingClass');
const instance = provider.factory();
expect(instance).toBeInstanceOf(DependingClass);
expect(instance.testClass).toBeInstanceOf(UseClass);
});
it('should compile a `useFactory` injectable declaration with dependencies', () => {
const provider = DependingFactory.ɵprov as ɵɵInjectableDeclaration<DependingFactory>;
expect((provider.token as any).name).toEqual('DependingFactory');
const instance = provider.factory();
expect(instance).toBeInstanceOf(DependingFactory);
expect(instance.testClass).toBeInstanceOf(UseClass);
});
it('should unwrap a `ForwardRef` `useClass` injectable declaration', () => {
class TestClass {
static ɵprov = ɵɵngDeclareInjectable({
type: TestClass,
useClass: forwardRef(function () {
return FutureClass;
}),
});
}
class FutureClass {
static ɵfac = () => new FutureClass();
}
const provider = TestClass.ɵprov as ɵɵInjectableDeclaration<FutureClass>;
const instance = provider.factory();
expect(instance).toBeInstanceOf(FutureClass);
});
it('should unwrap a `ForwardRef` `providedIn` injectable declaration', () => {
const expected = {};
class TestClass {
static ɵprov = ɵɵngDeclareInjectable({
type: TestClass,
providedIn: forwardRef(() => FutureModule),
useValue: expected,
});
}
class FutureModule {
static ɵinj = ɵɵngDeclareInjector({type: FutureModule});
}
const injector = ɵcreateInjector(FutureModule);
const actual = injector.get(TestClass);
expect(actual).toBe(expected);
});
});
class Minimal {
static ɵfac = () => new Minimal();
static ɵprov = ɵɵngDeclareInjectable({type: Minimal});
}
class UseClass {
static ɵprov = ɵɵngDeclareInjectable({type: UseClass, useClass: UseClass});
}
class UseFactory {
constructor(readonly msg: string) {}
static ɵprov = ɵɵngDeclareInjectable({
type: UseFactory,
useFactory: () => new UseFactory('from factory'),
});
}
class UseValue {
constructor(readonly msg: string) {}
static ɵprov = ɵɵngDeclareInjectable({type: UseValue, useValue: 'a value'});
}
const UseExistingToken = new InjectionToken('UseExistingToken');
class UseExisting {
static ɵprov = ɵɵngDeclareInjectable({type: UseExisting, useExisting: UseExistingToken});
}
class DependingClass {
constructor(readonly testClass: UseClass) {}
static ɵprov = ɵɵngDeclareInjectable({
type: DependingClass,
useClass: DependingClass,
deps: [{token: UseClass}],
});
}
class DependingFactory {
constructor(readonly testClass: UseClass) {}
static ɵprov = ɵɵngDeclareInjectable({
type: DependingFactory,
useFactory: (dep: UseClass) => new DependingFactory(dep),
deps: [{token: UseClass}],
});
}
class TestInjector {
static ɵinj = ɵɵdefineInjector({
providers: [
UseClass,
UseFactory,
UseValue,
UseExisting,
DependingClass,
{provide: UseExistingToken, useValue: 'existing'},
],
});
}
| {
"end_byte": 6052,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/jit/declare_injectable_spec.ts"
} |
angular/packages/core/test/render3/styling_next/style_binding_list_spec.ts_0_4228 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {createTNode} from '@angular/core/src/render3/instructions/shared';
import {TNode, TNodeType} from '@angular/core/src/render3/interfaces/node';
import {
getTStylingRangeNext,
getTStylingRangeNextDuplicate,
getTStylingRangePrev,
getTStylingRangePrevDuplicate,
TStylingKey,
TStylingRange,
} from '@angular/core/src/render3/interfaces/styling';
import {LView, TData} from '@angular/core/src/render3/interfaces/view';
import {enterView, leaveView} from '@angular/core/src/render3/state';
import {insertTStylingBinding} from '@angular/core/src/render3/styling/style_binding_list';
import {newArray} from '@angular/core/src/util/array_utils';
describe('TNode styling linked list', () => {
const mockFirstUpdatePassLView: LView = [null, {firstUpdatePass: true}] as any;
beforeEach(() => enterView(mockFirstUpdatePassLView));
afterEach(() => leaveView());
describe('insertTStylingBinding', () => {
it('should append template only', () => {
const tNode = createTNode(null!, null!, TNodeType.Element, 0, '', null);
const tData: TData = [null, null];
insertTStylingBinding(tData, tNode, 'tmpl1', 2, false, true);
expectRange(tNode.classBindings).toEqual([2, 2]);
expectTData(tData).toEqual([
null,
null, // 0
'tmpl1',
[false, 0, false, 0], // 2
]);
insertTStylingBinding(tData, tNode, 'tmpl2', 4, false, true);
expectRange(tNode.classBindings).toEqual([2, 4]);
expectTData(tData).toEqual([
null,
null, // 0
'tmpl1',
[false, 0, false, 4], // 2
'tmpl2',
[false, 2, false, 0], // 4
]);
insertTStylingBinding(tData, tNode, 'host1', 6, true, true);
expectRange(tNode.classBindings).toEqual([2, 4]);
expectTData(tData).toEqual([
null,
null, // 0
'tmpl1',
[false, 6, false, 4], // 2
'tmpl2',
[false, 2, false, 0], // 4
'host1',
[false, 0, false, 2], // 6
]);
insertTStylingBinding(tData, tNode, 'host2', 8, true, true);
expectRange(tNode.classBindings).toEqual([2, 4]);
expectTData(tData).toEqual([
null,
null, // 0
'tmpl1',
[false, 8, false, 4], // 2
'tmpl2',
[false, 2, false, 0], // 4
'host1',
[false, 0, false, 8], // 6
'host2',
[false, 6, false, 2], // 8
]);
});
it('should append host only', () => {
const tData: TData = [null, null];
const tNode = createTNode(null!, null!, TNodeType.Element, 0, '', null);
insertTStylingBinding(tData, tNode, 'host1', 2, true, true);
expectRange(tNode.classBindings).toEqual([2, 0 /* no template binding */]);
expectTData(tData).toEqual([
null,
null, // 0
'host1',
[false, 0, false, 0], // 2
]);
insertTStylingBinding(tData, tNode, 'host2', 4, true, true);
expectRange(tNode.classBindings).toEqual([4, 0 /* no template binding */]);
expectTData(tData).toEqual([
null,
null, // 0
'host1',
[false, 0, false, 4], // 2
'host2',
[false, 2, false, 0], // 4
]);
});
it('should append template and host', () => {
const tNode = createTNode(null!, null!, TNodeType.Element, 0, '', null);
const tData: TData = [null, null];
insertTStylingBinding(tData, tNode, 'tmpl1', 2, false, true);
expectRange(tNode.classBindings).toEqual([2, 2]);
expectTData(tData).toEqual([
null,
null, // 0
'tmpl1',
[false, 0, false, 0], // 2
]);
insertTStylingBinding(tData, tNode, 'host1', 4, true, true);
expectRange(tNode.classBindings).toEqual([2, 2]);
expectTData(tData).toEqual([
null,
null, // 0
'tmpl1',
[false, 4, false, 0], // 2
'host1',
[false, 0, false, 2], // 4
]);
});
it("should support example in 'tnode_linked_list.ts' documentation", () => | {
"end_byte": 4228,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/styling_next/style_binding_list_spec.ts"
} |
angular/packages/core/test/render3/styling_next/style_binding_list_spec.ts_4229_10404 | {
// See: `tnode_linked_list.ts` file description for this example.
// Template: (ExampleComponent)
// ɵɵstyleMap({color: '#001'}); // Binding index: 10
// ɵɵstyleProp('color', '#002'); // Binding index: 12
// MyComponent
// ɵɵstyleMap({color: '#003'}); // Binding index: 20
// ɵɵstyleProp('color', '#004'); // Binding index: 22
// Style1Directive
// ɵɵstyleMap({color: '#005'}); // Binding index: 24
// ɵɵstyleProp('color', '#006'); // Binding index: 26
// Style2Directive
// ɵɵstyleMap({color: '#007'}); // Binding index: 28
// ɵɵstyleProp('color', '#008'); // Binding index: 30
const tNode = createTNode(null!, null!, TNodeType.Element, 0, '', null);
tNode.styles = '';
const tData: TData = newArray(32, null);
insertTStylingBinding(tData, tNode, null, 10, false, false);
expectRange(tNode.styleBindings).toEqual([10, 10]);
expectTData(tData).toEqual([
...empty_0_through_9, //
null,
[false, 0, false, 0], // 10 - Template: ɵɵstyleMap({color: '#001'});
null,
null, // 12
...empty_14_through_19, // 14-19
null,
null, // 20
null,
null, // 22
null,
null, // 24
null,
null, // 26
null,
null, // 28
null,
null, // 30
]);
expectPriorityOrder(tData, tNode, false).toEqual([
[10, null, false, false], // 10 - Template: ɵɵstyleMap({color: '#001'});
]);
insertTStylingBinding(tData, tNode, 'color', 12, false, false);
expectRange(tNode.styleBindings).toEqual([10, 12]);
expectTData(tData).toEqual([
...empty_0_through_9, //
null,
[false, 0, false, 12], // 10 - Template: ɵɵstyleMap({color: '#001'});
'color',
[false, 10, false, 0], // 12 - Template: ɵɵstyleProp('color', '#002'});
...empty_14_through_19, // 14-19
null,
null, // 20
null,
null, // 22
null,
null, // 24
null,
null, // 26
null,
null, // 28
null,
null, // 30
]);
expectPriorityOrder(tData, tNode, false).toEqual([
[10, null, false, true], // 10 - Template: ɵɵstyleMap({color: '#001'});
[12, 'color', true, false], // 12 - Template: ɵɵstyleProp('color', '#002'});
]);
insertTStylingBinding(tData, tNode, null, 20, true, false);
expectRange(tNode.styleBindings).toEqual([10, 12]);
expectTData(tData).toEqual([
...empty_0_through_9, //
null,
[false, 20, false, 12], // 10 - Template: ɵɵstyleMap({color: '#001'});
'color',
[false, 10, false, 0], // 12 - Template: ɵɵstyleProp('color', '#002'});
...empty_14_through_19, // 14-19
null,
[false, 0, false, 10], // 20 - MyComponent: ɵɵstyleMap({color: '#003'});
null,
null, // 22
null,
null, // 24
null,
null, // 26
null,
null, // 28
null,
null, // 30
]);
expectPriorityOrder(tData, tNode, false).toEqual([
[20, null, false, true], // 20 - MyComponent: ɵɵstyleMap({color: '#003'});
[10, null, true, true], // 10 - Template: ɵɵstyleMap({color: '#001'});
[12, 'color', true, false], // 12 - Template: ɵɵstyleProp('color', '#002'});
]);
insertTStylingBinding(tData, tNode, 'color', 22, true, false);
expectRange(tNode.styleBindings).toEqual([10, 12]);
expectTData(tData).toEqual([
...empty_0_through_9, // 00-09
null,
[false, 22, false, 12], // 10 - Template: ɵɵstyleMap({color: '#001'});
'color',
[false, 10, false, 0], // 12 - Template: ɵɵstyleProp('color', '#002'});
...empty_14_through_19, // 14-19
null,
[false, 0, false, 22], // 20 - MyComponent: ɵɵstyleMap({color: '#003'});
'color',
[false, 20, false, 10], // 22 - MyComponent: ɵɵstyleProp('color', '#004'});
null,
null, // 24
null,
null, // 26
null,
null, // 28
null,
null, // 30
]);
expectPriorityOrder(tData, tNode, false).toEqual([
[20, null, false, true], // 20 - MyComponent: ɵɵstyleMap({color: '#003'});
[22, 'color', true, true], // 22 - MyComponent: ɵɵstyleProp('color', '#004'});
[10, null, true, true], // 10 - Template: ɵɵstyleMap({color: '#001'});
[12, 'color', true, false], // 12 - Template: ɵɵstyleProp('color', '#002'});
]);
insertTStylingBinding(tData, tNode, null, 24, true, false);
expectRange(tNode.styleBindings).toEqual([10, 12]);
expectTData(tData).toEqual([
...empty_0_through_9, //
null,
[false, 24, false, 12], // 10 - Template: ɵɵstyleMap({color: '#001'});
'color',
[false, 10, false, 0], // 12 - Template: ɵɵstyleProp('color', '#002'});
...empty_14_through_19, // 14-19
null,
[false, 0, false, 22], // 20 - MyComponent: ɵɵstyleMap({color: '#003'});
'color',
[false, 20, false, 24], // 22 - MyComponent: ɵɵstyleProp('color', '#004'});
null,
[false, 22, false, 10], // 24 - Style1Directive: ɵɵstyleMap({color: '#003'});
null,
null, // 26
null,
null, // 28
null,
null, // 30
]);
expectPriorityOrder(tData, tNode, false).toEqual([
[20, null, false, true], // 20 - MyComponent: ɵɵstyleMap({color: '#003'});
[22, 'color', true, true], // 22 - MyComponent: ɵɵstyleProp('color', '#004'});
[24, null, true, true], // 24 - Style1Directive: ɵɵstyleMap({color: '#003'});
[10, null, true, true], // 10 - Template: ɵɵstyleMap({color: '#001'});
[12, 'color', true, false], // 12 - Template: ɵɵstyleProp('color', '#002'});
]);
insertTStylingBinding(tData, tNode, 'color', 26, true, false);
expectRange(tNode.styleBindings).toEqual([10, 12]);
expectTData(tData).toEqual([
...empty_0_through_9, // 00-09
| {
"end_byte": 10404,
"start_byte": 4229,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/styling_next/style_binding_list_spec.ts"
} |
angular/packages/core/test/render3/styling_next/style_binding_list_spec.ts_10411_15343 | null,
[false, 26, false, 12], // 10 - Template: ɵɵstyleMap({color: '#001'});
'color',
[false, 10, false, 0], // 12 - Template: ɵɵstyleProp('color', '#002'});
...empty_14_through_19, // 14-19
null,
[false, 0, false, 22], // 20 - MyComponent: ɵɵstyleMap({color: '#003'});
'color',
[false, 20, false, 24], // 22 - MyComponent: ɵɵstyleProp('color', '#004'});
null,
[false, 22, false, 26], // 24 - Style1Directive: ɵɵstyleMap({color: '#005'});
'color',
[false, 24, false, 10], // 26 - Style1Directive: ɵɵstyleProp('color', '#006'});
null,
null, // 28
null,
null, // 30
]);
expectPriorityOrder(tData, tNode, false).toEqual([
[20, null, false, true], // 20 - MyComponent: ɵɵstyleMap({color: '#003'});
[22, 'color', true, true], // 22 - MyComponent: ɵɵstyleProp('color', '#004'});
[24, null, true, true], // 24 - Style1Directive: ɵɵstyleMap({color: '#003'});
[26, 'color', true, true], // 26 - Style1Directive: ɵɵstyleProp('color', '#006'});
[10, null, true, true], // 10 - Template: ɵɵstyleMap({color: '#001'});
[12, 'color', true, false], // 12 - Template: ɵɵstyleProp('color', '#002'});
]);
insertTStylingBinding(tData, tNode, null, 28, true, false);
expectRange(tNode.styleBindings).toEqual([10, 12]);
expectTData(tData).toEqual([
...empty_0_through_9, //
null,
[false, 28, false, 12], // 10 - Template: ɵɵstyleMap({color: '#001'});
'color',
[false, 10, false, 0], // 12 - Template: ɵɵstyleProp('color', '#002'});
...empty_14_through_19, // 14-19
null,
[false, 0, false, 22], // 20 - MyComponent: ɵɵstyleMap({color: '#003'});
'color',
[false, 20, false, 24], // 22 - MyComponent: ɵɵstyleProp('color', '#004'});
null,
[false, 22, false, 26], // 24 - Style1Directive: ɵɵstyleMap({color: '#005'});
'color',
[false, 24, false, 28], // 26 - Style1Directive: ɵɵstyleProp('color', '#006'});
null,
[false, 26, false, 10], // 28 - Style2Directive: ɵɵstyleMap({color: '#007'});
null,
null, // 30
]);
expectPriorityOrder(tData, tNode, false).toEqual([
[20, null, false, true], // 20 - MyComponent: ɵɵstyleMap({color: '#003'});
[22, 'color', true, true], // 22 - MyComponent: ɵɵstyleProp('color', '#004'});
[24, null, true, true], // 24 - Style1Directive: ɵɵstyleMap({color: '#003'});
[26, 'color', true, true], // 26 - Style1Directive: ɵɵstyleProp('color', '#006'});
[28, null, true, true], // 28 - Style2Directive: ɵɵstyleMap({color: '#007'});
[10, null, true, true], // 10 - Template: ɵɵstyleMap({color: '#001'});
[12, 'color', true, false], // 12 - Template: ɵɵstyleProp('color', '#002'});
]);
insertTStylingBinding(tData, tNode, 'color', 30, true, false);
expectRange(tNode.styleBindings).toEqual([10, 12]);
expectTData(tData).toEqual([
...empty_0_through_9, // 00-09
null,
[false, 30, false, 12], // 10 - Template: ɵɵstyleMap({color: '#001'});
'color',
[false, 10, false, 0], // 12 - Template: ɵɵstyleProp('color', '#002'});
...empty_14_through_19, // 14-19
null,
[false, 0, false, 22], // 20 - MyComponent: ɵɵstyleMap({color: '#003'});
'color',
[false, 20, false, 24], // 22 - MyComponent: ɵɵstyleProp('color', '#004'});
null,
[false, 22, false, 26], // 24 - Style1Directive: ɵɵstyleMap({color: '#005'});
'color',
[false, 24, false, 28], // 26 - Style1Directive: ɵɵstyleProp('color', '#006'});
null,
[false, 26, false, 30], // 28 - Style2Directive: ɵɵstyleMap({color: '#007'});
'color',
[false, 28, false, 10], // 30 - Style2Directive: ɵɵstyleProp('color', '#008'});
]);
expectPriorityOrder(tData, tNode, false).toEqual([
[20, null, false, true], // 20 - MyComponent: ɵɵstyleMap({color: '#003'});
[22, 'color', true, true], // 22 - MyComponent: ɵɵstyleProp('color', '#004'});
[24, null, true, true], // 24 - Style1Directive: ɵɵstyleMap({color: '#005'});
[26, 'color', true, true], // 26 - Style1Directive: ɵɵstyleProp('color', '#006'});
[28, null, true, true], // 28 - Style2Directive: ɵɵstyleMap({color: '#007'});
[30, 'color', true, true], // 30 - Style2Directive: ɵɵstyleProp('color', '#008'});
[10, null, true, true], // 10 - Template: ɵɵstyleMap({color: '#001'});
[12, 'color', true, false], // 12 - Template: ɵɵstyleProp('color', '#002'});
]);
});
});
describe('markDuplicates', () => {
it("should not mark items as duplicate if names don't match", () => {
const tNode = createTNode(null!, null!, T | {
"end_byte": 15343,
"start_byte": 10411,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/styling_next/style_binding_list_spec.ts"
} |
angular/packages/core/test/render3/styling_next/style_binding_list_spec.ts_15347_22055 | Type.Element, 0, '', null);
const tData: TData = [null, null];
insertTStylingBinding(tData, tNode, 'color', 2, false, false);
expectPriorityOrder(tData, tNode, false).toEqual([
// PREV, NEXT
[2, 'color', false, false],
]);
insertTStylingBinding(tData, tNode, 'width', 4, false, false);
expectPriorityOrder(tData, tNode, false).toEqual([
// PREV, NEXT
[2, 'color', false, false],
[4, 'width', false, false],
]);
insertTStylingBinding(tData, tNode, 'height', 6, true, false);
expectPriorityOrder(tData, tNode, false).toEqual([
// PREV, NEXT
[6, 'height', false, false],
[2, 'color', false, false],
[4, 'width', false, false],
]);
});
it('should mark items as duplicate if names match', () => {
const tNode = createTNode(null!, null!, TNodeType.Element, 0, '', null);
const tData: TData = [null, null];
insertTStylingBinding(tData, tNode, 'color', 2, false, false);
expectPriorityOrder(tData, tNode, false).toEqual([
// PREV, NEXT
[2, 'color', false, false],
]);
insertTStylingBinding(tData, tNode, 'color', 4, false, false);
expectPriorityOrder(tData, tNode, false).toEqual([
// PREV, NEXT
[2, 'color', false, true],
[4, 'color', true, false],
]);
insertTStylingBinding(tData, tNode, 'height', 6, true, false);
expectPriorityOrder(tData, tNode, false).toEqual([
// PREV, NEXT
[6, 'height', false, false],
[2, 'color', false, true],
[4, 'color', true, false],
]);
});
it('should treat maps as matching all', () => {
const tNode = createTNode(null!, null!, TNodeType.Element, 0, '', null);
const tData: TData = [null, null];
insertTStylingBinding(tData, tNode, 'color', 2, false, false);
insertTStylingBinding(tData, tNode, 'height', 4, true, false);
expectPriorityOrder(tData, tNode, false).toEqual([
// PREV, NEXT
[4, 'height', false, false],
[2, 'color', false, false],
]);
insertTStylingBinding(tData, tNode, null /*Map*/, 6, true, false);
expectPriorityOrder(tData, tNode, false).toEqual([
// PREV, NEXT
[4, 'height', false, true],
[6, null, true, true],
[2, 'color', true, false],
]);
});
it('should mark all things after map as duplicate', () => {
const tNode = createTNode(null!, null!, TNodeType.Element, 0, '', null);
const tData: TData = [null, null];
insertTStylingBinding(tData, tNode, null, 2, false, false);
insertTStylingBinding(tData, tNode, 'height', 4, false, false);
insertTStylingBinding(tData, tNode, 'color', 6, true, false);
expectPriorityOrder(tData, tNode, false).toEqual([
// PREV, NEXT
[6, 'color', false, true],
[2, null, true, true],
[4, 'height', true, false],
]);
});
it('should mark duplicate on complex objects like width.px', () => {
const tNode = createTNode(null!, null!, TNodeType.Element, 0, '', null);
const tData: TData = [null, null];
insertTStylingBinding(tData, tNode, 'width', 2, false, false);
insertTStylingBinding(tData, tNode, 'height', 4, false, false);
expectPriorityOrder(tData, tNode, false).toEqual([
// PREV, NEXT
[2, 'width', false, false],
[4, 'height', false, false],
]);
insertTStylingBinding(tData, tNode, 'height', 6, false, false);
expectPriorityOrder(tData, tNode, false).toEqual([
// PREV, NEXT
[2, 'width', false, false],
[4, 'height', false, true],
[6, 'height', true, false],
]);
insertTStylingBinding(tData, tNode, 'width', 8, false, false);
expectPriorityOrder(tData, tNode, false).toEqual([
// PREV, NEXT
[2, 'width', false, true],
[4, 'height', false, true],
[6, 'height', true, false],
[8, 'width', true, false],
]);
});
it('should mark duplicate on static fields', () => {
const tNode = createTNode(null!, null!, TNodeType.Element, 0, '', null);
tNode.residualStyles = ['color', 'blue'] as any;
const tData: TData = [null, null];
insertTStylingBinding(tData, tNode, 'width', 2, false, false);
expectPriorityOrder(tData, tNode, false).toEqual([
// PREV, NEXT
[2, 'width', false, false],
]);
insertTStylingBinding(tData, tNode, 'color', 4, false, false);
expectPriorityOrder(tData, tNode, false).toEqual([
// PREV, NEXT
[2, 'width', false, false],
[4, 'color', false, true],
]);
insertTStylingBinding(tData, tNode, null, 6, false, false);
expectPriorityOrder(tData, tNode, false).toEqual([
// PREV, NEXT
[2, 'width', false, true],
[4, 'color', false, true],
[6, null, true, false],
]);
});
});
});
const empty_0_through_9 = [null, null, null, null, null, null, null, null, null, null];
const empty_14_through_19 = [null, null, null, null, null, null];
function expectRange(tStylingRange: TStylingRange) {
return expect([
getTStylingRangePrev(tStylingRange), //
getTStylingRangeNext(tStylingRange), //
]);
}
function expectTData(tData: TData) {
return expect(
tData.map((tStylingRange: any) => {
return typeof tStylingRange === 'number'
? [
false,
getTStylingRangePrev(tStylingRange as any), //
false,
getTStylingRangeNext(tStylingRange as any), //
]
: tStylingRange;
}),
);
}
function expectPriorityOrder(tData: TData, tNode: TNode, isClassBinding: boolean) {
// first find head.
let index = getStylingBindingHead(tData, tNode, isClassBinding);
const indexes: [number, string | null, boolean, boolean][] = [];
while (index !== 0) {
let key = tData[index] as TStylingKey | null;
const tStylingRange = tData[index + 1] as TStylingRange;
indexes.push([
index, //
key as string, //
getTStylingRangePrevDuplicate(tStylingRange), //
getTStylingRangeNextDuplicate(tStylingRange), //
]);
index = getTStylingRangeNext(tStylingRange);
}
return expect(indexes);
}
/**
* Find the head of the styling binding linked list.
*/
export function getStylingBindingHead(tData: TData, tNode: TNode, isClassBinding: boolean): number {
let index = getTStylingRangePrev(isClassBinding ? tNode. | {
"end_byte": 22055,
"start_byte": 15347,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/styling_next/style_binding_list_spec.ts"
} |
angular/packages/core/test/render3/styling_next/style_binding_list_spec.ts_22056_22497 | lassBindings : tNode.styleBindings);
while (true) {
const tStylingRange = tData[index + 1] as TStylingRange;
const prev = getTStylingRangePrev(tStylingRange);
if (prev === 0) {
// found head exit.
return index;
} else {
index = prev;
}
}
}
| {
"end_byte": 22497,
"start_byte": 22056,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/styling_next/style_binding_list_spec.ts"
} |
angular/packages/core/test/render3/styling_next/static_styling_spec.ts_0_1941 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {createTNode} from '@angular/core/src/render3/instructions/shared';
import {AttributeMarker} from '@angular/core/src/render3/interfaces/attribute_marker';
import {TAttributes, TNode, TNodeType} from '@angular/core/src/render3/interfaces/node';
import {LView} from '@angular/core/src/render3/interfaces/view';
import {enterView} from '@angular/core/src/render3/state';
import {computeStaticStyling} from '@angular/core/src/render3/styling/static_styling';
describe('static styling', () => {
const mockFirstCreatePassLView: LView = [null, {firstCreatePass: true}] as any;
let tNode!: TNode;
beforeEach(() => {
enterView(mockFirstCreatePassLView);
tNode = createTNode(null!, null!, TNodeType.Element, 0, '', null);
});
it('should initialize when no attrs', () => {
computeStaticStyling(tNode, [], true);
expect(tNode.classes).toEqual(null);
expect(tNode.styles).toEqual(null);
});
it('should initialize from attrs', () => {
const tAttrs: TAttributes = [
'ignore', //
AttributeMarker.Classes,
'my-class', //
AttributeMarker.Styles,
'color',
'red', //
];
computeStaticStyling(tNode, tAttrs, true);
expect(tNode.classes).toEqual('my-class');
expect(tNode.styles).toEqual('color: red;');
});
it('should initialize from attrs when multiple', () => {
const tAttrs: TAttributes = [
'ignore', //
AttributeMarker.Classes,
'my-class',
'other', //
AttributeMarker.Styles,
'color',
'red',
'width',
'100px', //
];
computeStaticStyling(tNode, tAttrs, true);
expect(tNode.classes).toEqual('my-class other');
expect(tNode.styles).toEqual('color: red; width: 100px;');
});
});
| {
"end_byte": 1941,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/styling_next/static_styling_spec.ts"
} |
angular/packages/core/test/render3/styling_next/class_differ_spec.ts_0_976 | /**
* @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 {classIndexOf} from '../../../src/render3/styling/class_differ';
describe('class differ', () => {
describe('classIndexOf', () => {
it('should match simple case', () => {
expect(classIndexOf('A', 'A', 0)).toEqual(0);
expect(classIndexOf('AA', 'A', 0)).toEqual(-1);
expect(classIndexOf('_A_', 'A', 0)).toEqual(-1);
expect(classIndexOf('_ A_', 'A', 0)).toEqual(-1);
expect(classIndexOf('_ A _', 'A', 0)).toEqual(2);
});
it('should not match on partial matches', () => {
expect(classIndexOf('ABC AB', 'AB', 0)).toEqual(4);
expect(classIndexOf('AB ABC', 'AB', 1)).toEqual(-1);
expect(classIndexOf('ABC BC', 'BC', 0)).toEqual(4);
expect(classIndexOf('BC ABC', 'BB', 1)).toEqual(-1);
});
});
});
| {
"end_byte": 976,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/styling_next/class_differ_spec.ts"
} |
angular/packages/core/test/render3/i18n/i18n_spec.ts_0_991 | /**
* @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 {ɵɵi18nAttributes, ɵɵi18nPostprocess, ɵɵi18nStart} from '@angular/core';
import {ɵɵi18n} from '@angular/core/src/core';
import {
getTranslationForTemplate,
i18nStartFirstCreatePass,
} from '@angular/core/src/render3/i18n/i18n_parse';
import {getTIcu} from '@angular/core/src/render3/i18n/i18n_util';
import {TNodeType} from '@angular/core/src/render3/interfaces/node';
import {ɵɵelementEnd, ɵɵelementStart} from '../../../src/render3/instructions/all';
import {
I18nCreateOpCode,
I18nUpdateOpCodes,
TI18n,
TIcu,
} from '../../../src/render3/interfaces/i18n';
import {HEADER_OFFSET, TView} from '../../../src/render3/interfaces/view';
import {matchTNode} from '../matchers';
import {matchDebug} from '../utils';
import {ViewFixture} from '../view_fixture';
describe(' | {
"end_byte": 991,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/i18n/i18n_spec.ts"
} |
angular/packages/core/test/render3/i18n/i18n_spec.ts_993_7864 | ntime i18n', () => {
describe('getTranslationForTemplate', () => {
it('should crop messages for the selected template', () => {
let message = `simple text`;
expect(getTranslationForTemplate(message, -1)).toEqual(message);
message = `Hello �0�!`;
expect(getTranslationForTemplate(message, -1)).toEqual(message);
message = `Hello �#2��0��/#2�!`;
expect(getTranslationForTemplate(message, -1)).toEqual(message);
// Embedded sub-templates
message = `�0� is rendered as: �*2:1�before�*1:2�middle�/*1:2�after�/*2:1�!`;
expect(getTranslationForTemplate(message, -1)).toEqual('�0� is rendered as: �*2:1��/*2:1�!');
expect(getTranslationForTemplate(message, 1)).toEqual('before�*1:2��/*1:2�after');
expect(getTranslationForTemplate(message, 2)).toEqual('middle');
// Embedded & sibling sub-templates
message = `�0� is rendered as: �*2:1�before�*1:2�middle�/*1:2�after�/*2:1� and also �*4:3�before�*1:4�middle�/*1:4�after�/*4:3�!`;
expect(getTranslationForTemplate(message, -1)).toEqual(
'�0� is rendered as: �*2:1��/*2:1� and also �*4:3��/*4:3�!',
);
expect(getTranslationForTemplate(message, 1)).toEqual('before�*1:2��/*1:2�after');
expect(getTranslationForTemplate(message, 2)).toEqual('middle');
expect(getTranslationForTemplate(message, 3)).toEqual('before�*1:4��/*1:4�after');
expect(getTranslationForTemplate(message, 4)).toEqual('middle');
});
it('should throw if the template is malformed', () => {
const message = `�*2:1�message!`;
expect(() => getTranslationForTemplate(message, -1)).toThrowError(/Tag mismatch/);
});
});
let tView: TView;
function getOpCodes(
messageOrAtrs: string | string[],
createTemplate: () => void,
decls: number,
index: number,
): TI18n | I18nUpdateOpCodes {
const fixture = new ViewFixture({decls, consts: [messageOrAtrs]});
fixture.enterView();
createTemplate();
// Make `tView` available for tests.
tView = fixture.tView;
const opCodes = fixture.tView.data[index] as TI18n | I18nUpdateOpCodes;
ViewFixture.cleanUp();
return opCodes;
}
describe('i18nStart', () => {
it('for text', () => {
const message = 'simple text';
const nbConsts = 1;
const index = 1;
const opCodes = getOpCodes(
message,
() => {
ɵɵelementStart(0, 'div');
ɵɵi18nStart(index, 0);
ɵɵelementEnd();
},
nbConsts,
HEADER_OFFSET + index,
) as TI18n;
expect(opCodes).toEqual({
create: matchDebug([
`lView[${HEADER_OFFSET + 1}] = document.createText("simple text");`,
`parent.appendChild(lView[${HEADER_OFFSET + 1}]);`,
]),
update: [] as unknown as I18nUpdateOpCodes,
ast: [{kind: 0, index: HEADER_OFFSET + 1}],
parentTNodeIndex: HEADER_OFFSET,
});
});
it('for elements', () => {
const message = `Hello �#2�world�/#2� and �#3�universe�/#3�!`;
// Template: `<div>Hello <div>world</div> and <span>universe</span>!`
// 3 consts for the 2 divs and 1 span + 1 const for `i18nStart` = 4 consts
const nbConsts = 4;
const index = 1;
const opCodes = getOpCodes(
message,
() => {
ɵɵelementStart(0, 'div');
ɵɵi18nStart(index, 0);
ɵɵelementEnd();
},
nbConsts,
HEADER_OFFSET + index,
);
expect(opCodes).toEqual({
create: matchDebug([
`lView[${HEADER_OFFSET + 4}] = document.createText("Hello ");`,
`parent.appendChild(lView[${HEADER_OFFSET + 4}]);`,
`lView[${HEADER_OFFSET + 5}] = document.createText("world");`,
`lView[${HEADER_OFFSET + 6}] = document.createText(" and ");`,
`parent.appendChild(lView[${HEADER_OFFSET + 6}]);`,
`lView[${HEADER_OFFSET + 7}] = document.createText("universe");`,
`lView[${HEADER_OFFSET + 8}] = document.createText("!");`,
`parent.appendChild(lView[${HEADER_OFFSET + 8}]);`,
]),
update: [] as unknown as I18nUpdateOpCodes,
ast: [
{kind: 0, index: HEADER_OFFSET + 4},
{
kind: 2,
index: HEADER_OFFSET + 2,
children: [{kind: 0, index: HEADER_OFFSET + 5}],
type: 0,
},
{kind: 0, index: HEADER_OFFSET + 6},
{
kind: 2,
index: HEADER_OFFSET + 3,
children: [{kind: 0, index: HEADER_OFFSET + 7}],
type: 0,
},
{kind: 0, index: HEADER_OFFSET + 8},
],
parentTNodeIndex: HEADER_OFFSET,
});
});
it('for simple bindings', () => {
const message = `Hello �0�!`;
const nbConsts = 2;
const index = 1;
const opCodes = getOpCodes(
message,
() => {
ɵɵelementStart(0, 'div');
ɵɵi18nStart(index, 0);
ɵɵelementEnd();
},
nbConsts,
HEADER_OFFSET + index,
);
expect((opCodes as any).update.debug).toEqual([
`if (mask & 0b1) { (lView[${
HEADER_OFFSET + 2
}] as Text).textContent = \`Hello \${lView[i-1]}!\`; }`,
]);
expect(opCodes).toEqual({
create: matchDebug([
`lView[${HEADER_OFFSET + 2}] = document.createText("");`,
`parent.appendChild(lView[${HEADER_OFFSET + 2}]);`,
]),
update: matchDebug([
`if (mask & 0b1) { (lView[${
HEADER_OFFSET + 2
}] as Text).textContent = \`Hello \${lView[i-1]}!\`; }`,
]),
ast: [{kind: 0, index: HEADER_OFFSET + 2}],
parentTNodeIndex: HEADER_OFFSET,
});
});
it('for multiple bindings', () => {
const message = `Hello �0� and �1�, again �0�!`;
const nbConsts = 2;
const index = 1;
const opCodes = getOpCodes(
message,
() => {
ɵɵelementStart(0, 'div');
ɵɵi18nStart(index, 0);
ɵɵelementEnd();
},
nbConsts,
HEADER_OFFSET + index,
);
expect(opCodes).toEqual({
create: matchDebug([
`lView[${HEADER_OFFSET + 2}] = document.createText("");`,
`parent.appendChild(lView[${HEADER_OFFSET + 2}]);`,
]),
update: matchDebug([
`if (mask & 0b11) { (lView[${
HEADER_OFFSET + 2
}] as Text).textContent = \`Hello \${lView[i-1]} and \${lView[i-2]}, again \${lView[i-1]}!\`; }`,
]),
ast: [{kind: 0, index: HEADER_OFFSET + 2}],
parentTNodeIndex: HEADER_OFFSET,
});
});
it('for sub-templates', () => {
// Template:
// <div>
// {{value}} is rendered as:
// <span *ngIf>
// before <b *ngIf>middle</b> after
// </span>
| {
"end_byte": 7864,
"start_byte": 993,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/i18n/i18n_spec.ts"
} |
angular/packages/core/test/render3/i18n/i18n_spec.ts_7870_11122 | !
// </div>
const message = `�0� is rendered as: �*2:1��#1:1�before�*2:2��#1:2�middle�/#1:2��/*2:2�after�/#1:1��/*2:1�!`;
/**** Root template ****/
// �0� is rendered as: �*2:1��/*2:1�!
let nbConsts = 3;
let index = 1;
let opCodes = getOpCodes(
message,
() => {
ɵɵelementStart(0, 'div');
ɵɵi18nStart(index, 0);
ɵɵelementEnd();
},
nbConsts,
HEADER_OFFSET + index,
);
expect(opCodes).toEqual({
create: matchDebug([
`lView[${HEADER_OFFSET + 3}] = document.createText("");`,
`parent.appendChild(lView[${HEADER_OFFSET + 3}]);`,
`lView[${HEADER_OFFSET + 4}] = document.createText("!");`,
`parent.appendChild(lView[${HEADER_OFFSET + 4}]);`,
]),
update: matchDebug([
`if (mask & 0b1) { (lView[${
HEADER_OFFSET + 3
}] as Text).textContent = \`\${lView[i-1]} is rendered as: \`; }`,
]),
ast: [
{kind: 0, index: HEADER_OFFSET + 3},
{kind: 2, index: HEADER_OFFSET + 2, children: [], type: 1},
{kind: 0, index: HEADER_OFFSET + 4},
],
parentTNodeIndex: HEADER_OFFSET,
});
/**** First sub-template ****/
// �#1:1�before�*2:2�middle�/*2:2�after�/#1:1�
nbConsts = 3;
index = 1;
opCodes = getOpCodes(
message,
() => {
ɵɵelementStart(0, 'div');
ɵɵi18nStart(index, 0, 1);
},
nbConsts,
index + HEADER_OFFSET,
);
expect(opCodes).toEqual({
create: matchDebug([
`lView[${HEADER_OFFSET + 3}] = document.createText("before");`,
`lView[${HEADER_OFFSET + 4}] = document.createText("after");`,
]),
update: [] as unknown as I18nUpdateOpCodes,
ast: [
{
kind: 2,
index: HEADER_OFFSET + 1,
children: [
{kind: 0, index: HEADER_OFFSET + 3},
{kind: 2, index: HEADER_OFFSET + 2, children: [], type: 1},
{kind: 0, index: HEADER_OFFSET + 4},
],
type: 0,
},
],
parentTNodeIndex: HEADER_OFFSET,
});
/**** Second sub-template ****/
// middle
nbConsts = 2;
index = 1;
opCodes = getOpCodes(
message,
() => {
ɵɵelementStart(0, 'div');
ɵɵi18nStart(index, 0, 2);
},
nbConsts,
index + HEADER_OFFSET,
);
expect(opCodes).toEqual({
create: matchDebug([`lView[${HEADER_OFFSET + 2}] = document.createText("middle");`]),
update: [] as unknown as I18nUpdateOpCodes,
ast: [
{
kind: 2,
index: HEADER_OFFSET + 1,
children: [{kind: 0, index: HEADER_OFFSET + 2}],
type: 0,
},
],
parentTNodeIndex: HEADER_OFFSET,
});
});
it('for ICU expressions', () => {
const message = `{�0�, plural,
=0 {no <b title="none">emails</b>!}
=1 {one <i>email</i>}
other {�0� <span title="�1�">emails</span>}
}`;
const nbConsts = 2;
const index = 1;
const opCo | {
"end_byte": 11122,
"start_byte": 7870,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/i18n/i18n_spec.ts"
} |
angular/packages/core/test/render3/i18n/i18n_spec.ts_11128_16255 | getOpCodes(
message,
() => {
ɵɵelementStart(0, 'div');
ɵɵi18nStart(index, 0);
ɵɵelementEnd();
},
nbConsts,
HEADER_OFFSET + index,
) as TI18n;
expect(opCodes).toEqual({
create: matchDebug([
`lView[${HEADER_OFFSET + 2}] = document.createComment("ICU ${HEADER_OFFSET + 1}:0");`,
`parent.appendChild(lView[${HEADER_OFFSET + 2}]);`,
]),
update: matchDebug([
`if (mask & 0b1) { icuSwitchCase(${HEADER_OFFSET + 2}, \`\${lView[i-1]}\`); }`,
`if (mask & 0b1) { icuUpdateCase(${HEADER_OFFSET + 2}); }`,
]),
ast: [
{
kind: 3,
index: HEADER_OFFSET + 2,
cases: [
[
{kind: 0, index: HEADER_OFFSET + 4},
{
kind: 1,
index: HEADER_OFFSET + 5,
children: [{kind: 0, index: HEADER_OFFSET + 6}],
},
{kind: 0, index: HEADER_OFFSET + 7},
],
[
{kind: 0, index: HEADER_OFFSET + 8},
{
kind: 1,
index: HEADER_OFFSET + 9,
children: [{kind: 0, index: HEADER_OFFSET + 10}],
},
],
[
{kind: 0, index: HEADER_OFFSET + 11},
{
kind: 1,
index: HEADER_OFFSET + 12,
children: [{kind: 0, index: HEADER_OFFSET + 13}],
},
],
],
currentCaseLViewIndex: HEADER_OFFSET + 3,
},
],
parentTNodeIndex: HEADER_OFFSET,
});
expect(getTIcu(tView, HEADER_OFFSET + 2)).toEqual(<TIcu>{
type: 1,
currentCaseLViewIndex: HEADER_OFFSET + 3,
anchorIdx: HEADER_OFFSET + 2,
cases: ['0', '1', 'other'],
create: [
matchDebug([
`lView[${HEADER_OFFSET + 4}] = document.createTextNode("no ")`,
`(lView[${HEADER_OFFSET + 0}] as Element).appendChild(lView[${HEADER_OFFSET + 4}])`,
`lView[${HEADER_OFFSET + 5}] = document.createElement("b")`,
`(lView[${HEADER_OFFSET + 0}] as Element).appendChild(lView[${HEADER_OFFSET + 5}])`,
`(lView[${HEADER_OFFSET + 5}] as Element).setAttribute("title", "none")`,
`lView[${HEADER_OFFSET + 6}] = document.createTextNode("emails")`,
`(lView[${HEADER_OFFSET + 5}] as Element).appendChild(lView[${HEADER_OFFSET + 6}])`,
`lView[${HEADER_OFFSET + 7}] = document.createTextNode("!")`,
`(lView[${HEADER_OFFSET + 0}] as Element).appendChild(lView[${HEADER_OFFSET + 7}])`,
]),
matchDebug([
`lView[${HEADER_OFFSET + 8}] = document.createTextNode("one ")`,
`(lView[${HEADER_OFFSET + 0}] as Element).appendChild(lView[${HEADER_OFFSET + 8}])`,
`lView[${HEADER_OFFSET + 9}] = document.createElement("i")`,
`(lView[${HEADER_OFFSET + 0}] as Element).appendChild(lView[${HEADER_OFFSET + 9}])`,
`lView[${HEADER_OFFSET + 10}] = document.createTextNode("email")`,
`(lView[${HEADER_OFFSET + 9}] as Element).appendChild(lView[${HEADER_OFFSET + 10}])`,
]),
matchDebug([
`lView[${HEADER_OFFSET + 11}] = document.createTextNode("")`,
`(lView[${HEADER_OFFSET + 0}] as Element).appendChild(lView[${HEADER_OFFSET + 11}])`,
`lView[${HEADER_OFFSET + 12}] = document.createElement("span")`,
`(lView[${HEADER_OFFSET + 0}] as Element).appendChild(lView[${HEADER_OFFSET + 12}])`,
`lView[${HEADER_OFFSET + 13}] = document.createTextNode("emails")`,
`(lView[${HEADER_OFFSET + 12}] as Element).appendChild(lView[${HEADER_OFFSET + 13}])`,
]),
],
remove: [
matchDebug([
`remove(lView[${HEADER_OFFSET + 4}])`,
`remove(lView[${HEADER_OFFSET + 5}])`,
`remove(lView[${HEADER_OFFSET + 7}])`,
]),
matchDebug([
`remove(lView[${HEADER_OFFSET + 8}])`,
`remove(lView[${HEADER_OFFSET + 9}])`,
]),
matchDebug([
`remove(lView[${HEADER_OFFSET + 11}])`,
`remove(lView[${HEADER_OFFSET + 12}])`,
]),
],
update: [
matchDebug([]),
matchDebug([]),
matchDebug([
`if (mask & 0b1) { (lView[${
HEADER_OFFSET + 11
}] as Text).textContent = \`\${lView[i-1]} \`; }`,
`if (mask & 0b10) { (lView[${
HEADER_OFFSET + 12
}] as Element).setAttribute('title', \`\${lView[i-2]}\`); }`,
]),
],
});
});
it('for nested ICU expressions', () => {
const message = `{�0�, plural,
=0 {zero}
other {�0� {�1�, select,
cat {cats}
dog {dogs}
other {animals}
}!}
}`;
const nbConst | {
"end_byte": 16255,
"start_byte": 11128,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/i18n/i18n_spec.ts"
} |
angular/packages/core/test/render3/i18n/i18n_spec.ts_16261_23218 |
const index = 1;
const opCodes = getOpCodes(
message,
() => {
ɵɵelementStart(0, 'div');
ɵɵi18n(index, 0);
ɵɵelementEnd();
},
nbConsts,
HEADER_OFFSET + index,
);
expect(opCodes).toEqual({
create: matchDebug([
`lView[${HEADER_OFFSET + 2}] = document.createComment("ICU ${HEADER_OFFSET + 1}:0");`,
`parent.appendChild(lView[${HEADER_OFFSET + 2}]);`,
]),
update: matchDebug([
`if (mask & 0b1) { icuSwitchCase(${HEADER_OFFSET + 2}, \`\${lView[i-1]}\`); }`,
`if (mask & 0b10) { icuSwitchCase(${HEADER_OFFSET + 6}, \`\${lView[i-2]}\`); }`,
`if (mask & 0b1) { icuUpdateCase(${HEADER_OFFSET + 2}); }`,
]),
ast: [
{
kind: 3,
index: HEADER_OFFSET + 2,
cases: [
[{kind: 0, index: HEADER_OFFSET + 4}],
[
{kind: 0, index: HEADER_OFFSET + 5},
{
kind: 3,
index: HEADER_OFFSET + 6,
cases: [
[{kind: 0, index: HEADER_OFFSET + 8}],
[{kind: 0, index: HEADER_OFFSET + 9}],
[{kind: 0, index: HEADER_OFFSET + 10}],
],
currentCaseLViewIndex: HEADER_OFFSET + 7,
},
{kind: 0, index: HEADER_OFFSET + 11},
],
],
currentCaseLViewIndex: HEADER_OFFSET + 3,
},
],
parentTNodeIndex: HEADER_OFFSET,
});
expect(getTIcu(tView, HEADER_OFFSET + 2)).toEqual({
type: 1,
anchorIdx: HEADER_OFFSET + 2,
currentCaseLViewIndex: HEADER_OFFSET + 3,
cases: ['0', 'other'],
create: [
matchDebug([
`lView[${HEADER_OFFSET + 4}] = document.createTextNode("zero")`,
`(lView[${HEADER_OFFSET + 0}] as Element).appendChild(lView[${HEADER_OFFSET + 4}])`,
]),
matchDebug([
`lView[${HEADER_OFFSET + 5}] = document.createTextNode("")`,
`(lView[${HEADER_OFFSET + 0}] as Element).appendChild(lView[${HEADER_OFFSET + 5}])`,
`lView[${HEADER_OFFSET + 6}] = document.createComment("nested ICU 0")`,
`(lView[${HEADER_OFFSET + 0}] as Element).appendChild(lView[${HEADER_OFFSET + 6}])`,
`lView[${HEADER_OFFSET + 11}] = document.createTextNode("!")`,
`(lView[${HEADER_OFFSET + 0}] as Element).appendChild(lView[${HEADER_OFFSET + 11}])`,
]),
],
update: [
matchDebug([]),
matchDebug([
`if (mask & 0b1) { (lView[${
HEADER_OFFSET + 5
}] as Text).textContent = \`\${lView[i-1]} \`; }`,
]),
],
remove: [
matchDebug([`remove(lView[${HEADER_OFFSET + 4}])`]),
matchDebug([
`remove(lView[${HEADER_OFFSET + 5}])`,
`removeNestedICU(${HEADER_OFFSET + 6})`,
`remove(lView[${HEADER_OFFSET + 6}])`,
`remove(lView[${HEADER_OFFSET + 11}])`,
]),
],
});
expect(tView.data[HEADER_OFFSET + 6]).toEqual({
type: 0,
anchorIdx: HEADER_OFFSET + 6,
currentCaseLViewIndex: HEADER_OFFSET + 7,
cases: ['cat', 'dog', 'other'],
create: [
matchDebug([
`lView[${HEADER_OFFSET + 8}] = document.createTextNode("cats")`,
`(lView[${HEADER_OFFSET + 0}] as Element).appendChild(lView[${HEADER_OFFSET + 8}])`,
]),
matchDebug([
`lView[${HEADER_OFFSET + 9}] = document.createTextNode("dogs")`,
`(lView[${HEADER_OFFSET + 0}] as Element).appendChild(lView[${HEADER_OFFSET + 9}])`,
]),
matchDebug([
`lView[${HEADER_OFFSET + 10}] = document.createTextNode("animals")`,
`(lView[${HEADER_OFFSET + 0}] as Element).appendChild(lView[${HEADER_OFFSET + 10}])`,
]),
],
update: [matchDebug([]), matchDebug([]), matchDebug([])],
remove: [
matchDebug([`remove(lView[${HEADER_OFFSET + 8}])`]),
matchDebug([`remove(lView[${HEADER_OFFSET + 9}])`]),
matchDebug([`remove(lView[${HEADER_OFFSET + 10}])`]),
],
});
});
});
describe(`i18nAttribute`, () => {
it('for simple bindings', () => {
const message = `Hello �0�!`;
const attrs = ['title', message];
const nbConsts = 2;
const index = 1;
const opCodes = getOpCodes(
attrs,
() => {
ɵɵelementStart(0, 'div');
ɵɵi18nAttributes(index, 0);
ɵɵelementEnd();
},
nbConsts,
HEADER_OFFSET + index,
);
expect(opCodes).toEqual(
matchDebug([
`if (mask & 0b1) { (lView[${
HEADER_OFFSET + 0
}] as Element).setAttribute('title', \`Hello \$\{lView[i-1]}!\`); }`,
]),
);
});
it('for multiple bindings', () => {
const message = `Hello �0� and �1�, again �0�!`;
const attrs = ['title', message];
const nbConsts = 2;
const index = 1;
const opCodes = getOpCodes(
attrs,
() => {
ɵɵelementStart(0, 'div');
ɵɵi18nAttributes(index, 0);
ɵɵelementEnd();
},
nbConsts,
HEADER_OFFSET + index,
);
expect(opCodes).toEqual(
matchDebug([
`if (mask & 0b11) { (lView[${
HEADER_OFFSET + 0
}] as Element).setAttribute('title', \`Hello \$\{lView[i-1]} and \$\{lView[i-2]}, again \$\{lView[i-1]}!\`); }`,
]),
);
});
it('for multiple attributes', () => {
const message1 = `Hello �0� - �1�!`;
const message2 = `Bye �0� - �1�!`;
const attrs = ['title', message1, 'aria-label', message2];
const nbConsts = 4;
const index = 1;
const opCodes = getOpCodes(
attrs,
() => {
ɵɵelementStart(0, 'div');
ɵɵi18nAttributes(index, 0);
ɵɵelementEnd();
},
nbConsts,
HEADER_OFFSET + index,
);
expect(opCodes).toEqual(
matchDebug([
`if (mask & 0b11) { (lView[${HEADER_OFFSET + 0}] as Element).` +
"setAttribute('title', `Hello ${lView[i-1]} - ${lView[i-2]}!`); }",
`if (mask & 0b1100) { (lView[${HEADER_OFFSET + 0}] as Element).` +
"setAttribute('aria-label', `Bye ${lView[i-3]} - ${lView[i-4]}!`); }",
]),
);
});
});
describe('i18nPostprocess', () => {
it('should handle valid cases', () => {
const arr = ['�*1:1��#2:1�', '�#4:1�', '�6:1�', '�/#2:1��/*1:1�'];
const str = `[${arr.join('|')}]`;
const cases = [
// empty string
['', {}, ''],
// string without any special cases
['Foo [1,2,3] Bar - no ICU here', {}, 'Foo [1 | {
"end_byte": 23218,
"start_byte": 16261,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/i18n/i18n_spec.ts"
} |
angular/packages/core/test/render3/i18n/i18n_spec.ts_23222_28771 | ] Bar - no ICU here'],
// multi-value cases
[
`Start: ${str}, ${str} and ${str}, ${str} end.`,
{},
`Start: ${arr[0]}, ${arr[1]} and ${arr[2]}, ${arr[3]} end.`,
],
// replace VAR_SELECT
[
'My ICU: {VAR_SELECT, select, =1 {one} other {other}}',
{VAR_SELECT: '�1:2�'},
'My ICU: {�1:2�, select, =1 {one} other {other}}',
],
[
'My ICU: {\n\n\tVAR_SELECT_1 \n\n, select, =1 {one} other {other}}',
{VAR_SELECT_1: '�1:2�'},
'My ICU: {\n\n\t�1:2� \n\n, select, =1 {one} other {other}}',
],
// replace VAR_PLURAL
[
'My ICU: {VAR_PLURAL, plural, one {1} other {other}}',
{VAR_PLURAL: '�1:2�'},
'My ICU: {�1:2�, plural, one {1} other {other}}',
],
[
'My ICU: {\n\n\tVAR_PLURAL_1 \n\n, select, =1 {one} other {other}}',
{VAR_PLURAL_1: '�1:2�'},
'My ICU: {\n\n\t�1:2� \n\n, select, =1 {one} other {other}}',
],
// do not replace VAR_* anywhere else in a string (only in ICU)
[
'My ICU: {VAR_PLURAL, plural, one {1} other {other}} VAR_PLURAL and VAR_SELECT',
{VAR_PLURAL: '�1:2�'},
'My ICU: {�1:2�, plural, one {1} other {other}} VAR_PLURAL and VAR_SELECT',
],
// replace VAR_*'s in nested ICUs
[
'My ICU: {VAR_PLURAL, plural, one {1 - {VAR_SELECT, age, 50 {fifty} other {other}}} other {other}}',
{VAR_PLURAL: '�1:2�', VAR_SELECT: '�5�'},
'My ICU: {�1:2�, plural, one {1 - {�5�, age, 50 {fifty} other {other}}} other {other}}',
],
[
'My ICU: {VAR_PLURAL, plural, one {1 - {VAR_PLURAL_1, age, 50 {fifty} other {other}}} other {other}}',
{VAR_PLURAL: '�1:2�', VAR_PLURAL_1: '�5�'},
'My ICU: {�1:2�, plural, one {1 - {�5�, age, 50 {fifty} other {other}}} other {other}}',
],
// ICU replacement
[
'My ICU #1: �I18N_EXP_ICU�, My ICU #2: �I18N_EXP_ICU�',
{ICU: ['ICU_VALUE_1', 'ICU_VALUE_2']},
'My ICU #1: ICU_VALUE_1, My ICU #2: ICU_VALUE_2',
],
// mixed case
[
`Start: ${str}, ${str}. ICU: {VAR_SELECT, count, 10 {ten} other {other}}.
Another ICU: �I18N_EXP_ICU� and ${str}, ${str} and one more ICU: �I18N_EXP_ICU� and end.`,
{VAR_SELECT: '�1:2�', ICU: ['ICU_VALUE_1', 'ICU_VALUE_2']},
`Start: ${arr[0]}, ${arr[1]}. ICU: {�1:2�, count, 10 {ten} other {other}}.
Another ICU: ICU_VALUE_1 and ${arr[2]}, ${arr[3]} and one more ICU: ICU_VALUE_2 and end.`,
],
];
cases.forEach(([input, replacements, output]) => {
expect(ɵɵi18nPostprocess(input as string, replacements as any)).toEqual(output as string);
});
});
it('should handle nested template represented by multi-value placeholders', () => {
/**
* <div i18n>
* <span>
* Hello - 1
* </span>
* <span *ngIf="visible">
* Hello - 2
* <span *ngIf="visible">
* Hello - 3
* <span *ngIf="visible">
* Hello - 4
* </span>
* </span>
* </span>
* <span>
* Hello - 5
* </span>
* </div>
*/
const generated = `
[�#2�|�#4�] Bonjour - 1 [�/#2�|�/#1:3��/*2:3�|�/#1:2��/*2:2�|�/#1:1��/*3:1�|�/#4�]
[�*3:1��#1:1�|�*2:2��#1:2�|�*2:3��#1:3�]
Bonjour - 2
[�*3:1��#1:1�|�*2:2��#1:2�|�*2:3��#1:3�]
Bonjour - 3
[�*3:1��#1:1�|�*2:2��#1:2�|�*2:3��#1:3�] Bonjour - 4 [�/#2�|�/#1:3��/*2:3�|�/#1:2��/*2:2�|�/#1:1��/*3:1�|�/#4�]
[�/#2�|�/#1:3��/*2:3�|�/#1:2��/*2:2�|�/#1:1��/*3:1�|�/#4�]
[�/#2�|�/#1:3��/*2:3�|�/#1:2��/*2:2�|�/#1:1��/*3:1�|�/#4�]
[�#2�|�#4�] Bonjour - 5 [�/#2�|�/#1:3��/*2:3�|�/#1:2��/*2:2�|�/#1:1��/*3:1�|�/#4�]
`;
const final = `
�#2� Bonjour - 1 �/#2�
�*3:1�
�#1:1�
Bonjour - 2
�*2:2�
�#1:2�
Bonjour - 3
�*2:3�
�#1:3� Bonjour - 4 �/#1:3�
�/*2:3�
�/#1:2�
�/*2:2�
�/#1:1�
�/*3:1�
�#4� Bonjour - 5 �/#4�
`;
expect(ɵɵi18nPostprocess(generated.replace(/\s+/g, ''))).toEqual(final.replace(/\s+/g, ''));
});
it('should throw in case we have invalid string', () => {
expect(() =>
ɵɵi18nPostprocess('My ICU #1: �I18N_EXP_ICU�, My ICU #2: �I18N_EXP_ICU�', {
ICU: ['ICU_VALUE_1'],
}),
).toThrowError();
});
});
describe('i18nStartFirstCreatePass', () => {
let fixture: ViewFixture;
const DECLS = 20;
const VARS = 10;
beforeEach(() => {
fixture = new ViewFixture({decls: DECLS, vars: VARS});
fixture.enterView();
ɵɵelementStart(0, 'div');
});
afterEach(ViewFixture.cleanUp);
function i18nRangeOffset(offset: number): number {
return HEADER_OFFSET + DECLS + VARS + offset;
}
function i18nRangeOffsetOpcode(
offset: number,
{appendLater, comment}: {appendLater?: boolean; comment?: boolean} = {},
): number {
let index = i18nRangeOffset(offset) << I18nCreateOpCode.SHIFT;
if (!appendLater) {
index |= I18nCreateOpCode.APPEND_EAGERLY;
}
if (comment) {
index |= I18nCreateOpCode.COMMENT;
}
r | {
"end_byte": 28771,
"start_byte": 23222,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/i18n/i18n_spec.ts"
} |
angular/packages/core/test/render3/i18n/i18n_spec.ts_28775_34191 | n index;
}
it('should process text node with no siblings and no children', () => {
i18nStartFirstCreatePass(
fixture.tView,
0,
fixture.lView,
HEADER_OFFSET + 1,
'Hello World!',
-1,
);
const ti18n = fixture.tView.data[HEADER_OFFSET + 1] as TI18n;
// Expect that we only create the `Hello World!` text node and nothing else.
expect(ti18n.create).toEqual([
i18nRangeOffsetOpcode(0),
'Hello World!', //
]);
});
it('should process text with a child node', () => {
i18nStartFirstCreatePass(
fixture.tView,
0,
fixture.lView,
HEADER_OFFSET + 1,
'Hello �#2��/#2�!',
-1,
);
const ti18n = fixture.tView.data[HEADER_OFFSET + 1] as TI18n;
expect(ti18n.create).toEqual([
i18nRangeOffsetOpcode(0),
'Hello ', //
i18nRangeOffsetOpcode(1),
'!', //
]);
// Leave behind `Placeholder` to be picked up by `TNode` creation.
expect(fixture.tView.data[HEADER_OFFSET + 2]).toEqual(
matchTNode({
type: TNodeType.Placeholder,
// It should insert itself in front of "!"
insertBeforeIndex: i18nRangeOffset(1),
}),
);
});
it('should process text with a child node that has text', () => {
i18nStartFirstCreatePass(
fixture.tView,
0,
fixture.lView,
HEADER_OFFSET + 1,
'Hello �#2�World�/#2�!',
-1,
);
const ti18n = fixture.tView.data[HEADER_OFFSET + 1] as TI18n;
expect(ti18n.create).toEqual([
i18nRangeOffsetOpcode(0),
'Hello ', //
i18nRangeOffsetOpcode(1, {appendLater: true}),
'World', //
i18nRangeOffsetOpcode(2),
'!', //
]);
// Leave behind `Placeholder` to be picked up by `TNode` creation.
expect(fixture.tView.data[HEADER_OFFSET + 2]).toEqual(
matchTNode({
type: TNodeType.Placeholder,
insertBeforeIndex: [
i18nRangeOffset(2), // It should insert itself in front of "!"
i18nRangeOffset(1), // It should append "World"
],
}),
);
});
it('should process text with a child node that has text and with bindings', () => {
i18nStartFirstCreatePass(
fixture.tView,
0,
fixture.lView,
HEADER_OFFSET + 1,
'�0� �#2��1��/#2�!' /* {{salutation}} <b>{{name}}</b>! */,
-1,
);
const ti18n = fixture.tView.data[HEADER_OFFSET + 1] as TI18n;
expect(ti18n.create).toEqual([
i18nRangeOffsetOpcode(0),
'', // 1 is saved for binding
i18nRangeOffsetOpcode(1, {appendLater: true}),
'', // 3 is saved for binding
i18nRangeOffsetOpcode(2),
'!', //
]);
// Leave behind `insertBeforeIndex` to be picked up by `TNode` creation.
expect(fixture.tView.data[HEADER_OFFSET + 2]).toEqual(
matchTNode({
type: TNodeType.Placeholder,
insertBeforeIndex: [
i18nRangeOffset(2), // It should insert itself in front of "!"
i18nRangeOffset(1), // It should append child text node "{{name}}"
],
}),
);
expect(ti18n.update).toEqual(
matchDebug([
`if (mask & 0b1) { (lView[${
HEADER_OFFSET + 30
}] as Text).textContent = \`\${lView[i-1]} \`; }`,
`if (mask & 0b10) { (lView[${
HEADER_OFFSET + 31
}] as Text).textContent = \`\${lView[i-2]}\`; }`,
]),
);
});
it('should process text with a child template', () => {
i18nStartFirstCreatePass(
fixture.tView,
0,
fixture.lView,
HEADER_OFFSET + 1,
'Hello �*2:1�World�/*2:1�!',
-1,
);
const ti18n = fixture.tView.data[HEADER_OFFSET + 1] as TI18n;
expect(ti18n.create.debug).toEqual([
`lView[${HEADER_OFFSET + 30}] = document.createText("Hello ");`,
`parent.appendChild(lView[${HEADER_OFFSET + 30}]);`,
`lView[${HEADER_OFFSET + 31}] = document.createText("!");`,
`parent.appendChild(lView[${HEADER_OFFSET + 31}]);`,
]);
// Leave behind `Placeholder` to be picked up by `TNode` creation.
// It should insert itself in front of "!"
expect(fixture.tView.data[HEADER_OFFSET + 2]).toEqual(
matchTNode({
type: TNodeType.Placeholder,
insertBeforeIndex: HEADER_OFFSET + 31,
}),
);
});
});
});
| {
"end_byte": 34191,
"start_byte": 28775,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/i18n/i18n_spec.ts"
} |
angular/packages/core/test/render3/i18n/i18n_parse_spec.ts_0_5966 | /**
* @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 {ɵɵi18nApply, ɵɵi18nExp} from '@angular/core';
import {applyCreateOpCodes} from '@angular/core/src/render3/i18n/i18n_apply';
import {i18nStartFirstCreatePass} from '@angular/core/src/render3/i18n/i18n_parse';
import {getTIcu} from '@angular/core/src/render3/i18n/i18n_util';
import {I18nUpdateOpCodes, IcuType, TI18n} from '@angular/core/src/render3/interfaces/i18n';
import {HEADER_OFFSET, HOST} from '@angular/core/src/render3/interfaces/view';
import {matchTI18n, matchTIcu} from '../matchers';
import {matchDebug} from '../utils';
import {ViewFixture} from '../view_fixture';
describe('i18n_parse', () => {
let fixture: ViewFixture;
beforeEach(() => (fixture = new ViewFixture({decls: 1, vars: 1})));
describe('icu', () => {
it('should parse simple text', () => {
const tI18n = toT18n('some text');
expect(tI18n).toEqual(
matchTI18n({
create: matchDebug([
`lView[${HEADER_OFFSET + 2}] = document.createText("some text");`,
`parent.appendChild(lView[${HEADER_OFFSET + 2}]);`,
]),
update: [] as unknown as I18nUpdateOpCodes,
}),
);
fixture.apply(() => applyCreateOpCodes(fixture.lView, tI18n.create, fixture.host, null));
expect(fixture.host.innerHTML).toEqual('some text');
});
it('should parse simple ICU', () => {
// TData | LView
// ---------------------------+-------------------------------
// ----- DECL -----
// 21: TI18n |
// ----- VARS -----
// 22: Binding for ICU |
// ----- EXPANDO -----
// 23: null | #text(before|)
// 24: TIcu | <!-- ICU 20:0 -->
// 25: null | currently selected ICU case
// 26: null | #text(caseA)
// 27: null | #text(otherCase)
// 28: null | #text(|after)
const tI18n = toT18n(`before|{
�0�, select,
A {caseA}
other {otherCase}
}|after`);
expect(tI18n).toEqual(
matchTI18n({
create: matchDebug([
`lView[${HEADER_OFFSET + 2}] = document.createText("before|");`,
`parent.appendChild(lView[${HEADER_OFFSET + 2}]);`,
`lView[${HEADER_OFFSET + 3}] = document.createComment("ICU ${HEADER_OFFSET + 0}:0");`,
`parent.appendChild(lView[${HEADER_OFFSET + 3}]);`,
`lView[${HEADER_OFFSET + 7}] = document.createText("|after");`,
`parent.appendChild(lView[${HEADER_OFFSET + 7}]);`,
]),
update: matchDebug([
`if (mask & 0b1) { icuSwitchCase(${HEADER_OFFSET + 3}, \`\${lView[i-1]}\`); }`,
]),
}),
);
expect(getTIcu(fixture.tView, HEADER_OFFSET + 3)).toEqual(
matchTIcu({
type: IcuType.select,
anchorIdx: HEADER_OFFSET + 3,
currentCaseLViewIndex: HEADER_OFFSET + 4,
cases: ['A', 'other'],
create: [
matchDebug([
`lView[${HEADER_OFFSET + 5}] = document.createTextNode("caseA")`,
`(lView[${HOST}] as Element).appendChild(lView[${HEADER_OFFSET + 5}])`,
]),
matchDebug([
`lView[${HEADER_OFFSET + 6}] = document.createTextNode("otherCase")`,
`(lView[${HOST}] as Element).appendChild(lView[${HEADER_OFFSET + 6}])`,
]),
],
update: [matchDebug([]), matchDebug([])],
remove: [
matchDebug([`remove(lView[${HEADER_OFFSET + 5}])`]),
matchDebug([`remove(lView[${HEADER_OFFSET + 6}])`]),
],
}),
);
fixture.apply(() => {
applyCreateOpCodes(fixture.lView, tI18n.create, fixture.host, null);
expect(fixture.host.innerHTML).toEqual(`before|<!--ICU ${HEADER_OFFSET + 0}:0-->|after`);
});
fixture.apply(() => {
ɵɵi18nExp('A');
ɵɵi18nApply(0);
expect(fixture.host.innerHTML).toEqual(
`before|caseA<!--ICU ${HEADER_OFFSET + 0}:0-->|after`,
);
});
fixture.apply(() => {
ɵɵi18nExp('x');
ɵɵi18nApply(0);
expect(fixture.host.innerHTML).toEqual(
`before|otherCase<!--ICU ${HEADER_OFFSET + 0}:0-->|after`,
);
});
fixture.apply(() => {
ɵɵi18nExp('A');
ɵɵi18nApply(0);
expect(fixture.host.innerHTML).toEqual(
`before|caseA<!--ICU ${HEADER_OFFSET + 0}:0-->|after`,
);
});
});
it('should parse HTML in ICU', () => {
const tI18n = toT18n(`{
�0�, select,
A {Hello <b>world<i>!</i></b>}
other {<div>{�0�, select, 0 {nested0} other {nestedOther}}</div>}
}`);
fixture.apply(() => {
applyCreateOpCodes(fixture.lView, tI18n.create, fixture.host, null);
expect(fixture.host.innerHTML).toEqual(`<!--ICU ${HEADER_OFFSET + 0}:0-->`);
});
fixture.apply(() => {
ɵɵi18nExp('A');
ɵɵi18nApply(0);
expect(fixture.host.innerHTML).toEqual(
`Hello <b>world<i>!</i></b><!--ICU ${HEADER_OFFSET + 0}:0-->`,
);
});
fixture.apply(() => {
ɵɵi18nExp('x');
ɵɵi18nApply(0);
expect(fixture.host.innerHTML).toEqual(
`<div>nestedOther<!--nested ICU 0--></div><!--ICU ${HEADER_OFFSET + 0}:0-->`,
);
});
fixture.apply(() => {
ɵɵi18nExp('A');
ɵɵi18nApply(0);
expect(fixture.host.innerHTML).toEqual(
`Hello <b>world<i>!</i></b><!--ICU ${HEADER_OFFSET + 0}:0-->`,
);
});
});
it('should parse nested ICU', () = | {
"end_byte": 5966,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/i18n/i18n_parse_spec.ts"
} |
angular/packages/core/test/render3/i18n/i18n_parse_spec.ts_5972_11995 | fixture = new ViewFixture({decls: 1, vars: 3});
// TData | LView
// ---------------------------+-------------------------------
// ----- DECL -----
// 21: TI18n |
// ----- VARS -----
// 22: Binding for parent ICU |
// 23: Binding for child ICU |
// 24: Binding for child ICU |
// ----- EXPANDO -----
// 25: TIcu (parent) | <!-- ICU 20:0 -->
// 26: null | currently selected ICU case
// 27: null | #text( parentA )
// 28: TIcu (child) | <!-- nested ICU 0 -->
// 29: null | currently selected ICU case
// 30: null | #text(nested0)
// 31: null | #text({{�2�}})
// 32: null | #text( )
// 33: null | #text( parentOther )
const tI18n = toT18n(`{
�0�, select,
A {parentA {�1�, select, 0 {nested0} other {�2�}}!}
other {parentOther}
}`);
expect(tI18n).toEqual(
matchTI18n({
create: matchDebug([
`lView[${HEADER_OFFSET + 4}] = document.createComment("ICU ${HEADER_OFFSET + 0}:0");`,
`parent.appendChild(lView[${HEADER_OFFSET + 4}]);`,
]),
update: matchDebug([
`if (mask & 0b1) { icuSwitchCase(${HEADER_OFFSET + 4}, \`\${lView[i-1]}\`); }`,
`if (mask & 0b10) { icuSwitchCase(${HEADER_OFFSET + 7}, \`\${lView[i-2]}\`); }`,
`if (mask & 0b100) { icuUpdateCase(${HEADER_OFFSET + 7}); }`,
]),
}),
);
expect(getTIcu(fixture.tView, HEADER_OFFSET + 4)).toEqual(
matchTIcu({
type: IcuType.select,
anchorIdx: HEADER_OFFSET + 4,
currentCaseLViewIndex: HEADER_OFFSET + 5,
cases: ['A', 'other'],
create: [
matchDebug([
`lView[${HEADER_OFFSET + 6}] = document.createTextNode("parentA ")`,
`(lView[${HOST}] as Element).appendChild(lView[${HEADER_OFFSET + 6}])`,
`lView[${HEADER_OFFSET + 7}] = document.createComment("nested ICU 0")`,
`(lView[${HOST}] as Element).appendChild(lView[${HEADER_OFFSET + 7}])`,
`lView[${HEADER_OFFSET + 11}] = document.createTextNode("!")`,
`(lView[${HOST}] as Element).appendChild(lView[${HEADER_OFFSET + 11}])`,
]),
matchDebug([
`lView[${HEADER_OFFSET + 12}] = document.createTextNode("parentOther")`,
`(lView[${HOST}] as Element).appendChild(lView[${HEADER_OFFSET + 12}])`,
]),
],
update: [matchDebug([]), matchDebug([])],
remove: [
matchDebug([
`remove(lView[${HEADER_OFFSET + 6}])`,
`removeNestedICU(${HEADER_OFFSET + 7})`,
`remove(lView[${HEADER_OFFSET + 7}])`,
`remove(lView[${HEADER_OFFSET + 11}])`,
]),
matchDebug([`remove(lView[${HEADER_OFFSET + 12}])`]),
],
}),
);
expect(getTIcu(fixture.tView, HEADER_OFFSET + 7)).toEqual(
matchTIcu({
type: IcuType.select,
anchorIdx: HEADER_OFFSET + 7,
currentCaseLViewIndex: HEADER_OFFSET + 8,
cases: ['0', 'other'],
create: [
matchDebug([
`lView[${HEADER_OFFSET + 9}] = document.createTextNode("nested0")`,
`(lView[${HOST}] as Element).appendChild(lView[${HEADER_OFFSET + 9}])`,
]),
matchDebug([
`lView[${HEADER_OFFSET + 10}] = document.createTextNode("")`,
`(lView[${HOST}] as Element).appendChild(lView[${HEADER_OFFSET + 10}])`,
]),
],
update: [
matchDebug([]),
matchDebug([
`if (mask & 0b100) { (lView[${
HEADER_OFFSET + 10
}] as Text).textContent = \`\${lView[i-3]}\`; }`,
]),
],
remove: [
matchDebug([`remove(lView[${HEADER_OFFSET + 9}])`]),
matchDebug([`remove(lView[${HEADER_OFFSET + 10}])`]),
],
}),
);
fixture.apply(() => {
applyCreateOpCodes(fixture.lView, tI18n.create, fixture.host, null);
expect(fixture.host.innerHTML).toEqual(`<!--ICU ${HEADER_OFFSET + 0}:0-->`);
});
fixture.apply(() => {
ɵɵi18nExp('A');
ɵɵi18nExp('0');
ɵɵi18nExp('value1');
ɵɵi18nApply(0);
expect(fixture.host.innerHTML).toEqual(
`parentA nested0<!--nested ICU 0-->!<!--ICU ${HEADER_OFFSET + 0}:0-->`,
);
});
fixture.apply(() => {
ɵɵi18nExp('A');
ɵɵi18nExp('x');
ɵɵi18nExp('value1');
ɵɵi18nApply(0);
expect(fixture.host.innerHTML).toEqual(
`parentA value1<!--nested ICU 0-->!<!--ICU ${HEADER_OFFSET + 0}:0-->`,
);
});
fixture.apply(() => {
ɵɵi18nExp('x');
ɵɵi18nExp('x');
ɵɵi18nExp('value2');
ɵɵi18nApply(0);
expect(fixture.host.innerHTML).toEqual(`parentOther<!--ICU ${HEADER_OFFSET + 0}:0-->`);
});
fixture.apply(() => {
ɵɵi18nExp('A');
ɵɵi18nExp('A');
ɵɵi18nExp('value2');
ɵɵi18nApply(0);
expect(fixture.host.innerHTML).toEqual(
`parentA value2<!--nested ICU 0-->!<!--ICU ${HEADER_OFFSET + 0}:0-->`,
);
});
});
});
function toT18n(text: string) {
const tNodeIndex = HEADER_OFFSET;
fixture.enterView();
i18nStartFirstCreatePass(fixture.tView, 0, fixture.lView, tNodeIndex, text, -1);
fixture.leaveView();
const tI18n = fixture.tView.data[tNodeIndex] as TI18n;
expect(tI18n).toEqual(matchTI18n({}));
return tI18n;
}
});
| {
"end_byte": 11995,
"start_byte": 5972,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/i18n/i18n_parse_spec.ts"
} |
angular/packages/core/test/render3/i18n/i18n_insert_before_index_spec.ts_0_7937 | /**
* @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 {addTNodeAndUpdateInsertBeforeIndex} from '@angular/core/src/render3/i18n/i18n_insert_before_index';
import {createTNode} from '@angular/core/src/render3/instructions/shared';
import {TNode, TNodeType} from '@angular/core/src/render3/interfaces/node';
import {HEADER_OFFSET} from '@angular/core/src/render3/interfaces/view';
import {matchTNode} from '../matchers';
describe('addTNodeAndUpdateInsertBeforeIndex', () => {
function tNode(index: number, type: TNodeType, insertBeforeIndex: number | null = null): TNode {
const tNode = createTNode(null!, null, type, index, null, null);
tNode.insertBeforeIndex = insertBeforeIndex;
return tNode;
}
function tPlaceholderElementNode(index: number, insertBeforeIndex: number | null = null) {
return tNode(index, TNodeType.Placeholder, insertBeforeIndex);
}
function tI18NTextNode(index: number, insertBeforeIndex: number | null = null) {
return tNode(index, TNodeType.Element, insertBeforeIndex);
}
it('should add first node', () => {
const previousTNodes: TNode[] = [];
addTNodeAndUpdateInsertBeforeIndex(previousTNodes, tPlaceholderElementNode(HEADER_OFFSET + 0));
expect(previousTNodes).toEqual([
matchTNode({index: HEADER_OFFSET + 0, insertBeforeIndex: null}),
]);
});
describe('when adding a placeholder', () => {
describe('whose index is greater than those already there', () => {
it('should not update the `insertBeforeIndex` values', () => {
const previousTNodes: TNode[] = [
tPlaceholderElementNode(HEADER_OFFSET + 0),
tPlaceholderElementNode(HEADER_OFFSET + 1),
];
addTNodeAndUpdateInsertBeforeIndex(
previousTNodes,
tPlaceholderElementNode(HEADER_OFFSET + 2),
);
expect(previousTNodes).toEqual([
matchTNode({index: HEADER_OFFSET + 0, insertBeforeIndex: null}),
matchTNode({index: HEADER_OFFSET + 1, insertBeforeIndex: null}),
matchTNode({index: HEADER_OFFSET + 2, insertBeforeIndex: null}),
]);
});
});
describe('whose index is smaller than current nodes', () => {
it('should update the previous insertBeforeIndex', () => {
const previousTNodes: TNode[] = [
tPlaceholderElementNode(HEADER_OFFSET + 1),
tPlaceholderElementNode(HEADER_OFFSET + 2),
];
addTNodeAndUpdateInsertBeforeIndex(
previousTNodes,
tPlaceholderElementNode(HEADER_OFFSET + 0),
);
expect(previousTNodes).toEqual([
matchTNode({index: HEADER_OFFSET + 1, insertBeforeIndex: HEADER_OFFSET + 0}),
matchTNode({index: HEADER_OFFSET + 2, insertBeforeIndex: HEADER_OFFSET + 0}),
matchTNode({index: HEADER_OFFSET + 0, insertBeforeIndex: null}),
]);
});
it('should not update the previous insertBeforeIndex if it is already set', () => {
const previousTNodes: TNode[] = [
tPlaceholderElementNode(HEADER_OFFSET + 2, HEADER_OFFSET + 1),
tPlaceholderElementNode(HEADER_OFFSET + 3, HEADER_OFFSET + 1),
tPlaceholderElementNode(HEADER_OFFSET + 1),
];
addTNodeAndUpdateInsertBeforeIndex(
previousTNodes,
tPlaceholderElementNode(HEADER_OFFSET + 0),
);
expect(previousTNodes).toEqual([
matchTNode({index: HEADER_OFFSET + 2, insertBeforeIndex: HEADER_OFFSET + 1}),
matchTNode({index: HEADER_OFFSET + 3, insertBeforeIndex: HEADER_OFFSET + 1}),
matchTNode({index: HEADER_OFFSET + 1, insertBeforeIndex: HEADER_OFFSET + 0}),
matchTNode({index: HEADER_OFFSET + 0, insertBeforeIndex: null}),
]);
});
it('should not update the previous insertBeforeIndex if it is created after', () => {
const previousTNodes: TNode[] = [
tPlaceholderElementNode(HEADER_OFFSET + 5, HEADER_OFFSET + 0),
tPlaceholderElementNode(HEADER_OFFSET + 6, HEADER_OFFSET + 0),
tPlaceholderElementNode(HEADER_OFFSET + 0),
];
addTNodeAndUpdateInsertBeforeIndex(
previousTNodes,
tPlaceholderElementNode(HEADER_OFFSET + 3),
);
expect(previousTNodes).toEqual([
matchTNode({index: HEADER_OFFSET + 5, insertBeforeIndex: HEADER_OFFSET + 0}),
matchTNode({index: HEADER_OFFSET + 6, insertBeforeIndex: HEADER_OFFSET + 0}),
matchTNode({index: HEADER_OFFSET + 0, insertBeforeIndex: null}),
matchTNode({index: HEADER_OFFSET + 3, insertBeforeIndex: null}),
]);
});
});
});
describe('when adding a i18nText', () => {
describe('whose index is greater than those already there', () => {
it('should not update the `insertBeforeIndex` values', () => {
const previousTNodes: TNode[] = [
tPlaceholderElementNode(HEADER_OFFSET + 0),
tPlaceholderElementNode(HEADER_OFFSET + 1),
];
addTNodeAndUpdateInsertBeforeIndex(previousTNodes, tI18NTextNode(HEADER_OFFSET + 2));
expect(previousTNodes).toEqual([
matchTNode({index: HEADER_OFFSET + 0, insertBeforeIndex: HEADER_OFFSET + 2}),
matchTNode({index: HEADER_OFFSET + 1, insertBeforeIndex: HEADER_OFFSET + 2}),
matchTNode({index: HEADER_OFFSET + 2, insertBeforeIndex: null}),
]);
});
});
describe('whose index is smaller than current nodes', () => {
it('should update the previous insertBeforeIndex', () => {
const previousTNodes: TNode[] = [
tPlaceholderElementNode(HEADER_OFFSET + 1),
tPlaceholderElementNode(HEADER_OFFSET + 2),
];
addTNodeAndUpdateInsertBeforeIndex(previousTNodes, tI18NTextNode(HEADER_OFFSET + 0));
expect(previousTNodes).toEqual([
matchTNode({index: HEADER_OFFSET + 1, insertBeforeIndex: HEADER_OFFSET + 0}),
matchTNode({index: HEADER_OFFSET + 2, insertBeforeIndex: HEADER_OFFSET + 0}),
matchTNode({index: HEADER_OFFSET + 0, insertBeforeIndex: null}),
]);
});
it('should not update the previous insertBeforeIndex if it is already set', () => {
const previousTNodes: TNode[] = [
tPlaceholderElementNode(HEADER_OFFSET + 2, HEADER_OFFSET + 1),
tPlaceholderElementNode(HEADER_OFFSET + 3, HEADER_OFFSET + 1),
tPlaceholderElementNode(HEADER_OFFSET + 1),
];
addTNodeAndUpdateInsertBeforeIndex(previousTNodes, tI18NTextNode(HEADER_OFFSET + 0));
expect(previousTNodes).toEqual([
matchTNode({index: HEADER_OFFSET + 2, insertBeforeIndex: HEADER_OFFSET + 1}),
matchTNode({index: HEADER_OFFSET + 3, insertBeforeIndex: HEADER_OFFSET + 1}),
matchTNode({index: HEADER_OFFSET + 1, insertBeforeIndex: HEADER_OFFSET + 0}),
matchTNode({index: HEADER_OFFSET + 0, insertBeforeIndex: null}),
]);
});
it('should not update the previous insertBeforeIndex if it is created after', () => {
const previousTNodes: TNode[] = [
tPlaceholderElementNode(HEADER_OFFSET + 5, HEADER_OFFSET + 0),
tPlaceholderElementNode(HEADER_OFFSET + 6, HEADER_OFFSET + 0),
tPlaceholderElementNode(HEADER_OFFSET + 0),
];
addTNodeAndUpdateInsertBeforeIndex(previousTNodes, tI18NTextNode(HEADER_OFFSET + 3));
expect(previousTNodes).toEqual([
matchTNode({index: HEADER_OFFSET + 5, insertBeforeIndex: HEADER_OFFSET + 0}),
matchTNode({index: HEADER_OFFSET + 6, insertBeforeIndex: HEADER_OFFSET + 0}),
matchTNode({index: HEADER_OFFSET + 0, insertBeforeIndex: HEADER_OFFSET + 3}),
matchTNode({index: HEADER_OFFSET + 3, insertBeforeIndex: null}),
]);
});
});
}); | {
"end_byte": 7937,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/i18n/i18n_insert_before_index_spec.ts"
} |
angular/packages/core/test/render3/i18n/i18n_insert_before_index_spec.ts_7941_9540 | describe('scenario', () => {
it('should rearrange the nodes', () => {
const previousTNodes: TNode[] = [];
addTNodeAndUpdateInsertBeforeIndex(
previousTNodes,
tPlaceholderElementNode(HEADER_OFFSET + 2),
);
addTNodeAndUpdateInsertBeforeIndex(
previousTNodes,
tPlaceholderElementNode(HEADER_OFFSET + 8),
);
addTNodeAndUpdateInsertBeforeIndex(
previousTNodes,
tPlaceholderElementNode(HEADER_OFFSET + 4),
);
addTNodeAndUpdateInsertBeforeIndex(
previousTNodes,
tPlaceholderElementNode(HEADER_OFFSET + 5),
);
addTNodeAndUpdateInsertBeforeIndex(previousTNodes, tI18NTextNode(HEADER_OFFSET + 9));
addTNodeAndUpdateInsertBeforeIndex(
previousTNodes,
tPlaceholderElementNode(HEADER_OFFSET + 3),
);
addTNodeAndUpdateInsertBeforeIndex(
previousTNodes,
tPlaceholderElementNode(HEADER_OFFSET + 7),
);
expect(previousTNodes).toEqual([
matchTNode({index: HEADER_OFFSET + 2, insertBeforeIndex: HEADER_OFFSET + 9}),
matchTNode({index: HEADER_OFFSET + 8, insertBeforeIndex: HEADER_OFFSET + 4}),
matchTNode({index: HEADER_OFFSET + 4, insertBeforeIndex: HEADER_OFFSET + 9}),
matchTNode({index: HEADER_OFFSET + 5, insertBeforeIndex: HEADER_OFFSET + 9}),
matchTNode({index: HEADER_OFFSET + 9, insertBeforeIndex: null}),
matchTNode({index: HEADER_OFFSET + 3, insertBeforeIndex: null}),
matchTNode({index: HEADER_OFFSET + 7, insertBeforeIndex: null}),
]);
});
});
}); | {
"end_byte": 9540,
"start_byte": 7941,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/i18n/i18n_insert_before_index_spec.ts"
} |
angular/packages/core/test/render3/interfaces/node_spec.ts_0_1421 | /**
* @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 {TNodeType, toTNodeTypeAsString} from '@angular/core/src/render3/interfaces/node';
describe('node interfaces', () => {
describe('TNodeType', () => {
it('should agree with toTNodeTypeAsString', () => {
expect(toTNodeTypeAsString(TNodeType.Element)).toEqual('Element');
expect(toTNodeTypeAsString(TNodeType.Text)).toEqual('Text');
expect(toTNodeTypeAsString(TNodeType.Container)).toEqual('Container');
expect(toTNodeTypeAsString(TNodeType.Projection)).toEqual('Projection');
expect(toTNodeTypeAsString(TNodeType.ElementContainer)).toEqual('ElementContainer');
expect(toTNodeTypeAsString(TNodeType.Icu)).toEqual('IcuContainer');
expect(toTNodeTypeAsString(TNodeType.Placeholder)).toEqual('Placeholder');
expect(toTNodeTypeAsString(TNodeType.LetDeclaration)).toEqual('LetDeclaration');
expect(
toTNodeTypeAsString(
TNodeType.Container |
TNodeType.Projection |
TNodeType.Element |
TNodeType.ElementContainer |
TNodeType.Icu |
TNodeType.LetDeclaration,
),
).toEqual('Element|Container|ElementContainer|Projection|IcuContainer|LetDeclaration');
});
});
});
| {
"end_byte": 1421,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/render3/interfaces/node_spec.ts"
} |
angular/packages/core/test/dom/dom_adapter_spec.ts_0_2312 | /**
* @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 {isTextNode} from '@angular/platform-browser/testing/src/browser_util';
describe('dom adapter', () => {
let defaultDoc: any;
beforeEach(() => {
defaultDoc = getDOM().supportsDOMEvents ? document : getDOM().createHtmlDocument();
});
it('should be able to create text nodes and use them with the other APIs', () => {
const t = getDOM().getDefaultDocument().createTextNode('hello');
expect(isTextNode(t)).toBe(true);
const d = getDOM().createElement('div');
d.appendChild(t);
expect(d.innerHTML).toEqual('hello');
});
it('should set className via the class attribute', () => {
const d = getDOM().createElement('div');
d.setAttribute('class', 'class1');
expect(d.className).toEqual('class1');
});
it('should allow to remove nodes without parents', () => {
const d = getDOM().createElement('div');
expect(() => getDOM().remove(d)).not.toThrow();
});
if (getDOM().supportsDOMEvents) {
describe('getBaseHref', () => {
beforeEach(() => getDOM().resetBaseElement());
it('should return null if base element is absent', () => {
expect(getDOM().getBaseHref(defaultDoc)).toBeNull();
});
it('should return the value of the base element', () => {
const baseEl = getDOM().createElement('base');
baseEl.setAttribute('href', '/drop/bass/connon/');
const headEl = defaultDoc.head;
headEl.appendChild(baseEl);
const baseHref = getDOM().getBaseHref(defaultDoc);
baseEl.remove();
getDOM().resetBaseElement();
expect(baseHref).toEqual('/drop/bass/connon/');
});
it('should return a relative url', () => {
const baseEl = getDOM().createElement('base');
baseEl.setAttribute('href', 'base');
const headEl = defaultDoc.head;
headEl.appendChild(baseEl);
const baseHref = getDOM().getBaseHref(defaultDoc)!;
baseEl.remove();
getDOM().resetBaseElement();
expect(baseHref.endsWith('/base')).toBe(true);
});
});
}
});
| {
"end_byte": 2312,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/dom/dom_adapter_spec.ts"
} |
angular/packages/core/test/dom/shim_spec.ts_0_666 | /**
* @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
*/
// This isn't used for anything, but for some reason Bazel won't
// serve the file if there isn't at least one import.
import '@angular/core/testing';
describe('Shim', () => {
it('should provide correct function.name ', () => {
const functionWithoutName = identity(() => function () {});
function foo() {}
expect(functionWithoutName.name).toBeFalsy();
expect(foo.name).toEqual('foo');
});
});
function identity<T>(a: T): T {
return a;
}
| {
"end_byte": 666,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/dom/shim_spec.ts"
} |
angular/packages/core/test/strict_types/inheritance_spec.ts_0_1402 | /**
* @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 {ɵɵComponentDeclaration, ɵɵPipeDeclaration} from '@angular/core';
declare class SuperComponent {
static ɵcmp: ɵɵComponentDeclaration<SuperComponent, '[super]', never, {}, {}, never, never>;
}
declare class SubComponent extends SuperComponent {
// Declaring a field in the subtype makes its structure incompatible with that of the
// supertype. Special care needs to be taken in Ivy's definition types, or TypeScript
// would produce type errors when the "strictFunctionTypes" option is enabled.
onlyInSubtype: string;
static ɵcmp: ɵɵComponentDeclaration<SubComponent, '[sub]', never, {}, {}, never, never>;
}
declare class SuperPipe {
static ɵpipe: ɵɵPipeDeclaration<SuperPipe, 'super'>;
}
declare class SubPipe extends SuperPipe {
onlyInSubtype: string;
static ɵpipe: ɵɵPipeDeclaration<SubPipe, 'sub'>;
}
describe('inheritance strict type checking', () => {
// Verify that Ivy definition fields in declaration files conform to TypeScript's strict
// type checking constraints in the case of inheritance across directives/components/pipes.
// https://github.com/angular/angular/issues/28079
it('should compile without errors', () => {});
});
| {
"end_byte": 1402,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/strict_types/inheritance_spec.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.