_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/common/test/directives/ng_template_outlet_spec.ts_9151_15449 | it('should not throw when switching from template to null and back to template', waitForAsync(() => {
const template =
`<tpl-refs #refs="tplRefs"><ng-template>foo</ng-template></tpl-refs>` +
`<ng-container [ngTemplateOutlet]="currentTplRef"></ng-container>`;
fixture = createTestComponent(template);
fixture.detectChanges();
const refs = fixture.debugElement.children[0].references!['refs'];
setTplRef(refs.tplRefs.first);
detectChangesAndExpectText('foo');
setTplRef(null);
detectChangesAndExpectText('');
expect(() => {
setTplRef(refs.tplRefs.first);
detectChangesAndExpectText('foo');
}).not.toThrow();
}));
it('should not mutate context object if two contexts with an identical shape are swapped', () => {
fixture = TestBed.createComponent(MultiContextComponent);
const {componentInstance, nativeElement} = fixture;
componentInstance.context1 = {name: 'one'};
componentInstance.context2 = {name: 'two'};
fixture.detectChanges();
expect(nativeElement.textContent.trim()).toBe('one | two');
expect(componentInstance.context1).toEqual({name: 'one'});
expect(componentInstance.context2).toEqual({name: 'two'});
const temp = componentInstance.context1;
componentInstance.context1 = componentInstance.context2;
componentInstance.context2 = temp;
fixture.detectChanges();
expect(nativeElement.textContent.trim()).toBe('two | one');
expect(componentInstance.context1).toEqual({name: 'two'});
expect(componentInstance.context2).toEqual({name: 'one'});
});
it('should be able to specify an injector', waitForAsync(() => {
const template =
`<ng-template #tpl><inject-value></inject-value></ng-template>` +
`<ng-container *ngTemplateOutlet="tpl; injector: injector"></ng-container>`;
fixture = createTestComponent(template);
fixture.componentInstance.injector = Injector.create({
providers: [{provide: templateToken, useValue: 'world'}],
});
detectChangesAndExpectText('Hello world');
}));
it('should re-render if the injector changes', waitForAsync(() => {
const template =
`<ng-template #tpl><inject-value></inject-value></ng-template>` +
`<ng-container *ngTemplateOutlet="tpl; injector: injector"></ng-container>`;
fixture = createTestComponent(template);
fixture.componentInstance.injector = Injector.create({
providers: [{provide: templateToken, useValue: 'world'}],
});
detectChangesAndExpectText('Hello world');
fixture.componentInstance.injector = Injector.create({
providers: [{provide: templateToken, useValue: 'there'}],
});
detectChangesAndExpectText('Hello there');
}));
it('should override providers from parent component using custom injector', waitForAsync(() => {
const template =
`<ng-template #tpl><inject-value></inject-value></ng-template>` +
`<ng-container *ngTemplateOutlet="tpl; injector: injector"></ng-container>`;
fixture = createTestComponent(template, [{provide: templateToken, useValue: 'parent'}]);
fixture.componentInstance.injector = Injector.create({
providers: [{provide: templateToken, useValue: 'world'}],
});
detectChangesAndExpectText('Hello world');
}));
it('should be available as a standalone directive', () => {
@Component({
selector: 'test-component',
imports: [NgTemplateOutlet],
template: `
<ng-template #tpl>Hello World</ng-template>
<ng-container *ngTemplateOutlet="tpl"></ng-container>
`,
standalone: true,
})
class TestComponent {}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('Hello World');
});
it('should properly bind context if context is unset initially', () => {
@Component({
imports: [NgTemplateOutlet],
template: `
<ng-template #tpl let-name>Name:{{ name }}</ng-template>
<ng-template [ngTemplateOutlet]="tpl" [ngTemplateOutletContext]="ctx"></ng-template>
`,
standalone: true,
})
class TestComponent {
ctx: {$implicit: string} | undefined = undefined;
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('Name:');
fixture.componentInstance.ctx = {$implicit: 'Angular'};
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('Name:Angular');
});
});
const templateToken = new InjectionToken<string>('templateToken');
@Injectable()
class DestroyedSpyService {
destroyed = false;
}
@Component({
selector: 'destroyable-cmpt',
template: 'Content to destroy',
standalone: false,
})
class DestroyableCmpt implements OnDestroy {
constructor(private _spyService: DestroyedSpyService) {}
ngOnDestroy(): void {
this._spyService.destroyed = true;
}
}
@Directive({
selector: 'tpl-refs',
exportAs: 'tplRefs',
standalone: false,
})
class CaptureTplRefs {
@ContentChildren(TemplateRef) tplRefs?: QueryList<TemplateRef<any>>;
}
@Component({
selector: 'test-cmp',
template: '',
standalone: false,
})
class TestComponent {
currentTplRef?: TemplateRef<any>;
context: any = {foo: 'bar'};
value = 'bar';
injector: Injector | null = null;
}
@Component({
selector: 'inject-value',
template: 'Hello {{tokenValue}}',
standalone: false,
})
class InjectValueComponent {
constructor(@Inject(templateToken) public tokenValue: string) {}
}
@Component({
template: `
<ng-template #template let-name="name">{{ name }}</ng-template>
<ng-template [ngTemplateOutlet]="template" [ngTemplateOutletContext]="context1"></ng-template>
|
<ng-template [ngTemplateOutlet]="template" [ngTemplateOutletContext]="context2"></ng-template>
`,
standalone: false,
})
class MultiContextComponent {
context1: {name: string} | undefined;
context2: {name: string} | undefined;
}
function createTestComponent(
template: string,
providers: Provider[] = [],
): ComponentFixture<TestComponent> {
return TestBed.overrideComponent(TestComponent, {set: {template: template, providers}})
.configureTestingModule({schemas: [NO_ERRORS_SCHEMA]})
.createComponent(TestComponent);
} | {
"end_byte": 15449,
"start_byte": 9151,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_template_outlet_spec.ts"
} |
angular/packages/common/test/directives/ng_class_spec.ts_0_8115 | /**
* @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 {NgClass} from '@angular/common';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
describe('binding to CSS class list', () => {
let fixture: ComponentFixture<any> | null;
function normalizeClassNames(classes: string) {
return classes.trim().split(' ').sort().join(' ');
}
function detectChangesAndExpectClassName(classes: string): void {
fixture!.detectChanges();
let nonNormalizedClassName = fixture!.debugElement.children[0].nativeElement.className;
expect(normalizeClassNames(nonNormalizedClassName)).toEqual(normalizeClassNames(classes));
}
function getComponent(): TestComponent {
return fixture!.debugElement.componentInstance;
}
afterEach(() => {
fixture = null;
});
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestComponent],
});
});
it('should clean up when the directive is destroyed', waitForAsync(() => {
fixture = createTestComponent('<div *ngFor="let item of items" [ngClass]="item"></div>');
getComponent().items = [['0']];
fixture.detectChanges();
getComponent().items = [['1']];
detectChangesAndExpectClassName('1');
}));
describe('expressions evaluating to objects', () => {
it('should add classes specified in an object literal', waitForAsync(() => {
fixture = createTestComponent('<div [ngClass]="{foo: true, bar: false}"></div>');
detectChangesAndExpectClassName('foo');
}));
it('should add classes specified in an object literal without change in class names', waitForAsync(() => {
fixture = createTestComponent(`<div [ngClass]="{'foo-bar': true, 'fooBar': true}"></div>`);
detectChangesAndExpectClassName('foo-bar fooBar');
}));
it('should add and remove classes based on changes in object literal values', waitForAsync(() => {
fixture = createTestComponent('<div [ngClass]="{foo: condition, bar: !condition}"></div>');
detectChangesAndExpectClassName('foo');
getComponent().condition = false;
detectChangesAndExpectClassName('bar');
}));
it('should add and remove classes based on changes to the expression object', waitForAsync(() => {
fixture = createTestComponent('<div [ngClass]="objExpr"></div>');
const objExpr = getComponent().objExpr;
detectChangesAndExpectClassName('foo');
objExpr!['bar'] = true;
detectChangesAndExpectClassName('foo bar');
objExpr!['baz'] = true;
detectChangesAndExpectClassName('foo bar baz');
delete objExpr!['bar'];
detectChangesAndExpectClassName('foo baz');
}));
it('should add and remove classes based on reference changes to the expression object', waitForAsync(() => {
fixture = createTestComponent('<div [ngClass]="objExpr"></div>');
detectChangesAndExpectClassName('foo');
getComponent().objExpr = {foo: true, bar: true};
detectChangesAndExpectClassName('foo bar');
getComponent().objExpr = {baz: true};
detectChangesAndExpectClassName('baz');
}));
it('should remove active classes when expression evaluates to null', waitForAsync(() => {
fixture = createTestComponent('<div [ngClass]="objExpr"></div>');
detectChangesAndExpectClassName('foo');
getComponent().objExpr = null;
detectChangesAndExpectClassName('');
getComponent().objExpr = {'foo': false, 'bar': true};
detectChangesAndExpectClassName('bar');
}));
it('should remove active classes when expression evaluates to undefined', waitForAsync(() => {
fixture = createTestComponent('<div [ngClass]="objExpr"></div>');
detectChangesAndExpectClassName('foo');
getComponent().objExpr = undefined;
detectChangesAndExpectClassName('');
getComponent().objExpr = {'foo': false, 'bar': true};
detectChangesAndExpectClassName('bar');
}));
it('should allow multiple classes per expression', waitForAsync(() => {
fixture = createTestComponent('<div [ngClass]="objExpr"></div>');
getComponent().objExpr = {'bar baz': true, 'bar1 baz1': true};
detectChangesAndExpectClassName('bar baz bar1 baz1');
getComponent().objExpr = {'bar baz': false, 'bar1 baz1': true};
detectChangesAndExpectClassName('bar1 baz1');
}));
it('should split by one or more spaces between classes', waitForAsync(() => {
fixture = createTestComponent('<div [ngClass]="objExpr"></div>');
getComponent().objExpr = {'foo bar baz': true};
detectChangesAndExpectClassName('foo bar baz');
}));
});
describe('expressions evaluating to lists', () => {
it('should add classes specified in a list literal', waitForAsync(() => {
fixture = createTestComponent(`<div [ngClass]="['foo', 'bar', 'foo-bar', 'fooBar']"></div>`);
detectChangesAndExpectClassName('foo bar foo-bar fooBar');
}));
it('should add and remove classes based on changes to the expression', waitForAsync(() => {
fixture = createTestComponent('<div [ngClass]="arrExpr"></div>');
const arrExpr = getComponent().arrExpr;
detectChangesAndExpectClassName('foo');
arrExpr.push('bar');
detectChangesAndExpectClassName('foo bar');
arrExpr[1] = 'baz';
detectChangesAndExpectClassName('foo baz');
getComponent().arrExpr = arrExpr.filter((v: string) => v !== 'baz');
detectChangesAndExpectClassName('foo');
}));
it('should add and remove classes when a reference changes', waitForAsync(() => {
fixture = createTestComponent('<div [ngClass]="arrExpr"></div>');
detectChangesAndExpectClassName('foo');
getComponent().arrExpr = ['bar'];
detectChangesAndExpectClassName('bar');
}));
it('should take initial classes into account when a reference changes', waitForAsync(() => {
fixture = createTestComponent('<div class="foo" [ngClass]="arrExpr"></div>');
detectChangesAndExpectClassName('foo');
getComponent().arrExpr = ['bar'];
detectChangesAndExpectClassName('foo bar');
}));
it('should ignore empty or blank class names', waitForAsync(() => {
fixture = createTestComponent('<div class="foo" [ngClass]="arrExpr"></div>');
getComponent().arrExpr = ['', ' '];
detectChangesAndExpectClassName('foo');
}));
it('should trim blanks from class names', waitForAsync(() => {
fixture = createTestComponent('<div class="foo" [ngClass]="arrExpr"></div>');
getComponent().arrExpr = [' bar '];
detectChangesAndExpectClassName('foo bar');
}));
it('should allow multiple classes per item in arrays', waitForAsync(() => {
fixture = createTestComponent('<div [ngClass]="arrExpr"></div>');
getComponent().arrExpr = ['foo bar baz', 'foo1 bar1 baz1'];
detectChangesAndExpectClassName('foo bar baz foo1 bar1 baz1');
getComponent().arrExpr = ['foo bar baz foobar'];
detectChangesAndExpectClassName('foo bar baz foobar');
}));
it('should throw with descriptive error message when CSS class is not a string', () => {
fixture = createTestComponent(`<div [ngClass]="['foo', {}]"></div>`);
expect(() => fixture!.detectChanges()).toThrowError(
/NgClass can only toggle CSS classes expressed as strings, got \[object Object\]/,
);
});
});
describe('expressions evaluating to sets', () => {
it('should add and remove classes if the set instance changed', waitForAsync(() => {
fixture = createTestComponent('<div [ngClass]="setExpr"></div>');
let setExpr = new Set<string>();
setExpr.add('bar');
getComponent().setExpr = setExpr;
detectChangesAndExpectClassName('bar');
setExpr = new Set<string>();
setExpr.add('baz');
getComponent().setExpr = setExpr;
detectChangesAndExpectClassName('baz');
}));
}); | {
"end_byte": 8115,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_class_spec.ts"
} |
angular/packages/common/test/directives/ng_class_spec.ts_8119_13994 | describe('expressions evaluating to string', () => {
it('should add classes specified in a string literal', waitForAsync(() => {
fixture = createTestComponent(`<div [ngClass]="'foo bar foo-bar fooBar'"></div>`);
detectChangesAndExpectClassName('foo bar foo-bar fooBar');
}));
it('should add and remove classes based on changes to the expression', waitForAsync(() => {
fixture = createTestComponent('<div [ngClass]="strExpr"></div>');
detectChangesAndExpectClassName('foo');
getComponent().strExpr = 'foo bar';
detectChangesAndExpectClassName('foo bar');
getComponent().strExpr = 'baz';
detectChangesAndExpectClassName('baz');
}));
it('should remove active classes when switching from string to null', waitForAsync(() => {
fixture = createTestComponent(`<div [ngClass]="strExpr"></div>`);
detectChangesAndExpectClassName('foo');
getComponent().strExpr = null;
detectChangesAndExpectClassName('');
}));
it('should remove active classes when switching from string to undefined', waitForAsync(() => {
fixture = createTestComponent(`<div [ngClass]="strExpr"></div>`);
detectChangesAndExpectClassName('foo');
getComponent().strExpr = undefined;
detectChangesAndExpectClassName('');
}));
it('should take initial classes into account when switching from string to null', waitForAsync(() => {
fixture = createTestComponent(`<div class="foo" [ngClass]="strExpr"></div>`);
detectChangesAndExpectClassName('foo');
getComponent().strExpr = null;
detectChangesAndExpectClassName('foo');
}));
it('should take initial classes into account when switching from string to undefined', waitForAsync(() => {
fixture = createTestComponent(`<div class="foo" [ngClass]="strExpr"></div>`);
detectChangesAndExpectClassName('foo');
getComponent().strExpr = undefined;
detectChangesAndExpectClassName('foo');
}));
it('should ignore empty and blank strings', waitForAsync(() => {
fixture = createTestComponent(`<div class="foo" [ngClass]="strExpr"></div>`);
getComponent().strExpr = '';
detectChangesAndExpectClassName('foo');
}));
});
describe('cooperation with other class-changing constructs', () => {
it('should co-operate with the class attribute', waitForAsync(() => {
fixture = createTestComponent('<div [ngClass]="objExpr" class="init foo"></div>');
const objExpr = getComponent().objExpr;
objExpr!['bar'] = true;
detectChangesAndExpectClassName('init foo bar');
objExpr!['foo'] = false;
detectChangesAndExpectClassName('init bar');
getComponent().objExpr = null;
detectChangesAndExpectClassName('init foo');
getComponent().objExpr = undefined;
detectChangesAndExpectClassName('init foo');
}));
it('should co-operate with the interpolated class attribute', waitForAsync(() => {
fixture = createTestComponent(`<div [ngClass]="objExpr" class="{{'init foo'}}"></div>`);
const objExpr = getComponent().objExpr;
objExpr!['bar'] = true;
detectChangesAndExpectClassName(`init foo bar`);
objExpr!['foo'] = false;
detectChangesAndExpectClassName(`init bar`);
getComponent().objExpr = null;
detectChangesAndExpectClassName(`init foo`);
getComponent().objExpr = undefined;
detectChangesAndExpectClassName(`init foo`);
}));
it('should co-operate with the interpolated class attribute when interpolation changes', waitForAsync(() => {
fixture = createTestComponent(
`<div [ngClass]="{large: false, small: true}" class="{{strExpr}}"></div>`,
);
detectChangesAndExpectClassName(`foo small`);
getComponent().strExpr = 'bar';
detectChangesAndExpectClassName(`bar small`);
getComponent().strExpr = undefined;
detectChangesAndExpectClassName(`small`);
}));
it('should co-operate with the class attribute and binding to it', waitForAsync(() => {
fixture = createTestComponent(`<div [ngClass]="objExpr" class="init" [class]="'foo'"></div>`);
const objExpr = getComponent().objExpr;
objExpr!['bar'] = true;
detectChangesAndExpectClassName(`init foo bar`);
objExpr!['foo'] = false;
detectChangesAndExpectClassName(`init bar`);
getComponent().objExpr = null;
detectChangesAndExpectClassName(`init foo`);
getComponent().objExpr = undefined;
detectChangesAndExpectClassName(`init foo`);
}));
it('should co-operate with the class attribute and class.name binding', waitForAsync(() => {
const template = '<div class="init foo" [ngClass]="objExpr" [class.baz]="condition"></div>';
fixture = createTestComponent(template);
const objExpr = getComponent().objExpr;
detectChangesAndExpectClassName('init foo baz');
objExpr!['bar'] = true;
detectChangesAndExpectClassName('init foo baz bar');
objExpr!['foo'] = false;
detectChangesAndExpectClassName('init baz bar');
getComponent().condition = false;
detectChangesAndExpectClassName('init bar');
}));
it('should co-operate with initial class and class attribute binding when binding changes', waitForAsync(() => {
const template = '<div class="init" [ngClass]="objExpr" [class]="strExpr"></div>';
fixture = createTestComponent(template);
const cmp = getComponent();
detectChangesAndExpectClassName('init foo');
cmp.objExpr!['bar'] = true;
detectChangesAndExpectClassName('init foo bar');
cmp.strExpr = 'baz';
detectChangesAndExpectClassName('init bar baz foo');
cmp.objExpr = null;
detectChangesAndExpectClassName('init baz');
cmp.objExpr = undefined;
detectChangesAndExpectClassName('init baz');
}));
}); | {
"end_byte": 13994,
"start_byte": 8119,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_class_spec.ts"
} |
angular/packages/common/test/directives/ng_class_spec.ts_13998_19334 | describe('prevent regressions', () => {
// https://github.com/angular/angular/issues/34336
it('should not write to the native node unless the bound expression has changed', () => {
fixture = createTestComponent(`<div [ngClass]="{'color-red': condition}"></div>`);
detectChangesAndExpectClassName('color-red');
// Overwrite CSS classes so that we can check if ngClass performed DOM manipulation to
// update it
fixture.debugElement.children[0].nativeElement.className = '';
// Assert that the DOM node still has the same value after change detection
detectChangesAndExpectClassName('');
fixture.componentInstance.condition = false;
fixture.detectChanges();
fixture.componentInstance.condition = true;
detectChangesAndExpectClassName('color-red');
});
it('should not write to the native node when values are the same (obj reference change)', () => {
fixture = createTestComponent(`<div [ngClass]="objExpr"></div>`);
detectChangesAndExpectClassName('foo');
// Overwrite CSS classes so that we can check if ngClass performed DOM manipulation to
// update it
fixture.debugElement.children[0].nativeElement.className = '';
// Assert that the DOM node still has the same value after change detection
detectChangesAndExpectClassName('');
// change the object reference (without changing values)
fixture.componentInstance.objExp = {...fixture.componentInstance.objExp};
detectChangesAndExpectClassName('');
});
it('should not write to the native node when values are the same (array reference change)', () => {
fixture = createTestComponent(`<div [ngClass]="arrExpr"></div>`);
detectChangesAndExpectClassName('foo');
// Overwrite CSS classes so that we can check if ngClass performed DOM manipulation to
// update it
fixture.debugElement.children[0].nativeElement.className = '';
// Assert that the DOM node still has the same value after change detection
detectChangesAndExpectClassName('');
// change the object reference (without changing values)
fixture.componentInstance.arrExpr = [...fixture.componentInstance.arrExpr];
detectChangesAndExpectClassName('');
});
it('should not add css class when bound initial class is removed by ngClass binding', () => {
fixture = createTestComponent(`<div [class]="'bar'" [ngClass]="objExpr"></div>`);
detectChangesAndExpectClassName('foo');
});
it('should not add css class when static initial class is removed by ngClass binding', () => {
fixture = createTestComponent(`<div class="bar" [ngClass]="objExpr"></div>`);
detectChangesAndExpectClassName('foo');
});
it('should allow classes with trailing and leading spaces in [ngClass]', () => {
@Component({
template: `
<div leading-space [ngClass]="{' foo': applyClasses}"></div>
<div trailing-space [ngClass]="{'foo ': applyClasses}"></div>
`,
standalone: false,
})
class Cmp {
applyClasses = true;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
fixture.detectChanges();
const leading = fixture.nativeElement.querySelector('[leading-space]');
const trailing = fixture.nativeElement.querySelector('[trailing-space]');
expect(leading.className).toBe('foo');
expect(trailing.className).toBe('foo');
});
it('should mix class and ngClass bindings with the same value', () => {
@Component({
selector: 'test-component',
imports: [NgClass],
template: `<div class="{{ 'option-' + level }}" [ngClass]="'option-' + level"></div>`,
standalone: true,
})
class TestComponent {
level = 1;
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement.firstChild.className).toBe('option-1');
fixture.componentInstance.level = 5;
fixture.detectChanges();
expect(fixture.nativeElement.firstChild.className).toBe('option-5');
});
it('should be available as a standalone directive', () => {
@Component({
selector: 'test-component',
imports: [NgClass],
template: `<div trailing-space [ngClass]="{foo: applyClasses}"></div>`,
standalone: true,
})
class TestComponent {
applyClasses = true;
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement.firstChild.className).toBe('foo');
});
});
});
@Component({
selector: 'test-cmp',
template: '',
standalone: false,
})
class TestComponent {
condition: boolean = true;
items: any[] | undefined;
arrExpr: string[] = ['foo'];
setExpr: Set<string> = new Set<string>();
objExpr: {[klass: string]: any} | null | undefined = {'foo': true, 'bar': false};
strExpr: string | null | undefined = 'foo';
constructor() {
this.setExpr.add('foo');
}
}
function createTestComponent(template: string): ComponentFixture<TestComponent> {
return TestBed.overrideComponent(TestComponent, {set: {template: template}}).createComponent(
TestComponent,
);
} | {
"end_byte": 19334,
"start_byte": 13998,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_class_spec.ts"
} |
angular/packages/common/test/directives/ng_switch_spec.ts_0_527 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {CommonModule, NgSwitch, NgSwitchCase, NgSwitchDefault} from '@angular/common';
import {Attribute, Component, Directive, TemplateRef, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers'; | {
"end_byte": 527,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_switch_spec.ts"
} |
angular/packages/common/test/directives/ng_switch_spec.ts_529_8682 | describe('NgSwitch', () => {
let fixture: ComponentFixture<any>;
function getComponent(): TestComponent {
return fixture.componentInstance;
}
function detectChangesAndExpectText(text: string): void {
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText(text);
}
afterEach(() => {
fixture = null!;
});
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestComponent, ComplexComponent],
imports: [CommonModule],
});
});
describe('switch value changes', () => {
it('should switch amongst when values', () => {
const template =
'<ul [ngSwitch]="switchValue">' +
'<li *ngSwitchCase="\'a\'">when a</li>' +
'<li *ngSwitchCase="\'b\'">when b</li>' +
'</ul>';
fixture = createTestComponent(template);
detectChangesAndExpectText('');
getComponent().switchValue = 'a';
detectChangesAndExpectText('when a');
getComponent().switchValue = 'b';
detectChangesAndExpectText('when b');
});
it('should switch amongst when values with fallback to default', () => {
const template =
'<ul [ngSwitch]="switchValue">' +
'<li *ngSwitchCase="\'a\'">when a</li>' +
'<li *ngSwitchDefault>when default</li>' +
'</ul>';
fixture = createTestComponent(template);
detectChangesAndExpectText('when default');
getComponent().switchValue = 'a';
detectChangesAndExpectText('when a');
getComponent().switchValue = 'b';
detectChangesAndExpectText('when default');
getComponent().switchValue = 'c';
detectChangesAndExpectText('when default');
});
it('should support multiple whens with the same value', () => {
const template =
'<ul [ngSwitch]="switchValue">' +
'<li *ngSwitchCase="\'a\'">when a1;</li>' +
'<li *ngSwitchCase="\'b\'">when b1;</li>' +
'<li *ngSwitchCase="\'a\'">when a2;</li>' +
'<li *ngSwitchCase="\'b\'">when b2;</li>' +
'<li *ngSwitchDefault>when default1;</li>' +
'<li *ngSwitchDefault>when default2;</li>' +
'</ul>';
fixture = createTestComponent(template);
detectChangesAndExpectText('when default1;when default2;');
getComponent().switchValue = 'a';
detectChangesAndExpectText('when a1;when a2;');
getComponent().switchValue = 'b';
detectChangesAndExpectText('when b1;when b2;');
});
it('should use === to match cases', () => {
const template =
'<ul [ngSwitch]="switchValue">' +
'<li *ngSwitchCase="1">when one</li>' +
'<li *ngSwitchDefault>when default</li>' +
'</ul>';
fixture = createTestComponent(template);
detectChangesAndExpectText('when default');
getComponent().switchValue = 1;
detectChangesAndExpectText('when one');
getComponent().switchValue = '1';
detectChangesAndExpectText('when default');
});
});
describe('when values changes', () => {
it('should switch amongst when values', () => {
const template =
'<ul [ngSwitch]="switchValue">' +
'<li *ngSwitchCase="when1">when 1;</li>' +
'<li *ngSwitchCase="when2">when 2;</li>' +
'<li *ngSwitchDefault>when default;</li>' +
'</ul>';
fixture = createTestComponent(template);
getComponent().when1 = 'a';
getComponent().when2 = 'b';
getComponent().switchValue = 'a';
detectChangesAndExpectText('when 1;');
getComponent().switchValue = 'b';
detectChangesAndExpectText('when 2;');
getComponent().switchValue = 'c';
detectChangesAndExpectText('when default;');
getComponent().when1 = 'c';
detectChangesAndExpectText('when 1;');
getComponent().when1 = 'd';
detectChangesAndExpectText('when default;');
});
});
it('should be available as standalone directives', () => {
@Component({
selector: 'test-component',
imports: [NgSwitch, NgSwitchCase, NgSwitchDefault],
template:
'<ul [ngSwitch]="switchValue">' +
'<li *ngSwitchCase="\'a\'">when a</li>' +
'<li *ngSwitchDefault>when default</li>' +
'</ul>',
standalone: true,
})
class TestComponent {
switchValue = 'a';
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('when a');
fixture.componentInstance.switchValue = 'b';
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('when default');
fixture.componentInstance.switchValue = 'c';
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('when default');
});
describe('corner cases', () => {
it('should not create the default case if another case matches', () => {
const log: string[] = [];
@Directive({
selector: '[test]',
standalone: false,
})
class TestDirective {
constructor(@Attribute('test') test: string) {
log.push(test);
}
}
const template =
'<div [ngSwitch]="switchValue">' +
'<div *ngSwitchCase="\'a\'" test="aCase"></div>' +
'<div *ngSwitchDefault test="defaultCase"></div>' +
'</div>';
TestBed.configureTestingModule({declarations: [TestDirective]});
const fixture = createTestComponent(template);
fixture.componentInstance.switchValue = 'a';
fixture.detectChanges();
expect(log).toEqual(['aCase']);
});
it('should create the default case if there is no other case', () => {
const template =
'<ul [ngSwitch]="switchValue">' +
'<li *ngSwitchDefault>when default1;</li>' +
'<li *ngSwitchDefault>when default2;</li>' +
'</ul>';
fixture = createTestComponent(template);
detectChangesAndExpectText('when default1;when default2;');
});
it('should allow defaults before cases', () => {
const template =
'<ul [ngSwitch]="switchValue">' +
'<li *ngSwitchDefault>when default1;</li>' +
'<li *ngSwitchDefault>when default2;</li>' +
'<li *ngSwitchCase="\'a\'">when a1;</li>' +
'<li *ngSwitchCase="\'b\'">when b1;</li>' +
'<li *ngSwitchCase="\'a\'">when a2;</li>' +
'<li *ngSwitchCase="\'b\'">when b2;</li>' +
'</ul>';
fixture = createTestComponent(template);
detectChangesAndExpectText('when default1;when default2;');
getComponent().switchValue = 'a';
detectChangesAndExpectText('when a1;when a2;');
getComponent().switchValue = 'b';
detectChangesAndExpectText('when b1;when b2;');
});
it('should throw error when ngSwitchCase is used outside of ngSwitch', waitForAsync(() => {
const template = '<div [ngSwitch]="switchValue"></div>' + '<div *ngSwitchCase="\'a\'"></div>';
expect(() => createTestComponent(template)).toThrowError(
'NG02000: An element with the "ngSwitchCase" attribute (matching the "NgSwitchCase" directive) must be located inside an element with the "ngSwitch" attribute (matching "NgSwitch" directive)',
);
}));
it('should throw error when ngSwitchDefault is used outside of ngSwitch', waitForAsync(() => {
const template = '<div [ngSwitch]="switchValue"></div>' + '<div *ngSwitchDefault></div>';
expect(() => createTestComponent(template)).toThrowError(
'NG02000: An element with the "ngSwitchDefault" attribute (matching the "NgSwitchDefault" directive) must be located inside an element with the "ngSwitch" attribute (matching "NgSwitch" directive)',
);
}));
it('should support nested NgSwitch on ng-container with ngTemplateOutlet', () => {
fixture = TestBed.createComponent(ComplexComponent);
detectChangesAndExpectText('Foo');
fixture.componentInstance.state = 'case2';
detectChangesAndExpectText('Bar');
fixture.componentInstance.state = 'notACase';
detectChangesAndExpectText('Default');
fixture.componentInstance.state = 'case1';
detectChangesAndExpectText('Foo');
});
});
}); | {
"end_byte": 8682,
"start_byte": 529,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_switch_spec.ts"
} |
angular/packages/common/test/directives/ng_switch_spec.ts_8684_10150 | @Component({
selector: 'test-cmp',
template: '',
standalone: false,
})
class TestComponent {
switchValue: any = null;
when1: any = null;
when2: any = null;
}
@Component({
selector: 'complex-cmp',
template: `
<div [ngSwitch]="state">
<ng-container *ngSwitchCase="'case1'" [ngSwitch]="true">
<ng-container *ngSwitchCase="true" [ngTemplateOutlet]="foo"></ng-container>
<span *ngSwitchDefault>Should never render</span>
</ng-container>
<ng-container *ngSwitchCase="'case2'" [ngSwitch]="true">
<ng-container *ngSwitchCase="true" [ngTemplateOutlet]="bar"></ng-container>
<span *ngSwitchDefault>Should never render</span>
</ng-container>
<ng-container *ngSwitchDefault [ngSwitch]="false">
<ng-container *ngSwitchCase="true" [ngTemplateOutlet]="foo"></ng-container>
<span *ngSwitchDefault>Default</span>
</ng-container>
</div>
<ng-template #foo>
<span>Foo</span>
</ng-template>
<ng-template #bar>
<span>Bar</span>
</ng-template>
`,
standalone: false,
})
class ComplexComponent {
@ViewChild('foo', {static: true}) foo!: TemplateRef<any>;
@ViewChild('bar', {static: true}) bar!: TemplateRef<any>;
state: string = 'case1';
}
function createTestComponent(template: string): ComponentFixture<TestComponent> {
return TestBed.overrideComponent(TestComponent, {set: {template: template}}).createComponent(
TestComponent,
);
} | {
"end_byte": 10150,
"start_byte": 8684,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_switch_spec.ts"
} |
angular/packages/common/test/directives/ng_style_spec.ts_0_378 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {CommonModule, NgStyle} from '@angular/common';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; | {
"end_byte": 378,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_style_spec.ts"
} |
angular/packages/common/test/directives/ng_style_spec.ts_380_8864 | describe('NgStyle', () => {
let fixture: ComponentFixture<TestComponent>;
const supportsCssVariables =
typeof getComputedStyle !== 'undefined' &&
typeof CSS !== 'undefined' &&
typeof CSS.supports !== 'undefined' &&
CSS.supports('color', 'var(--fake-var)');
function getComponent(): TestComponent {
return fixture.componentInstance;
}
function expectNativeEl(fixture: ComponentFixture<any>): any {
return expect(fixture.debugElement.children[0].nativeElement);
}
afterEach(() => {
fixture = null!;
});
beforeEach(() => {
TestBed.configureTestingModule({declarations: [TestComponent], imports: [CommonModule]});
});
it('should add styles specified in an object literal', waitForAsync(() => {
const template = `<div [ngStyle]="{'max-width': '40px'}"></div>`;
fixture = createTestComponent(template);
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'max-width': '40px'});
}));
it('should add and change styles specified in an object expression', waitForAsync(() => {
const template = `<div [ngStyle]="expr"></div>`;
fixture = createTestComponent(template);
getComponent().expr = {'max-width': '40px'};
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'max-width': '40px'});
let expr = getComponent().expr;
expr['max-width'] = '30%';
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'max-width': '30%'});
}));
it('should remove styles with a null expression', waitForAsync(() => {
const template = `<div [ngStyle]="expr"></div>`;
fixture = createTestComponent(template);
getComponent().expr = {'max-width': '40px'};
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'max-width': '40px'});
getComponent().expr = null;
fixture.detectChanges();
expectNativeEl(fixture).not.toHaveCssStyle('max-width');
}));
it('should remove styles with an undefined expression', waitForAsync(() => {
const template = `<div [ngStyle]="expr"></div>`;
fixture = createTestComponent(template);
getComponent().expr = {'max-width': '40px'};
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'max-width': '40px'});
getComponent().expr = undefined;
fixture.detectChanges();
expectNativeEl(fixture).not.toHaveCssStyle('max-width');
}));
it('should add and remove styles specified using style.unit notation', waitForAsync(() => {
const template = `<div [ngStyle]="{'max-width.px': expr}"></div>`;
fixture = createTestComponent(template);
getComponent().expr = '40';
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'max-width': '40px'});
getComponent().expr = null;
fixture.detectChanges();
expectNativeEl(fixture).not.toHaveCssStyle('max-width');
}));
// https://github.com/angular/angular/issues/21064
it('should add and remove styles which names are not dash-cased', waitForAsync(() => {
fixture = createTestComponent(`<div [ngStyle]="{'color': expr}"></div>`);
getComponent().expr = 'green';
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'color': 'green'});
getComponent().expr = null;
fixture.detectChanges();
expectNativeEl(fixture).not.toHaveCssStyle('color');
}));
it('should update styles using style.unit notation when unit changes', waitForAsync(() => {
const template = `<div [ngStyle]="expr"></div>`;
fixture = createTestComponent(template);
getComponent().expr = {'max-width.px': '40'};
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'max-width': '40px'});
getComponent().expr = {'max-width.em': '40'};
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'max-width': '40em'});
}));
// keyValueDiffer is sensitive to key order #9115
it('should change styles specified in an object expression', waitForAsync(() => {
const template = `<div [ngStyle]="expr"></div>`;
fixture = createTestComponent(template);
getComponent().expr = {
// height, width order is important here
height: '10px',
width: '10px',
};
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'height': '10px', 'width': '10px'});
getComponent().expr = {
// width, height order is important here
width: '5px',
height: '5px',
};
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'height': '5px', 'width': '5px'});
}));
it('should remove styles when deleting a key in an object expression', waitForAsync(() => {
const template = `<div [ngStyle]="expr"></div>`;
fixture = createTestComponent(template);
getComponent().expr = {'max-width': '40px'};
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'max-width': '40px'});
delete getComponent().expr['max-width'];
fixture.detectChanges();
expectNativeEl(fixture).not.toHaveCssStyle('max-width');
}));
it('should co-operate with the style attribute', waitForAsync(() => {
const template = `<div style="font-size: 12px" [ngStyle]="expr"></div>`;
fixture = createTestComponent(template);
getComponent().expr = {'max-width': '40px'};
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'max-width': '40px', 'font-size': '12px'});
delete getComponent().expr['max-width'];
fixture.detectChanges();
expectNativeEl(fixture).not.toHaveCssStyle('max-width');
expectNativeEl(fixture).toHaveCssStyle({'font-size': '12px'});
}));
it('should co-operate with the style.[styleName]="expr" special-case in the compiler', waitForAsync(() => {
const template = `<div [style.font-size.px]="12" [ngStyle]="expr"></div>`;
fixture = createTestComponent(template);
getComponent().expr = {'max-width': '40px'};
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'max-width': '40px', 'font-size': '12px'});
delete getComponent().expr['max-width'];
fixture.detectChanges();
expectNativeEl(fixture).not.toHaveCssStyle('max-width');
expectNativeEl(fixture).toHaveCssStyle({'font-size': '12px'});
}));
it('should not write to the native node unless the bound expression has changed', () => {
const template = `<div [ngStyle]="{'color': expr}"></div>`;
fixture = createTestComponent(template);
fixture.componentInstance.expr = 'red';
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'color': 'red'});
// Overwrite native styles so that we can check if ngStyle has performed DOM manupulation to
// update it.
fixture.debugElement.children[0].nativeElement.style.color = 'blue';
fixture.detectChanges();
// Assert that the style hasn't been updated
expectNativeEl(fixture).toHaveCssStyle({'color': 'blue'});
fixture.componentInstance.expr = 'yellow';
fixture.detectChanges();
// Assert that the style has changed now that the model has changed
expectNativeEl(fixture).toHaveCssStyle({'color': 'yellow'});
});
it('should correctly update style with units (.px) when the model is set to number', () => {
const template = `<div [ngStyle]="{'width.px': expr}"></div>`;
fixture = createTestComponent(template);
fixture.componentInstance.expr = 400;
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'width': '400px'});
});
it('should handle CSS variables', () => {
if (!supportsCssVariables) {
return;
}
const template = `<div style="width: var(--width)" [ngStyle]="{'--width': expr}"></div>`;
fixture = createTestComponent(template);
fixture.componentInstance.expr = '100px';
fixture.detectChanges();
const target: HTMLElement = fixture.nativeElement.querySelector('div');
expect(getComputedStyle(target).getPropertyValue('width')).toEqual('100px');
});
it('should be available as a standalone directive', () => {
@Component({
selector: 'test-component',
imports: [NgStyle],
template: `<div [ngStyle]="{'width.px': expr}"></div>`,
standalone: true,
})
class TestComponent {
expr = 400;
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'width': '400px'});
});
});
@Component({
selector: 'test-cmp',
template: '',
standalone: false,
})
class TestComponent {
expr: any;
} | {
"end_byte": 8864,
"start_byte": 380,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_style_spec.ts"
} |
angular/packages/common/test/directives/ng_style_spec.ts_8866_9069 | function createTestComponent(template: string): ComponentFixture<TestComponent> {
return TestBed.overrideComponent(TestComponent, {set: {template: template}}).createComponent(
TestComponent,
);
} | {
"end_byte": 9069,
"start_byte": 8866,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_style_spec.ts"
} |
angular/packages/common/test/directives/ng_if_spec.ts_0_529 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {CommonModule, NgIf, ɵgetDOM as getDOM} from '@angular/common';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser/src/dom/debug/by';
import {expect} from '@angular/platform-browser/testing/src/matchers';
| {
"end_byte": 529,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_if_spec.ts"
} |
angular/packages/common/test/directives/ng_if_spec.ts_531_9786 | escribe('ngIf directive', () => {
let fixture: ComponentFixture<any>;
function getComponent(): TestComponent {
return fixture.componentInstance;
}
afterEach(() => {
fixture = null!;
});
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestComponent],
imports: [CommonModule],
});
});
it('should work in a template attribute', waitForAsync(() => {
const template = '<span *ngIf="booleanCondition">hello</span>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(1);
expect(fixture.nativeElement).toHaveText('hello');
}));
it('should work on a template element', waitForAsync(() => {
const template = '<ng-template [ngIf]="booleanCondition">hello2</ng-template>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('hello2');
}));
it('should toggle node when condition changes', waitForAsync(() => {
const template = '<span *ngIf="booleanCondition">hello</span>';
fixture = createTestComponent(template);
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(0);
expect(fixture.nativeElement).toHaveText('');
getComponent().booleanCondition = true;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(1);
expect(fixture.nativeElement).toHaveText('hello');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(0);
expect(fixture.nativeElement).toHaveText('');
}));
it('should handle nested if correctly', waitForAsync(() => {
const template =
'<div *ngIf="booleanCondition"><span *ngIf="nestedBooleanCondition">hello</span></div>';
fixture = createTestComponent(template);
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(0);
expect(fixture.nativeElement).toHaveText('');
getComponent().booleanCondition = true;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(1);
expect(fixture.nativeElement).toHaveText('hello');
getComponent().nestedBooleanCondition = false;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(0);
expect(fixture.nativeElement).toHaveText('');
getComponent().nestedBooleanCondition = true;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(1);
expect(fixture.nativeElement).toHaveText('hello');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(0);
expect(fixture.nativeElement).toHaveText('');
}));
it('should update several nodes with if', waitForAsync(() => {
const template =
'<span *ngIf="numberCondition + 1 >= 2">helloNumber</span>' +
'<span *ngIf="stringCondition == \'foo\'">helloString</span>' +
'<span *ngIf="functionCondition(stringCondition, numberCondition)">helloFunction</span>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(3);
expect(fixture.nativeElement.textContent).toEqual('helloNumberhelloStringhelloFunction');
getComponent().numberCondition = 0;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(1);
expect(fixture.nativeElement).toHaveText('helloString');
getComponent().numberCondition = 1;
getComponent().stringCondition = 'bar';
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(1);
expect(fixture.nativeElement).toHaveText('helloNumber');
}));
it('should not add the element twice if the condition goes from truthy to truthy', waitForAsync(() => {
const template = '<span *ngIf="numberCondition">hello</span>';
fixture = createTestComponent(template);
fixture.detectChanges();
let els = fixture.debugElement.queryAll(By.css('span'));
expect(els.length).toEqual(1);
els[0].nativeElement.classList.add('marker');
expect(fixture.nativeElement).toHaveText('hello');
getComponent().numberCondition = 2;
fixture.detectChanges();
els = fixture.debugElement.queryAll(By.css('span'));
expect(els.length).toEqual(1);
expect(els[0].nativeElement.classList.contains('marker')).toBe(true);
expect(fixture.nativeElement).toHaveText('hello');
}));
describe('then/else templates', () => {
it('should support else', waitForAsync(() => {
const template =
'<span *ngIf="booleanCondition; else elseBlock">TRUE</span>' +
'<ng-template #elseBlock>FALSE</ng-template>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('TRUE');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('FALSE');
}));
it('should support then and else', waitForAsync(() => {
const template =
'<span *ngIf="booleanCondition; then thenBlock; else elseBlock">IGNORE</span>' +
'<ng-template #thenBlock>THEN</ng-template>' +
'<ng-template #elseBlock>ELSE</ng-template>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('THEN');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('ELSE');
}));
it('should support removing the then/else templates', () => {
const template = `<span *ngIf="booleanCondition;
then nestedBooleanCondition ? tplRef : null;
else nestedBooleanCondition ? tplRef : null"></span>
<ng-template #tplRef>Template</ng-template>`;
fixture = createTestComponent(template);
const comp = fixture.componentInstance;
// then template
comp.booleanCondition = true;
comp.nestedBooleanCondition = true;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('Template');
comp.nestedBooleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('');
// else template
comp.booleanCondition = true;
comp.nestedBooleanCondition = true;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('Template');
comp.nestedBooleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('');
});
it('should support dynamic else', waitForAsync(() => {
const template =
'<span *ngIf="booleanCondition; else nestedBooleanCondition ? b1 : b2">TRUE</span>' +
'<ng-template #b1>FALSE1</ng-template>' +
'<ng-template #b2>FALSE2</ng-template>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('TRUE');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('FALSE1');
getComponent().nestedBooleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('FALSE2');
}));
it('should support binding to variable using let', waitForAsync(() => {
const template =
'<span *ngIf="booleanCondition; else elseBlock; let v">{{v}}</span>' +
'<ng-template #elseBlock let-v>{{v}}</ng-template>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('true');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('false');
}));
it('should support binding to variable using as', waitForAsync(() => {
const template =
'<span *ngIf="booleanCondition as v; else elseBlock">{{v}}</span>' +
'<ng-template #elseBlock let-v>{{v}}</ng-template>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('true');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('false');
}));
it('should be available as a standalone directive', () => {
@Component({
selector: 'test-component',
imports: [NgIf],
template: `
<div *ngIf="true">Hello</div>
<div *ngIf="false">World</div>
`,
standalone: true,
})
class TestComponent {}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('Hello');
expect(fixture.nativeElement.textContent).not.toBe('World');
});
});
| {
"end_byte": 9786,
"start_byte": 531,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_if_spec.ts"
} |
angular/packages/common/test/directives/ng_if_spec.ts_9790_11150 | escribe('Type guarding', () => {
it('should throw when then block is not template', waitForAsync(() => {
const template =
'<span *ngIf="booleanCondition; then thenBlock">IGNORE</span>' +
'<div #thenBlock>THEN</div>';
fixture = createTestComponent(template);
expect(() => fixture.detectChanges()).toThrowError(
/ngIfThen must be a TemplateRef, but received/,
);
}));
it('should throw when else block is not template', waitForAsync(() => {
const template =
'<span *ngIf="booleanCondition; else elseBlock">IGNORE</span>' +
'<div #elseBlock>ELSE</div>';
fixture = createTestComponent(template);
expect(() => fixture.detectChanges()).toThrowError(
/ngIfElse must be a TemplateRef, but received/,
);
}));
});
});
@Component({
selector: 'test-cmp',
template: '',
standalone: false,
})
class TestComponent {
booleanCondition: boolean = true;
nestedBooleanCondition: boolean = true;
numberCondition: number = 1;
stringCondition: string = 'foo';
functionCondition: Function = (s: any, n: any): boolean => s == 'foo' && n == 1;
}
function createTestComponent(template: string): ComponentFixture<TestComponent> {
return TestBed.overrideComponent(TestComponent, {set: {template: template}}).createComponent(
TestComponent,
);
}
| {
"end_byte": 11150,
"start_byte": 9790,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_if_spec.ts"
} |
angular/packages/common/test/directives/ng_component_outlet_spec.ts_0_738 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {CommonModule} from '@angular/common';
import {NgComponentOutlet} from '@angular/common/src/directives/ng_component_outlet';
import {
Compiler,
Component,
ComponentRef,
Inject,
InjectionToken,
Injector,
Input,
NgModule,
NgModuleFactory,
NO_ERRORS_SCHEMA,
Optional,
QueryList,
TemplateRef,
Type,
ViewChild,
ViewChildren,
ViewContainerRef,
} from '@angular/core';
import {TestBed, waitForAsync} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers'; | {
"end_byte": 738,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_component_outlet_spec.ts"
} |
angular/packages/common/test/directives/ng_component_outlet_spec.ts_740_11235 | describe('insert/remove', () => {
beforeEach(() => {
TestBed.configureTestingModule({imports: [TestModule]});
});
it('should do nothing if component is null', waitForAsync(() => {
const template = `<ng-template *ngComponentOutlet="currentComponent"></ng-template>`;
TestBed.overrideComponent(TestComponent, {set: {template: template}});
let fixture = TestBed.createComponent(TestComponent);
fixture.componentInstance.currentComponent = null;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('');
}));
it('should insert content specified by a component', waitForAsync(() => {
let fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('');
fixture.componentInstance.currentComponent = InjectedComponent;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('foo');
}));
it('should emit a ComponentRef once a component was created', waitForAsync(() => {
let fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('');
fixture.componentInstance.cmpRef = undefined;
fixture.componentInstance.currentComponent = InjectedComponent;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('foo');
expect(fixture.componentInstance.cmpRef).toBeInstanceOf(ComponentRef);
expect(fixture.componentInstance.cmpRef!.instance).toBeInstanceOf(InjectedComponent);
}));
it('should clear view if component becomes null', waitForAsync(() => {
let fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('');
fixture.componentInstance.currentComponent = InjectedComponent;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('foo');
fixture.componentInstance.currentComponent = null;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('');
}));
it('should swap content if component changes', waitForAsync(() => {
let fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('');
fixture.componentInstance.currentComponent = InjectedComponent;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('foo');
fixture.componentInstance.currentComponent = InjectedComponentAgain;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('bar');
}));
it('should use the injector, if one supplied', waitForAsync(() => {
let fixture = TestBed.createComponent(TestComponent);
const uniqueValue = {};
fixture.componentInstance.currentComponent = InjectedComponent;
fixture.componentInstance.injector = Injector.create({
providers: [{provide: TEST_TOKEN, useValue: uniqueValue}],
parent: fixture.componentRef.injector,
});
fixture.detectChanges();
let cmpRef: ComponentRef<InjectedComponent> = fixture.componentInstance.cmpRef!;
expect(cmpRef).toBeInstanceOf(ComponentRef);
expect(cmpRef.instance).toBeInstanceOf(InjectedComponent);
expect(cmpRef.instance.testToken).toBe(uniqueValue);
}));
it('should resolve with an injector', waitForAsync(() => {
let fixture = TestBed.createComponent(TestComponent);
// We are accessing a ViewChild (ngComponentOutlet) before change detection has run
fixture.componentInstance.cmpRef = undefined;
fixture.componentInstance.currentComponent = InjectedComponent;
fixture.detectChanges();
let cmpRef: ComponentRef<InjectedComponent> = fixture.componentInstance.cmpRef!;
expect(cmpRef).toBeInstanceOf(ComponentRef);
expect(cmpRef.instance).toBeInstanceOf(InjectedComponent);
expect(cmpRef.instance.testToken).toBeNull();
}));
it('should render projectable nodes, if supplied', waitForAsync(() => {
const template = `<ng-template>projected foo</ng-template>${TEST_CMP_TEMPLATE}`;
TestBed.overrideComponent(TestComponent, {set: {template: template}}).configureTestingModule({
schemas: [NO_ERRORS_SCHEMA],
});
TestBed.overrideComponent(InjectedComponent, {
set: {template: `<ng-content></ng-content>`},
}).configureTestingModule({schemas: [NO_ERRORS_SCHEMA]});
let fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('');
fixture.componentInstance.currentComponent = InjectedComponent;
fixture.componentInstance.projectables = [
fixture.componentInstance.vcRef.createEmbeddedView(fixture.componentInstance.tplRefs.first)
.rootNodes,
];
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('projected foo');
}));
it('should resolve components from other modules, if supplied as an NgModuleFactory', waitForAsync(() => {
const compiler = TestBed.inject(Compiler);
let fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('');
fixture.componentInstance.ngModuleFactory = compiler.compileModuleSync(TestModule2);
fixture.componentInstance.currentComponent = Module2InjectedComponent;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('baz');
}));
it('should resolve components from other modules, if supplied as an NgModule class reference', waitForAsync(() => {
let fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('');
fixture.componentInstance.ngModule = TestModule2;
fixture.componentInstance.currentComponent = Module2InjectedComponent;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('baz');
}));
it('should clean up moduleRef, if supplied as an NgModuleFactory', waitForAsync(() => {
const compiler = TestBed.inject(Compiler);
const fixture = TestBed.createComponent(TestComponent);
fixture.componentInstance.ngModuleFactory = compiler.compileModuleSync(TestModule2);
fixture.componentInstance.currentComponent = Module2InjectedComponent;
fixture.detectChanges();
const moduleRef = fixture.componentInstance.ngComponentOutlet?.['_moduleRef']!;
spyOn(moduleRef, 'destroy').and.callThrough();
expect(moduleRef.destroy).not.toHaveBeenCalled();
fixture.destroy();
expect(moduleRef.destroy).toHaveBeenCalled();
}));
it('should clean up moduleRef, if supplied as an NgModule class reference', waitForAsync(() => {
const fixture = TestBed.createComponent(TestComponent);
fixture.componentInstance.ngModule = TestModule2;
fixture.componentInstance.currentComponent = Module2InjectedComponent;
fixture.detectChanges();
const moduleRef = fixture.componentInstance.ngComponentOutlet?.['_moduleRef']!;
spyOn(moduleRef, 'destroy').and.callThrough();
expect(moduleRef.destroy).not.toHaveBeenCalled();
fixture.destroy();
expect(moduleRef.destroy).toHaveBeenCalled();
}));
it("should not re-create moduleRef when it didn't actually change", waitForAsync(() => {
const compiler = TestBed.inject(Compiler);
const fixture = TestBed.createComponent(TestComponent);
fixture.componentInstance.ngModuleFactory = compiler.compileModuleSync(TestModule2);
fixture.componentInstance.currentComponent = Module2InjectedComponent;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('baz');
const moduleRef = fixture.componentInstance.ngComponentOutlet?.['_moduleRef'];
fixture.componentInstance.currentComponent = Module2InjectedComponent2;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('baz2');
expect(moduleRef).toBe(fixture.componentInstance.ngComponentOutlet?.['_moduleRef']);
}));
it('should re-create moduleRef when changed (NgModuleFactory)', waitForAsync(() => {
const compiler = TestBed.inject(Compiler);
const fixture = TestBed.createComponent(TestComponent);
fixture.componentInstance.ngModuleFactory = compiler.compileModuleSync(TestModule2);
fixture.componentInstance.currentComponent = Module2InjectedComponent;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('baz');
fixture.componentInstance.ngModuleFactory = compiler.compileModuleSync(TestModule3);
fixture.componentInstance.currentComponent = Module3InjectedComponent;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('bat');
}));
it('should re-create moduleRef when changed (NgModule class reference)', waitForAsync(() => {
const fixture = TestBed.createComponent(TestComponent);
fixture.componentInstance.ngModule = TestModule2;
fixture.componentInstance.currentComponent = Module2InjectedComponent;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('baz');
fixture.componentInstance.ngModule = TestModule3;
fixture.componentInstance.currentComponent = Module3InjectedComponent;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('bat');
}));
it('should override providers from parent component using custom injector', waitForAsync(() => {
TestBed.overrideComponent(InjectedComponent, {set: {template: 'Value: {{testToken}}'}});
TestBed.overrideComponent(TestComponent, {
set: {providers: [{provide: TEST_TOKEN, useValue: 'parent'}]},
});
const fixture = TestBed.createComponent(TestComponent);
fixture.componentInstance.currentComponent = InjectedComponent;
fixture.componentInstance.injector = Injector.create({
providers: [{provide: TEST_TOKEN, useValue: 'child'}],
parent: fixture.componentInstance.vcRef.injector,
});
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('Value: child');
}));
it('should be available as a standalone directive', () => {
@Component({
standalone: true,
template: 'Hello World',
})
class HelloWorldComp {}
@Component({
selector: 'test-component',
imports: [NgComponentOutlet],
template: ` <ng-container *ngComponentOutlet="component"></ng-container> `,
standalone: true,
})
class TestComponent {
component = HelloWorldComp;
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('Hello World');
});
}); | {
"end_byte": 11235,
"start_byte": 740,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_component_outlet_spec.ts"
} |
angular/packages/common/test/directives/ng_component_outlet_spec.ts_11237_17078 | describe('inputs', () => {
it('should be binding the component input', () => {
const fixture = TestBed.createComponent(TestInputsComponent);
fixture.componentInstance.currentComponent = ComponentWithInputs;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('foo: , bar: , baz: Baz');
fixture.componentInstance.inputs = {};
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('foo: , bar: , baz: Baz');
fixture.componentInstance.inputs = {foo: 'Foo', bar: 'Bar'};
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('foo: Foo, bar: Bar, baz: Baz');
fixture.componentInstance.inputs = {foo: 'Foo'};
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('foo: Foo, bar: , baz: Baz');
fixture.componentInstance.inputs = {foo: 'Foo', baz: null};
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('foo: Foo, bar: , baz: ');
fixture.componentInstance.inputs = undefined;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('foo: , bar: , baz: ');
});
it('should be binding the component input (with mutable inputs)', () => {
const fixture = TestBed.createComponent(TestInputsComponent);
fixture.componentInstance.currentComponent = ComponentWithInputs;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('foo: , bar: , baz: Baz');
fixture.componentInstance.inputs = {foo: 'Hello', bar: 'World'};
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('foo: Hello, bar: World, baz: Baz');
fixture.componentInstance.inputs['bar'] = 'Angular';
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('foo: Hello, bar: Angular, baz: Baz');
delete fixture.componentInstance.inputs['foo'];
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('foo: , bar: Angular, baz: Baz');
});
it('should be binding the component input (with component type change)', () => {
const fixture = TestBed.createComponent(TestInputsComponent);
fixture.componentInstance.currentComponent = ComponentWithInputs;
fixture.componentInstance.inputs = {foo: 'Foo', bar: 'Bar'};
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('foo: Foo, bar: Bar, baz: Baz');
fixture.componentInstance.currentComponent = AnotherComponentWithInputs;
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('[ANOTHER] foo: Foo, bar: Bar, baz: Baz');
});
});
const TEST_TOKEN = new InjectionToken('TestToken');
@Component({
selector: 'injected-component',
template: 'foo',
standalone: false,
})
class InjectedComponent {
constructor(@Optional() @Inject(TEST_TOKEN) public testToken: any) {}
}
@Component({
selector: 'injected-component-again',
template: 'bar',
standalone: false,
})
class InjectedComponentAgain {}
const TEST_CMP_TEMPLATE = `<ng-template *ngComponentOutlet="
currentComponent;
injector: injector;
inputs: inputs;
content: projectables;
ngModule: ngModule;
ngModuleFactory: ngModuleFactory;
"></ng-template>`;
@Component({
selector: 'test-cmp',
template: TEST_CMP_TEMPLATE,
standalone: false,
})
class TestComponent {
currentComponent: Type<unknown> | null = null;
injector?: Injector;
inputs?: Record<string, unknown>;
projectables?: any[][];
ngModule?: Type<unknown>;
ngModuleFactory?: NgModuleFactory<unknown>;
get cmpRef(): ComponentRef<any> | undefined {
return this.ngComponentOutlet?.['_componentRef'];
}
set cmpRef(value: ComponentRef<any> | undefined) {
if (this.ngComponentOutlet) {
this.ngComponentOutlet['_componentRef'] = value;
}
}
@ViewChildren(TemplateRef) tplRefs: QueryList<TemplateRef<any>> = new QueryList();
@ViewChild(NgComponentOutlet, {static: true}) ngComponentOutlet?: NgComponentOutlet;
constructor(public vcRef: ViewContainerRef) {}
}
@NgModule({
imports: [CommonModule],
declarations: [TestComponent, InjectedComponent, InjectedComponentAgain],
exports: [TestComponent, InjectedComponent, InjectedComponentAgain],
})
export class TestModule {}
@Component({
selector: 'module-2-injected-component',
template: 'baz',
standalone: false,
})
class Module2InjectedComponent {}
@Component({
selector: 'module-2-injected-component-2',
template: 'baz2',
standalone: false,
})
class Module2InjectedComponent2 {}
@NgModule({
imports: [CommonModule],
declarations: [Module2InjectedComponent, Module2InjectedComponent2],
exports: [Module2InjectedComponent, Module2InjectedComponent2],
})
export class TestModule2 {}
@Component({
selector: 'module-3-injected-component',
template: 'bat',
standalone: false,
})
class Module3InjectedComponent {}
@NgModule({
imports: [CommonModule],
declarations: [Module3InjectedComponent],
exports: [Module3InjectedComponent],
})
export class TestModule3 {}
@Component({
selector: 'cmp-with-inputs',
standalone: true,
template: `foo: {{ foo }}, bar: {{ bar }}, baz: {{ baz }}`,
})
class ComponentWithInputs {
@Input() foo?: any;
@Input() bar?: any;
@Input() baz?: any = 'Baz';
}
@Component({
selector: 'another-cmp-with-inputs',
standalone: true,
template: `[ANOTHER] foo: {{ foo }}, bar: {{ bar }}, baz: {{ baz }}`,
})
class AnotherComponentWithInputs {
@Input() foo?: any;
@Input() bar?: any;
@Input() baz?: any = 'Baz';
}
@Component({
selector: 'test-cmp',
standalone: true,
imports: [NgComponentOutlet],
template: `<ng-template *ngComponentOutlet="currentComponent; inputs: inputs"></ng-template>`,
})
class TestInputsComponent {
currentComponent: Type<unknown> | null = null;
inputs?: Record<string, unknown>;
} | {
"end_byte": 17078,
"start_byte": 11237,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_component_outlet_spec.ts"
} |
angular/packages/common/test/directives/ng_for_spec.ts_0_538 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {CommonModule, NgFor, NgForOf} from '@angular/common';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser/src/dom/debug/by';
import {expect} from '@angular/platform-browser/testing/src/matchers';
let thisArg: any; | {
"end_byte": 538,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_for_spec.ts"
} |
angular/packages/common/test/directives/ng_for_spec.ts_540_7784 | describe('ngFor', () => {
let fixture: ComponentFixture<any>;
function getComponent(): TestComponent {
return fixture.componentInstance;
}
function detectChangesAndExpectText(text: string): void {
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText(text);
}
afterEach(() => {
fixture = null as any;
});
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestComponent],
imports: [CommonModule],
});
});
it('should reflect initial elements', waitForAsync(() => {
fixture = createTestComponent();
detectChangesAndExpectText('1;2;');
}));
it('should reflect added elements', waitForAsync(() => {
fixture = createTestComponent();
fixture.detectChanges();
getComponent().items.push(3);
detectChangesAndExpectText('1;2;3;');
}));
it('should reflect removed elements', waitForAsync(() => {
fixture = createTestComponent();
fixture.detectChanges();
getComponent().items.splice(1, 1);
detectChangesAndExpectText('1;');
}));
it('should reflect moved elements', waitForAsync(() => {
fixture = createTestComponent();
fixture.detectChanges();
getComponent().items.splice(0, 1);
getComponent().items.push(1);
detectChangesAndExpectText('2;1;');
}));
it('should reflect a mix of all changes (additions/removals/moves)', waitForAsync(() => {
fixture = createTestComponent();
getComponent().items = [0, 1, 2, 3, 4, 5];
fixture.detectChanges();
getComponent().items = [6, 2, 7, 0, 4, 8];
detectChangesAndExpectText('6;2;7;0;4;8;');
}));
it('should iterate over an array of objects', waitForAsync(() => {
const template = '<ul><li *ngFor="let item of items">{{item["name"]}};</li></ul>';
fixture = createTestComponent(template);
// INIT
getComponent().items = [{'name': 'misko'}, {'name': 'shyam'}];
detectChangesAndExpectText('misko;shyam;');
// GROW
getComponent().items.push({'name': 'adam'});
detectChangesAndExpectText('misko;shyam;adam;');
// SHRINK
getComponent().items.splice(2, 1);
getComponent().items.splice(0, 1);
detectChangesAndExpectText('shyam;');
}));
it('should gracefully handle nulls', waitForAsync(() => {
const template = '<ul><li *ngFor="let item of null">{{item}};</li></ul>';
fixture = createTestComponent(template);
detectChangesAndExpectText('');
}));
it('should gracefully handle ref changing to null and back', waitForAsync(() => {
fixture = createTestComponent();
detectChangesAndExpectText('1;2;');
getComponent().items = null!;
detectChangesAndExpectText('');
getComponent().items = [1, 2, 3];
detectChangesAndExpectText('1;2;3;');
}));
it('should throw on non-iterable ref', waitForAsync(() => {
fixture = createTestComponent();
getComponent().items = <any>'whaaa';
expect(() => fixture.detectChanges()).toThrowError(
`NG02200: Cannot find a differ supporting object 'whaaa' of type 'string'. NgFor only supports binding to Iterables, such as Arrays. Find more at https://angular.dev/errors/NG02200`,
);
}));
it('should throw on non-iterable ref and suggest using an array ', waitForAsync(() => {
fixture = createTestComponent();
getComponent().items = <any>{'stuff': 'whaaa'};
expect(() => fixture.detectChanges()).toThrowError(
`NG02200: Cannot find a differ supporting object '\[object Object\]' of type 'object'. NgFor only supports binding to Iterables, such as Arrays. Did you mean to use the keyvalue pipe? Find more at https://angular.dev/errors/NG02200`,
);
}));
it('should throw on ref changing to string', waitForAsync(() => {
fixture = createTestComponent();
detectChangesAndExpectText('1;2;');
getComponent().items = <any>'whaaa';
expect(() => fixture.detectChanges()).toThrowError();
}));
it('should works with duplicates', waitForAsync(() => {
fixture = createTestComponent();
const a = new Foo();
getComponent().items = [a, a];
detectChangesAndExpectText('foo;foo;');
}));
it('should repeat over nested arrays', waitForAsync(() => {
const template =
'<div *ngFor="let item of items">' +
'<div *ngFor="let subitem of item">{{subitem}}-{{item.length}};</div>|' +
'</div>';
fixture = createTestComponent(template);
getComponent().items = [['a', 'b'], ['c']];
detectChangesAndExpectText('a-2;b-2;|c-1;|');
getComponent().items = [['e'], ['f', 'g']];
detectChangesAndExpectText('e-1;|f-2;g-2;|');
}));
it('should repeat over nested arrays with no intermediate element', waitForAsync(() => {
const template =
'<div *ngFor="let item of items">' +
'<div *ngFor="let subitem of item">{{subitem}}-{{item.length}};</div>' +
'</div>';
fixture = createTestComponent(template);
getComponent().items = [['a', 'b'], ['c']];
detectChangesAndExpectText('a-2;b-2;c-1;');
getComponent().items = [['e'], ['f', 'g']];
detectChangesAndExpectText('e-1;f-2;g-2;');
}));
it('should repeat over nested ngIf that are the last node in the ngFor template', waitForAsync(() => {
const template =
`<div *ngFor="let item of items; let i=index">` +
`<div>{{i}}|</div>` +
`<div *ngIf="i % 2 == 0">even|</div>` +
`</div>`;
fixture = createTestComponent(template);
const items = [1];
getComponent().items = items;
detectChangesAndExpectText('0|even|');
items.push(1);
detectChangesAndExpectText('0|even|1|');
items.push(1);
detectChangesAndExpectText('0|even|1|2|even|');
}));
it('should allow of saving the collection', waitForAsync(() => {
const template =
'<ul><li *ngFor="let item of items as collection; index as i">{{i}}/{{collection.length}} - {{item}};</li></ul>';
fixture = createTestComponent(template);
detectChangesAndExpectText('0/2 - 1;1/2 - 2;');
getComponent().items = [1, 2, 3];
detectChangesAndExpectText('0/3 - 1;1/3 - 2;2/3 - 3;');
}));
it('should display indices correctly', waitForAsync(() => {
const template = '<span *ngFor ="let item of items; let i=index">{{i.toString()}}</span>';
fixture = createTestComponent(template);
getComponent().items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
detectChangesAndExpectText('0123456789');
getComponent().items = [1, 2, 6, 7, 4, 3, 5, 8, 9, 0];
detectChangesAndExpectText('0123456789');
}));
it('should display count correctly', waitForAsync(() => {
const template = '<span *ngFor="let item of items; let len=count">{{len}}</span>';
fixture = createTestComponent(template);
getComponent().items = [0, 1, 2];
detectChangesAndExpectText('333');
getComponent().items = [4, 3, 2, 1, 0, -1];
detectChangesAndExpectText('666666');
}));
it('should display first item correctly', waitForAsync(() => {
const template =
'<span *ngFor="let item of items; let isFirst=first">{{isFirst.toString()}}</span>';
fixture = createTestComponent(template);
getComponent().items = [0, 1, 2];
detectChangesAndExpectText('truefalsefalse');
getComponent().items = [2, 1];
detectChangesAndExpectText('truefalse');
})); | {
"end_byte": 7784,
"start_byte": 540,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_for_spec.ts"
} |
angular/packages/common/test/directives/ng_for_spec.ts_7788_15317 | it('should display last item correctly', waitForAsync(() => {
const template =
'<span *ngFor="let item of items; let isLast=last">{{isLast.toString()}}</span>';
fixture = createTestComponent(template);
getComponent().items = [0, 1, 2];
detectChangesAndExpectText('falsefalsetrue');
getComponent().items = [2, 1];
detectChangesAndExpectText('falsetrue');
}));
it('should display even items correctly', waitForAsync(() => {
const template =
'<span *ngFor="let item of items; let isEven=even">{{isEven.toString()}}</span>';
fixture = createTestComponent(template);
getComponent().items = [0, 1, 2];
detectChangesAndExpectText('truefalsetrue');
getComponent().items = [2, 1];
detectChangesAndExpectText('truefalse');
}));
it('should display odd items correctly', waitForAsync(() => {
const template = '<span *ngFor="let item of items; let isOdd=odd">{{isOdd.toString()}}</span>';
fixture = createTestComponent(template);
getComponent().items = [0, 1, 2, 3];
detectChangesAndExpectText('falsetruefalsetrue');
getComponent().items = [2, 1];
detectChangesAndExpectText('falsetrue');
}));
it('should allow to use a custom template', waitForAsync(() => {
const template =
'<ng-container *ngFor="let item of items; template: tpl"></ng-container>' +
'<ng-template let-item let-i="index" #tpl><p>{{i}}: {{item}};</p></ng-template>';
fixture = createTestComponent(template);
getComponent().items = ['a', 'b', 'c'];
fixture.detectChanges();
detectChangesAndExpectText('0: a;1: b;2: c;');
}));
it('should use a default template if a custom one is null', waitForAsync(() => {
const template = `<ul><ng-container *ngFor="let item of items; template: null; let i=index">{{i}}: {{item}};</ng-container></ul>`;
fixture = createTestComponent(template);
getComponent().items = ['a', 'b', 'c'];
fixture.detectChanges();
detectChangesAndExpectText('0: a;1: b;2: c;');
}));
it('should use a custom template when both default and a custom one are present', waitForAsync(() => {
const template =
'<ng-container *ngFor="let item of items; template: tpl">{{i}};</ng-container>' +
'<ng-template let-item let-i="index" #tpl>{{i}}: {{item}};</ng-template>';
fixture = createTestComponent(template);
getComponent().items = ['a', 'b', 'c'];
fixture.detectChanges();
detectChangesAndExpectText('0: a;1: b;2: c;');
}));
describe('track by', () => {
it('should console.warn if trackBy is not a function', waitForAsync(() => {
// TODO(vicb): expect a warning message when we have a proper log service
const template = `<p *ngFor="let item of items; trackBy: value"></p>`;
fixture = createTestComponent(template);
fixture.componentInstance.value = 0;
fixture.detectChanges();
}));
it('should track by identity when trackBy is to `null` or `undefined`', waitForAsync(() => {
// TODO(vicb): expect no warning message when we have a proper log service
const template = `<p *ngFor="let item of items; trackBy: value">{{ item }}</p>`;
fixture = createTestComponent(template);
fixture.componentInstance.items = ['a', 'b', 'c'];
fixture.componentInstance.value = null;
detectChangesAndExpectText('abc');
fixture.componentInstance.value = undefined;
detectChangesAndExpectText('abc');
}));
it('should set the context to the component instance', waitForAsync(() => {
const template = `<p *ngFor="let item of items; trackBy: trackByContext.bind(this)"></p>`;
fixture = createTestComponent(template);
thisArg = null;
fixture.detectChanges();
expect(thisArg).toBe(getComponent());
}));
it('should not replace tracked items', waitForAsync(() => {
const template = `<p *ngFor="let item of items; trackBy: trackById; let i=index">{{items[i]}}</p>`;
fixture = createTestComponent(template);
const buildItemList = () => {
getComponent().items = [{'id': 'a'}];
fixture.detectChanges();
return fixture.debugElement.queryAll(By.css('p'))[0];
};
const firstP = buildItemList();
const finalP = buildItemList();
expect(finalP.nativeElement).toBe(firstP.nativeElement);
}));
it('should update implicit local variable on view', waitForAsync(() => {
const template = `<div *ngFor="let item of items; trackBy: trackById">{{item['color']}}</div>`;
fixture = createTestComponent(template);
getComponent().items = [{'id': 'a', 'color': 'blue'}];
detectChangesAndExpectText('blue');
getComponent().items = [{'id': 'a', 'color': 'red'}];
detectChangesAndExpectText('red');
}));
it('should move items around and keep them updated ', waitForAsync(() => {
const template = `<div *ngFor="let item of items; trackBy: trackById">{{item['color']}}</div>`;
fixture = createTestComponent(template);
getComponent().items = [
{'id': 'a', 'color': 'blue'},
{'id': 'b', 'color': 'yellow'},
];
detectChangesAndExpectText('blueyellow');
getComponent().items = [
{'id': 'b', 'color': 'orange'},
{'id': 'a', 'color': 'red'},
];
detectChangesAndExpectText('orangered');
}));
it('should handle added and removed items properly when tracking by index', waitForAsync(() => {
const template = `<div *ngFor="let item of items; trackBy: trackByIndex">{{item}}</div>`;
fixture = createTestComponent(template);
getComponent().items = ['a', 'b', 'c', 'd'];
fixture.detectChanges();
getComponent().items = ['e', 'f', 'g', 'h'];
fixture.detectChanges();
getComponent().items = ['e', 'f', 'h'];
detectChangesAndExpectText('efh');
}));
});
it('should be available as a standalone directive', () => {
@Component({
selector: 'test-component',
imports: [NgForOf],
template: ` <ng-container *ngFor="let item of items">{{ item }}|</ng-container> `,
standalone: true,
})
class TestComponent {
items = [1, 2, 3];
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('1|2|3|');
});
it('should be available as a standalone directive using an `NgFor` alias', () => {
@Component({
selector: 'test-component',
imports: [NgFor],
template: ` <ng-container *ngFor="let item of items">{{ item }}|</ng-container> `,
standalone: true,
})
class TestComponent {
items = [1, 2, 3];
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('1|2|3|');
});
});
class Foo {
toString() {
return 'foo';
}
}
@Component({
selector: 'test-cmp',
template: '',
standalone: false,
})
class TestComponent {
value: any;
items: any[] = [1, 2];
trackById(index: number, item: any): string {
return item['id'];
}
trackByIndex(index: number, item: any): number {
return index;
}
trackByContext(): void {
thisArg = this;
}
}
const TEMPLATE = '<div><span *ngFor="let item of items">{{item.toString()}};</span></div>';
function createTestComponent(template: string = TEMPLATE): ComponentFixture<TestComponent> {
return TestBed.overrideComponent(TestComponent, {set: {template: template}}).createComponent(
TestComponent,
);
} | {
"end_byte": 15317,
"start_byte": 7788,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_for_spec.ts"
} |
angular/packages/common/test/directives/non_bindable_spec.ts_0_2392 | /**
* @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} from '@angular/core';
import {ElementRef} from '@angular/core/src/linker/element_ref';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {hasClass} from '@angular/platform-browser/testing/src/browser_util';
import {expect} from '@angular/platform-browser/testing/src/matchers';
describe('non-bindable', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestComponent, TestDirective],
});
});
it('should not interpolate children', waitForAsync(() => {
const template = '<div>{{text}}<span ngNonBindable>{{text}}</span></div>';
const fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('foo{{text}}');
}));
it('should ignore directives on child nodes', waitForAsync(() => {
const template = '<div ngNonBindable><span id=child test-dec>{{text}}</span></div>';
const fixture = createTestComponent(template);
fixture.detectChanges();
// We must use getDOM().querySelector instead of fixture.query here
// since the elements inside are not compiled.
const span = fixture.nativeElement.querySelector('#child');
expect(hasClass(span, 'compiled')).toBeFalsy();
}));
it('should trigger directives on the same node', waitForAsync(() => {
const template = '<div><span id=child ngNonBindable test-dec>{{text}}</span></div>';
const fixture = createTestComponent(template);
fixture.detectChanges();
const span = fixture.nativeElement.querySelector('#child');
expect(hasClass(span, 'compiled')).toBeTruthy();
}));
});
@Directive({
selector: '[test-dec]',
standalone: false,
})
class TestDirective {
constructor(el: ElementRef) {
el.nativeElement.classList.add('compiled');
}
}
@Component({
selector: 'test-cmp',
template: '',
standalone: false,
})
class TestComponent {
text: string;
constructor() {
this.text = 'foo';
}
}
function createTestComponent(template: string): ComponentFixture<TestComponent> {
return TestBed.overrideComponent(TestComponent, {set: {template: template}}).createComponent(
TestComponent,
);
}
| {
"end_byte": 2392,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/non_bindable_spec.ts"
} |
angular/packages/common/test/directives/ng_plural_spec.ts_0_6152 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {CommonModule, NgLocalization, NgPlural, NgPluralCase} from '@angular/common';
import {Component, Injectable} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers';
describe('ngPlural', () => {
let fixture: ComponentFixture<any>;
function getComponent(): TestComponent {
return fixture.componentInstance;
}
function detectChangesAndExpectText<T>(text: string): void {
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText(text);
}
afterEach(() => {
fixture = null!;
});
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestComponent],
providers: [{provide: NgLocalization, useClass: TestLocalization}],
imports: [CommonModule],
});
});
it('should display the template according to the exact value', waitForAsync(() => {
const template =
'<ul [ngPlural]="switchValue">' +
'<ng-template ngPluralCase="=0"><li>you have no messages.</li></ng-template>' +
'<ng-template ngPluralCase="=1"><li>you have one message.</li></ng-template>' +
'</ul>';
fixture = createTestComponent(template);
getComponent().switchValue = 0;
detectChangesAndExpectText('you have no messages.');
getComponent().switchValue = 1;
detectChangesAndExpectText('you have one message.');
}));
it('should display the template according to the exact numeric value', waitForAsync(() => {
const template =
'<div>' +
'<ul [ngPlural]="switchValue">' +
'<ng-template ngPluralCase="0"><li>you have no messages.</li></ng-template>' +
'<ng-template ngPluralCase="1"><li>you have one message.</li></ng-template>' +
'</ul></div>';
fixture = createTestComponent(template);
getComponent().switchValue = 0;
detectChangesAndExpectText('you have no messages.');
getComponent().switchValue = 1;
detectChangesAndExpectText('you have one message.');
}));
// https://github.com/angular/angular/issues/9868
// https://github.com/angular/angular/issues/9882
it('should not throw when ngPluralCase contains expressions', waitForAsync(() => {
const template =
'<ul [ngPlural]="switchValue">' +
'<ng-template ngPluralCase="=0"><li>{{ switchValue }}</li></ng-template>' +
'</ul>';
fixture = createTestComponent(template);
getComponent().switchValue = 0;
expect(() => fixture.detectChanges()).not.toThrow();
}));
it('should be applicable to <ng-container> elements', waitForAsync(() => {
const template =
'<ng-container [ngPlural]="switchValue">' +
'<ng-template ngPluralCase="=0">you have no messages.</ng-template>' +
'<ng-template ngPluralCase="=1">you have one message.</ng-template>' +
'</ng-container>';
fixture = createTestComponent(template);
getComponent().switchValue = 0;
detectChangesAndExpectText('you have no messages.');
getComponent().switchValue = 1;
detectChangesAndExpectText('you have one message.');
}));
it('should display the template according to the category', waitForAsync(() => {
const template =
'<ul [ngPlural]="switchValue">' +
'<ng-template ngPluralCase="few"><li>you have a few messages.</li></ng-template>' +
'<ng-template ngPluralCase="many"><li>you have many messages.</li></ng-template>' +
'</ul>';
fixture = createTestComponent(template);
getComponent().switchValue = 2;
detectChangesAndExpectText('you have a few messages.');
getComponent().switchValue = 8;
detectChangesAndExpectText('you have many messages.');
}));
it('should default to other when no matches are found', waitForAsync(() => {
const template =
'<ul [ngPlural]="switchValue">' +
'<ng-template ngPluralCase="few"><li>you have a few messages.</li></ng-template>' +
'<ng-template ngPluralCase="other"><li>default message.</li></ng-template>' +
'</ul>';
fixture = createTestComponent(template);
getComponent().switchValue = 100;
detectChangesAndExpectText('default message.');
}));
it('should prioritize value matches over category matches', waitForAsync(() => {
const template =
'<ul [ngPlural]="switchValue">' +
'<ng-template ngPluralCase="few"><li>you have a few messages.</li></ng-template>' +
'<ng-template ngPluralCase="=2">you have two messages.</ng-template>' +
'</ul>';
fixture = createTestComponent(template);
getComponent().switchValue = 2;
detectChangesAndExpectText('you have two messages.');
getComponent().switchValue = 3;
detectChangesAndExpectText('you have a few messages.');
}));
});
it('should be available as a standalone directive', () => {
@Component({
selector: 'test-component',
imports: [NgPlural, NgPluralCase],
template:
'<ul [ngPlural]="switchValue">' +
'<ng-template ngPluralCase="=0"><li>no messages</li></ng-template>' +
'<ng-template ngPluralCase="=1"><li>one message</li></ng-template>' +
'</ul>',
standalone: true,
})
class TestComponent {
switchValue = 1;
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('one message');
});
@Injectable()
class TestLocalization extends NgLocalization {
override getPluralCategory(value: number): string {
if (value > 1 && value < 4) {
return 'few';
}
if (value >= 4 && value < 10) {
return 'many';
}
return 'other';
}
}
@Component({
selector: 'test-cmp',
template: '',
standalone: false,
})
class TestComponent {
switchValue: number | null = null;
}
function createTestComponent(template: string): ComponentFixture<TestComponent> {
return TestBed.overrideComponent(TestComponent, {set: {template: template}}).createComponent(
TestComponent,
);
}
| {
"end_byte": 6152,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/directives/ng_plural_spec.ts"
} |
angular/packages/common/test/image_loaders/image_loader_spec.ts_0_1708 | /**
* @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 {
IMAGE_LOADER,
ImageLoader,
ImageLoaderConfig,
provideNetlifyLoader,
} from '@angular/common/src/directives/ng_optimized_image';
import {provideCloudflareLoader} from '@angular/common/src/directives/ng_optimized_image/image_loaders/cloudflare_loader';
import {provideCloudinaryLoader} from '@angular/common/src/directives/ng_optimized_image/image_loaders/cloudinary_loader';
import {provideImageKitLoader} from '@angular/common/src/directives/ng_optimized_image/image_loaders/imagekit_loader';
import {provideImgixLoader} from '@angular/common/src/directives/ng_optimized_image/image_loaders/imgix_loader';
import {isValidPath} from '@angular/common/src/directives/ng_optimized_image/url';
import {RuntimeErrorCode} from '@angular/common/src/errors';
import {createEnvironmentInjector, EnvironmentInjector} from '@angular/core';
import {TestBed} from '@angular/core/testing';
const absoluteUrlError = (src: string, path: string) =>
`NG02959: Image loader has detected a \`<img>\` tag with an invalid ` +
`\`ngSrc\` attribute: ${src}. This image loader expects \`ngSrc\` ` +
`to be a relative URL - however the provided value is an absolute URL. ` +
`To fix this, provide \`ngSrc\` as a path relative to the base URL ` +
`configured for this loader (\`${path}\`).`;
const invalidPathError = (path: string, formats: string) =>
`NG02959: Image loader has detected an invalid path (\`${path}\`). ` +
`To fix this, supply a path using one of the following formats: ${formats}`; | {
"end_byte": 1708,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/image_loaders/image_loader_spec.ts"
} |
angular/packages/common/test/image_loaders/image_loader_spec.ts_1710_9405 | describe('Built-in image directive loaders', () => {
describe('Imgix loader', () => {
function createImgixLoader(path: string): ImageLoader {
const injector = createEnvironmentInjector(
[provideImgixLoader(path)],
TestBed.inject(EnvironmentInjector),
);
return injector.get(IMAGE_LOADER);
}
it('should construct an image loader with the given path', () => {
const path = 'https://somesite.imgix.net';
const loader = createImgixLoader(path);
const config = {src: 'img.png'};
expect(loader(config)).toBe(`${path}/img.png?auto=format`);
});
it('should handle a trailing forward slash on the path', () => {
const path = 'https://somesite.imgix.net';
const loader = createImgixLoader(`${path}/`);
const config = {src: 'img.png'};
expect(loader(config)).toBe(`${path}/img.png?auto=format`);
});
it('should handle a leading forward slash on the image src', () => {
const path = 'https://somesite.imgix.net';
const loader = createImgixLoader(path);
const config = {src: '/img.png'};
expect(loader(config)).toBe(`${path}/img.png?auto=format`);
});
it('should construct an image loader with the given path', () => {
const path = 'https://somesite.imgix.net';
const loader = createImgixLoader(path);
const config = {src: 'img.png', width: 100};
expect(loader(config)).toBe(`${path}/img.png?auto=format&w=100`);
});
it('should throw if an absolute URL is provided as a loader input', () => {
const path = 'https://somesite.imgix.net';
const src = 'https://angular.io/img.png';
const loader = createImgixLoader(path);
expect(() => loader({src})).toThrowError(absoluteUrlError(src, path));
});
it('should load a low quality image when a placeholder is requested', () => {
const path = 'https://somesite.imgix.net';
const loader = createImgixLoader(path);
const config = {src: 'img.png', isPlaceholder: true};
expect(loader(config)).toBe(`${path}/img.png?auto=format&q=20`);
});
});
describe('Cloudinary loader', () => {
function createCloudinaryLoader(path: string): ImageLoader {
const injector = createEnvironmentInjector(
[provideCloudinaryLoader(path)],
TestBed.inject(EnvironmentInjector),
);
return injector.get(IMAGE_LOADER);
}
it('should construct an image loader with the given path', () => {
const path = 'https://res.cloudinary.com/mysite';
const loader = createCloudinaryLoader(path);
expect(loader({src: 'img.png'})).toBe(`${path}/image/upload/f_auto,q_auto/img.png`);
expect(
loader({
src: 'marketing/img-2.png',
}),
).toBe(`${path}/image/upload/f_auto,q_auto/marketing/img-2.png`);
});
it('should load a low quality image when a placeholder is requested', () => {
const path = 'https://res.cloudinary.com/mysite';
const loader = createCloudinaryLoader(path);
const config = {src: 'img.png', isPlaceholder: true};
expect(loader(config)).toBe(`${path}/image/upload/f_auto,q_auto:low/img.png`);
});
describe('input validation', () => {
it('should throw if an absolute URL is provided as a loader input', () => {
const path = 'https://res.cloudinary.com/mysite';
const src = 'https://angular.io/img.png';
const loader = createCloudinaryLoader(path);
expect(() => loader({src})).toThrowError(absoluteUrlError(src, path));
});
it('should throw if the path is invalid', () => {
expect(() => provideCloudinaryLoader('my-cloudinary-account')).toThrowError(
invalidPathError(
'my-cloudinary-account',
'https://res.cloudinary.com/mysite or https://mysite.cloudinary.com ' +
'or https://subdomain.mysite.com',
),
);
});
it('should handle a trailing forward slash on the path', () => {
const path = 'https://res.cloudinary.com/mysite';
const loader = createCloudinaryLoader(`${path}/`);
expect(loader({src: 'img.png'})).toBe(`${path}/image/upload/f_auto,q_auto/img.png`);
});
it('should handle a leading forward slash on the image src', () => {
const path = 'https://res.cloudinary.com/mysite';
const loader = createCloudinaryLoader(path);
expect(loader({src: '/img.png'})).toBe(`${path}/image/upload/f_auto,q_auto/img.png`);
});
});
describe('config validation', () => {
it('should add the r_max cloudinary transformation to the URL when the rounded option is provided', () => {
const path = 'https://res.cloudinary.com/mysite';
const loader = createCloudinaryLoader(path);
expect(loader({src: '/img.png', loaderParams: {rounded: true}})).toBe(
`${path}/image/upload/f_auto,q_auto,r_max/img.png`,
);
});
});
});
describe('ImageKit loader', () => {
function createImageKitLoader(path: string): ImageLoader {
const injector = createEnvironmentInjector(
[provideImageKitLoader(path)],
TestBed.inject(EnvironmentInjector),
);
return injector.get(IMAGE_LOADER);
}
it('should construct an image loader with the given path', () => {
const path = 'https://ik.imageengine.io/imagetest';
const loader = createImageKitLoader(path);
expect(loader({src: 'img.png'})).toBe(`${path}/img.png`);
expect(loader({src: 'marketing/img-2.png'})).toBe(`${path}/marketing/img-2.png`);
});
it('should construct an image loader with the given path', () => {
const path = 'https://ik.imageengine.io/imagetest';
const loader = createImageKitLoader(path);
expect(loader({src: 'img.png', width: 100})).toBe(`${path}/tr:w-100/img.png`);
expect(loader({src: 'marketing/img-2.png', width: 200})).toBe(
`${path}/tr:w-200/marketing/img-2.png`,
);
});
it('should load a low quality image when a placeholder is requested', () => {
const path = 'https://ik.imageengine.io/imagetest';
const loader = createImageKitLoader(path);
let config: ImageLoaderConfig = {src: 'img.png', isPlaceholder: true};
expect(loader(config)).toBe(`${path}/tr:q-20/img.png`);
config = {src: 'img.png', isPlaceholder: true, width: 30};
expect(loader(config)).toBe(`${path}/tr:w-30,q-20/img.png`);
});
describe('input validation', () => {
it('should throw if an absolute URL is provided as a loader input', () => {
const path = 'https://ik.imageengine.io/imagetest';
const src = 'https://angular.io/img.png';
const loader = createImageKitLoader(path);
expect(() => loader({src})).toThrowError(absoluteUrlError(src, path));
});
it('should throw if the path is invalid', () => {
expect(() => provideImageKitLoader('my-imagekit-account')).toThrowError(
invalidPathError(
'my-imagekit-account',
'https://ik.imagekit.io/mysite or https://subdomain.mysite.com',
),
);
});
it('should handle a trailing forward slash on the path', () => {
const path = 'https://ik.imageengine.io/imagetest';
const loader = createImageKitLoader(`${path}/`);
expect(loader({src: 'img.png'})).toBe(`${path}/img.png`);
});
it('should handle a leading forward slash on the image src', () => {
const path = 'https://ik.imageengine.io/imagetest';
const loader = createImageKitLoader(path);
expect(loader({src: '/img.png'})).toBe(`${path}/img.png`);
});
});
}); | {
"end_byte": 9405,
"start_byte": 1710,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/image_loaders/image_loader_spec.ts"
} |
angular/packages/common/test/image_loaders/image_loader_spec.ts_9409_14810 | describe('Cloudflare loader', () => {
function createCloudflareLoader(path: string): ImageLoader {
const injector = createEnvironmentInjector(
[provideCloudflareLoader(path)],
TestBed.inject(EnvironmentInjector),
);
return injector.get(IMAGE_LOADER);
}
it('should construct an image loader with the given path', () => {
const loader = createCloudflareLoader('https://mysite.com');
let config = {src: 'img.png'};
expect(loader(config)).toBe('https://mysite.com/cdn-cgi/image/format=auto/img.png');
});
it('should construct an image loader with the given path', () => {
const loader = createCloudflareLoader('https://mysite.com');
const config = {src: 'img.png', width: 100};
expect(loader(config)).toBe('https://mysite.com/cdn-cgi/image/format=auto,width=100/img.png');
});
it('should throw if an absolute URL is provided as a loader input', () => {
const path = 'https://mysite.com';
const src = 'https://angular.io/img.png';
const loader = createCloudflareLoader(path);
expect(() => loader({src})).toThrowError(absoluteUrlError(src, path));
});
it('should load a low quality image when a placeholder is requested', () => {
const path = 'https://mysite.com';
const loader = createCloudflareLoader(path);
const config = {src: 'img.png', isPlaceholder: true};
expect(loader(config)).toBe(
'https://mysite.com/cdn-cgi/image/format=auto,quality=20/img.png',
);
});
});
describe('Netlify loader', () => {
function createNetlifyLoader(path?: string): ImageLoader {
const injector = createEnvironmentInjector(
[provideNetlifyLoader(path)],
TestBed.inject(EnvironmentInjector),
);
return injector.get(IMAGE_LOADER);
}
it('should construct an image loader with an empty path', () => {
const loader = createNetlifyLoader();
let config = {src: 'img.png'};
expect(loader(config)).toBe('/.netlify/images?url=%2Fimg.png');
});
it('should construct an image loader with the given path', () => {
const loader = createNetlifyLoader('https://mysite.com');
let config = {src: 'img.png'};
expect(loader(config)).toBe('https://mysite.com/.netlify/images?url=%2Fimg.png');
});
it('should construct an image loader with the given path', () => {
const loader = createNetlifyLoader('https://mysite.com');
const config = {src: 'img.png', width: 100};
expect(loader(config)).toBe('https://mysite.com/.netlify/images?url=%2Fimg.png&w=100');
});
it('should construct an image URL with custom options', () => {
const loader = createNetlifyLoader('https://mysite.com');
const config = {src: 'img.png', width: 100, loaderParams: {quality: 50}};
expect(loader(config)).toBe('https://mysite.com/.netlify/images?url=%2Fimg.png&w=100&q=50');
});
it('should construct an image with an absolute URL', () => {
const path = 'https://mysite.com';
const src = 'https://angular.io/img.png';
const loader = createNetlifyLoader(path);
expect(loader({src})).toBe(
'https://mysite.com/.netlify/images?url=https%3A%2F%2Fangular.io%2Fimg.png',
);
});
it('should warn if an unknown loader parameter is provided', () => {
const path = 'https://mysite.com';
const loader = createNetlifyLoader(path);
const config = {src: 'img.png', loaderParams: {unknown: 'value'}};
spyOn(console, 'warn');
expect(loader(config)).toBe('https://mysite.com/.netlify/images?url=%2Fimg.png');
expect(console.warn).toHaveBeenCalledWith(
`NG0${RuntimeErrorCode.INVALID_LOADER_ARGUMENTS}: The Netlify image loader has detected an \`<img>\` tag with the unsupported attribute "\`unknown\`".`,
);
});
it('should load a low quality image when a placeholder is requested', () => {
const path = 'https://mysite.com';
const loader = createNetlifyLoader(path);
const config = {src: 'img.png', isPlaceholder: true};
expect(loader(config)).toBe('https://mysite.com/.netlify/images?url=%2Fimg.png&q=20');
});
it('should not load a low quality image when a placeholder is requested with a quality param', () => {
const path = 'https://mysite.com';
const loader = createNetlifyLoader(path);
const config = {src: 'img.png', isPlaceholder: true, loaderParams: {quality: 50}};
expect(loader(config)).toBe('https://mysite.com/.netlify/images?url=%2Fimg.png&q=50');
});
});
describe('loader utils', () => {
it('should identify valid paths', () => {
expect(isValidPath('https://cdn.imageprovider.com/image-test')).toBe(true);
expect(isValidPath('https://cdn.imageprovider.com')).toBe(true);
expect(isValidPath('https://imageprovider.com')).toBe(true);
});
it('should reject empty paths', () => {
expect(isValidPath('')).toBe(false);
});
it('should reject path if it is not a URL', () => {
expect(isValidPath('myaccount')).toBe(false);
});
it('should reject path if it does not include a protocol', () => {
expect(isValidPath('myaccount.imageprovider.com')).toBe(false);
});
it('should reject path if is malformed', () => {
expect(isValidPath('somepa\th.imageprovider.com? few')).toBe(false);
});
});
}); | {
"end_byte": 14810,
"start_byte": 9409,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/image_loaders/image_loader_spec.ts"
} |
angular/packages/common/test/location/location_spec.ts_0_504 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
APP_BASE_HREF,
CommonModule,
Location,
LocationStrategy,
PathLocationStrategy,
PlatformLocation,
} from '@angular/common';
import {MockLocationStrategy, MockPlatformLocation} from '@angular/common/testing';
import {TestBed} from '@angular/core/testing';
const baseUrl = '/base'; | {
"end_byte": 504,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/location/location_spec.ts"
} |
angular/packages/common/test/location/location_spec.ts_506_10064 | describe('Location Class', () => {
describe('stripTrailingSlash', () => {
it('should strip single character slash', () => {
const input = '/';
expect(Location.stripTrailingSlash(input)).toBe('');
});
it('should normalize strip a trailing slash', () => {
const input = baseUrl + '/';
expect(Location.stripTrailingSlash(input)).toBe(baseUrl);
});
it('should ignore query params when stripping a slash', () => {
const input = baseUrl + '/?param=1';
expect(Location.stripTrailingSlash(input)).toBe(baseUrl + '?param=1');
});
it('should not remove slashes inside query params', () => {
const input = baseUrl + '?test/?=3';
expect(Location.stripTrailingSlash(input)).toBe(input);
});
it('should not remove slashes after a pound sign', () => {
const input = baseUrl + '#test/?=3';
expect(Location.stripTrailingSlash(input)).toBe(input);
});
});
describe('location.getState()', () => {
let location: Location;
beforeEach(() => {
TestBed.configureTestingModule({
teardown: {destroyAfterEach: true},
imports: [CommonModule],
providers: [
{provide: LocationStrategy, useClass: PathLocationStrategy},
{
provide: PlatformLocation,
useFactory: () => {
return new MockPlatformLocation();
},
},
{provide: Location, useClass: Location, deps: [LocationStrategy]},
],
});
location = TestBed.inject(Location);
});
it('should get the state object', () => {
expect(location.getState()).toBe(null);
location.go('/test', '', {foo: 'bar'});
expect(location.getState()).toEqual({foo: 'bar'});
});
it('should work after using back button', () => {
expect(location.getState()).toBe(null);
location.go('/test1', '', {url: 'test1'});
location.go('/test2', '', {url: 'test2'});
expect(location.getState()).toEqual({url: 'test2'});
location.back();
expect(location.getState()).toEqual({url: 'test1'});
});
it('should work after using forward button', () => {
expect(location.getState()).toBe(null);
location.go('/test1', '', {url: 'test1'});
location.go('/test2', '', {url: 'test2'});
expect(location.getState()).toEqual({url: 'test2'});
location.back();
expect(location.getState()).toEqual({url: 'test1'});
location.forward();
expect(location.getState()).toEqual({url: 'test2'});
});
it('should work after using location.historyGo()', () => {
expect(location.getState()).toBe(null);
location.go('/test1', '', {url: 'test1'});
location.go('/test2', '', {url: 'test2'});
location.go('/test3', '', {url: 'test3'});
expect(location.getState()).toEqual({url: 'test3'});
location.historyGo(-2);
expect(location.getState()).toEqual({url: 'test1'});
location.historyGo(2);
expect(location.getState()).toEqual({url: 'test3'});
location.go('/test3', '', {url: 'test4'});
location.historyGo(0);
expect(location.getState()).toEqual({url: 'test4'});
location.historyGo();
expect(location.getState()).toEqual({url: 'test4'});
// we are testing the behaviour of the `historyGo` method at the moment when the value of
// the relativePosition goes out of bounds.
// The result should be that the locationState does not change.
location.historyGo(100);
expect(location.getState()).toEqual({url: 'test4'});
location.historyGo(-100);
expect(location.getState()).toEqual({url: 'test4'});
location.back();
expect(location.getState()).toEqual({url: 'test3'});
});
});
describe('location.onUrlChange()', () => {
let location: Location;
let locationStrategy: MockLocationStrategy;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [CommonModule],
providers: [
{provide: LocationStrategy, useClass: MockLocationStrategy},
{
provide: PlatformLocation,
useFactory: () => {
return new MockPlatformLocation();
},
},
{provide: Location, useClass: Location, deps: [LocationStrategy]},
],
});
location = TestBed.inject(Location);
locationStrategy = TestBed.inject(LocationStrategy) as MockLocationStrategy;
});
it('should have onUrlChange method', () => {
expect(typeof location.onUrlChange).toBe('function');
});
it('should add registered functions to urlChangeListeners', () => {
function changeListener(url: string, state: unknown) {
return undefined;
}
expect((location as any)._urlChangeListeners.length).toBe(0);
location.onUrlChange(changeListener);
expect((location as any)._urlChangeListeners.length).toBe(1);
expect((location as any)._urlChangeListeners[0]).toEqual(changeListener);
});
it('should unregister a URL change listener and unsubscribe from URL changes when the root view is removed', () => {
const changeListener = jasmine.createSpy('changeListener');
const removeUrlChangeFn = location.onUrlChange(changeListener);
location.go('x');
expect(changeListener).toHaveBeenCalledTimes(1);
removeUrlChangeFn();
expect(changeListener).toHaveBeenCalledTimes(1);
location.onUrlChange((url: string, state: unknown) => {});
TestBed.resetTestingModule();
// Let's ensure that URL change listeners are unregistered when the root view is removed,
// tho the last returned `onUrlChange` function hasn't been invoked.
expect((location as any)._urlChangeListeners.length).toEqual(0);
expect((location as any)._urlChangeSubscription.closed).toEqual(true);
});
it('should only notify listeners once when multiple listeners are registered', () => {
let notificationCount = 0;
function incrementChangeListener(url: string, state: unknown) {
notificationCount += 1;
return undefined;
}
function noopChangeListener(url: string, state: unknown) {
return undefined;
}
location.onUrlChange(incrementChangeListener);
location.onUrlChange(noopChangeListener);
expect(notificationCount).toBe(0);
locationStrategy.simulatePopState('/test');
expect(notificationCount).toBe(1);
});
});
describe('location.normalize(url) should return only route', () => {
const basePath = '/en';
const route = '/go/to/there';
const url = basePath + route;
const getBaseHref = (origin: string) => origin + basePath + '/';
it('in case APP_BASE_HREF starts with http:', () => {
const origin = 'http://example.com';
const baseHref = getBaseHref(origin);
TestBed.configureTestingModule({providers: [{provide: APP_BASE_HREF, useValue: baseHref}]});
const location = TestBed.inject(Location);
expect(location.normalize(url)).toBe(route);
});
it('in case APP_BASE_HREF starts with https:', () => {
const origin = 'https://example.com';
const baseHref = getBaseHref(origin);
TestBed.configureTestingModule({providers: [{provide: APP_BASE_HREF, useValue: baseHref}]});
const location = TestBed.inject(Location);
expect(location.normalize(url)).toBe(route);
});
it('in case APP_BASE_HREF starts with no protocol', () => {
const origin = '//example.com';
const baseHref = getBaseHref(origin);
TestBed.configureTestingModule({providers: [{provide: APP_BASE_HREF, useValue: baseHref}]});
const location = TestBed.inject(Location);
expect(location.normalize(url)).toBe(route);
});
it('in case APP_BASE_HREF starts with no origin', () => {
const origin = '';
const baseHref = getBaseHref(origin);
TestBed.configureTestingModule({providers: [{provide: APP_BASE_HREF, useValue: baseHref}]});
const location = TestBed.inject(Location);
expect(location.normalize(url)).toBe(route);
});
});
describe('location.normalize(url) should return properly normalized url', () => {
it('in case url starts with the substring equals APP_BASE_HREF', () => {
const baseHref = '/en';
const path = '/enigma';
const queryParams = '?param1=123';
const matrixParams = ';param1=123';
const fragment = '#anchor1';
TestBed.configureTestingModule({providers: [{provide: APP_BASE_HREF, useValue: baseHref}]});
const location = TestBed.inject(Location);
expect(location.normalize(path)).toBe(path);
expect(location.normalize(baseHref)).toBe('');
expect(location.normalize(baseHref + path)).toBe(path);
expect(location.normalize(baseHref + queryParams)).toBe(queryParams);
expect(location.normalize(baseHref + matrixParams)).toBe(matrixParams);
expect(location.normalize(baseHref + fragment)).toBe(fragment);
});
it('in case APP_BASE_HREF contains characters that have special meaning in a regex', () => {
const baseHref = 'c:/users/name(test)/en';
const path = '/test-path';
TestBed.configureTestingModule({providers: [{provide: APP_BASE_HREF, useValue: baseHref}]});
const location = TestBed.inject(Location);
expect(location.normalize(path)).toBe(path);
expect(location.normalize(baseHref)).toBe('');
expect(location.normalize(baseHref + path)).toBe(path);
});
});
}); | {
"end_byte": 10064,
"start_byte": 506,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/location/location_spec.ts"
} |
angular/packages/common/test/location/provide_location_mocks_spec.ts_0_840 | /**
* @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 {Location, LocationStrategy} from '@angular/common';
import {MockLocationStrategy, provideLocationMocks, SpyLocation} from '@angular/common/testing';
import {TestBed} from '@angular/core/testing';
describe('provideLocationMocks() function', () => {
it('should mock Location and LocationStrategy classes', () => {
TestBed.configureTestingModule({providers: [provideLocationMocks()]});
const location = TestBed.inject(Location);
const locationStrategy = TestBed.inject(LocationStrategy);
expect(location).toBeInstanceOf(SpyLocation);
expect(locationStrategy).toBeInstanceOf(MockLocationStrategy);
});
});
| {
"end_byte": 840,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/location/provide_location_mocks_spec.ts"
} |
angular/packages/common/test/navigation/fake_platform_navigation.spec.ts_0_5535 | /**
* @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 {
ExperimentalNavigationInterceptOptions,
FakeNavigateEvent,
FakeNavigation,
FakeNavigationCurrentEntryChangeEvent,
} from '../../testing/src/navigation/fake_navigation';
interface Locals {
navigation: FakeNavigation;
navigateEvents: FakeNavigateEvent[];
navigationCurrentEntryChangeEvents: FakeNavigationCurrentEntryChangeEvent[];
popStateEvents: PopStateEvent[];
pendingInterceptOptions: ExperimentalNavigationInterceptOptions[];
nextNavigateEvent: () => Promise<FakeNavigateEvent>;
setExtraNavigateCallback: (callback: (event: FakeNavigateEvent) => void) => void;
}
describe('navigation', () => {
let locals: Locals;
const popStateListener = (event: Event) => {
const popStateEvent = event as PopStateEvent;
locals.popStateEvents.push(popStateEvent);
};
beforeEach(() => {
window.addEventListener('popstate', popStateListener);
});
afterEach(() => {
window.removeEventListener('popstate', popStateListener);
});
beforeEach(() => {
const navigation = new FakeNavigation(window, 'https://test.com');
const navigateEvents: FakeNavigateEvent[] = [];
let nextNavigateEventResolve!: (value: FakeNavigateEvent) => void;
let nextNavigateEventPromise = new Promise<FakeNavigateEvent>((resolve) => {
nextNavigateEventResolve = resolve;
});
const navigationCurrentEntryChangeEvents: FakeNavigationCurrentEntryChangeEvent[] = [];
const popStateEvents: PopStateEvent[] = [];
const pendingInterceptOptions: ExperimentalNavigationInterceptOptions[] = [];
let extraNavigateCallback: ((event: FakeNavigateEvent) => void) | undefined = undefined;
navigation.addEventListener('navigate', (event: Event) => {
const navigateEvent = event as FakeNavigateEvent;
nextNavigateEventResolve(navigateEvent);
nextNavigateEventPromise = new Promise<FakeNavigateEvent>((resolve) => {
nextNavigateEventResolve = resolve;
});
locals.navigateEvents.push(navigateEvent);
const interceptOptions = pendingInterceptOptions.shift();
if (interceptOptions) {
navigateEvent.intercept(interceptOptions);
}
extraNavigateCallback?.(navigateEvent);
});
navigation.addEventListener('currententrychange', (event: Event) => {
const currentNavigationEntryChangeEvent = event as FakeNavigationCurrentEntryChangeEvent;
locals.navigationCurrentEntryChangeEvents.push(currentNavigationEntryChangeEvent);
});
locals = {
navigation,
navigateEvents,
navigationCurrentEntryChangeEvents,
popStateEvents,
pendingInterceptOptions,
nextNavigateEvent() {
return nextNavigateEventPromise;
},
setExtraNavigateCallback(callback: (event: FakeNavigateEvent) => void) {
extraNavigateCallback = callback;
},
};
});
const setUpEntries = async ({hash = false} = {}) => {
locals.pendingInterceptOptions.push({});
const pathPrefix = hash ? '#' : '/';
const firstPageEntry = await locals.navigation.navigate(`${pathPrefix}page1`, {
state: {page1: true},
}).finished;
locals.pendingInterceptOptions.push({});
const secondPageEntry = await locals.navigation.navigate(`${pathPrefix}page2`, {
state: {page2: true},
}).finished;
locals.pendingInterceptOptions.push({});
const thirdPageEntry = await locals.navigation.navigate(`${pathPrefix}page3`, {
state: {page3: true},
}).finished;
locals.navigateEvents.length = 0;
locals.navigationCurrentEntryChangeEvents.length = 0;
locals.popStateEvents.length = 0;
return [firstPageEntry, secondPageEntry, thirdPageEntry];
};
const setUpEntriesWithHistory = ({hash = false} = {}) => {
const pathPrefix = hash ? '#' : '/';
locals.navigation.pushState({state: {page1: true}}, '', `${pathPrefix}page1`);
const firstPageEntry = locals.navigation.currentEntry;
locals.navigation.pushState({state: {page2: true}}, '', `${pathPrefix}page2`);
const secondPageEntry = locals.navigation.currentEntry;
locals.navigation.pushState({state: {page3: true}}, '', `${pathPrefix}page3`);
const thirdPageEntry = locals.navigation.currentEntry;
locals.navigateEvents.length = 0;
locals.navigationCurrentEntryChangeEvents.length = 0;
locals.popStateEvents.length = 0;
return [firstPageEntry, secondPageEntry, thirdPageEntry];
};
it('disposes', async () => {
expect(locals.navigation.isDisposed()).toBeFalse();
const navigateEvents: Event[] = [];
locals.navigation.addEventListener('navigate', (event: Event) => {
navigateEvents.push(event);
});
const navigationCurrentEntryChangeEvents: Event[] = [];
locals.navigation.addEventListener('currententrychange', (event: Event) => {
navigationCurrentEntryChangeEvents.push(event);
});
await locals.navigation.navigate('#page1').finished;
expect(navigateEvents.length).toBe(1);
expect(navigationCurrentEntryChangeEvents.length).toBe(1);
locals.navigation.dispose();
// After a dispose, a different singleton.
expect(locals.navigation.isDisposed()).toBeTrue();
await locals.navigation.navigate('#page2').finished;
// Listeners are disposed.
expect(navigateEvents.length).toBe(1);
expect(navigationCurrentEntryChangeEvents.length).toBe(1);
}); | {
"end_byte": 5535,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/navigation/fake_platform_navigation.spec.ts"
} |
angular/packages/common/test/navigation/fake_platform_navigation.spec.ts_5539_14911 | describe('navigate', () => {
it('push URL', async () => {
const initialEntry = locals.navigation.currentEntry;
locals.pendingInterceptOptions.push({});
const {committed, finished} = locals.navigation.navigate('/test');
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(navigateEvent).toEqual(
jasmine.objectContaining({
canIntercept: true,
hashChange: false,
info: undefined,
navigationType: 'push',
userInitiated: false,
signal: jasmine.any(AbortSignal),
destination: jasmine.objectContaining({
url: 'https://test.com/test',
key: null,
id: null,
index: -1,
sameDocument: false,
}),
}),
);
expect(navigateEvent.destination.getState()).toBeUndefined();
const committedEntry = await committed;
expect(committedEntry).toEqual(
jasmine.objectContaining({
url: 'https://test.com/test',
key: '1',
id: '1',
index: 1,
sameDocument: true,
}),
);
expect(committedEntry.getState()).toBeUndefined();
expect(locals.navigation.currentEntry).toBe(committedEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
const currentEntryChangeEvent = locals.navigationCurrentEntryChangeEvents[0];
expect(currentEntryChangeEvent).toEqual(
jasmine.objectContaining({
navigationType: 'push',
from: jasmine.objectContaining({
url: initialEntry.url,
key: initialEntry.key,
id: initialEntry.id,
index: initialEntry.index,
sameDocument: initialEntry.sameDocument,
}),
}),
);
expect(currentEntryChangeEvent.from.getState()).toBe(initialEntry.getState());
expect(locals.popStateEvents.length).toBe(1);
const popStateEvent = locals.popStateEvents[0];
expect(popStateEvent.state).toBeNull();
const finishedEntry = await finished;
expect(committedEntry).toBe(finishedEntry);
expect(locals.navigation.currentEntry).toBe(finishedEntry);
expect(locals.navigateEvents.length).toBe(1);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
});
it('push URL relative', async () => {
locals.pendingInterceptOptions.push({});
await locals.navigation.navigate('/a/b/c').finished;
expect(locals.navigation.currentEntry.url).toBe('https://test.com/a/b/c');
locals.pendingInterceptOptions.push({
handler: () => Promise.resolve(),
});
await locals.navigation.navigate('../').finished;
expect(locals.navigation.currentEntry.url).toBe('https://test.com/a/');
});
it('replace URL', async () => {
const initialEntry = locals.navigation.currentEntry;
locals.pendingInterceptOptions.push({});
const {committed, finished} = locals.navigation.navigate('/test', {
history: 'replace',
});
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(navigateEvent).toEqual(
jasmine.objectContaining({
canIntercept: true,
hashChange: false,
info: undefined,
navigationType: 'replace',
userInitiated: false,
signal: jasmine.any(AbortSignal),
destination: jasmine.objectContaining({
url: 'https://test.com/test',
key: null,
id: null,
index: -1,
sameDocument: false,
}),
}),
);
expect(navigateEvent.destination.getState()).toBeUndefined();
const committedEntry = await committed;
expect(committedEntry).toEqual(
jasmine.objectContaining({
url: 'https://test.com/test',
key: '0',
id: '1',
index: 0,
sameDocument: true,
}),
);
expect(committedEntry.getState()).toBeUndefined();
expect(locals.navigation.currentEntry).toBe(committedEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
const currentEntryChangeEvent = locals.navigationCurrentEntryChangeEvents[0];
expect(currentEntryChangeEvent).toEqual(
jasmine.objectContaining({
navigationType: 'replace',
from: jasmine.objectContaining({
url: initialEntry.url,
key: initialEntry.key,
id: initialEntry.id,
index: initialEntry.index,
sameDocument: initialEntry.sameDocument,
}),
}),
);
expect(currentEntryChangeEvent.from.getState()).toBe(initialEntry.getState());
expect(locals.popStateEvents.length).toBe(1);
const popStateEvent = locals.popStateEvents[0];
expect(popStateEvent.state).toBeNull();
const finishedEntry = await finished;
expect(committedEntry).toBe(finishedEntry);
expect(locals.navigation.currentEntry).toBe(finishedEntry);
expect(locals.navigateEvents.length).toBe(1);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
});
it('push URL with state', async () => {
locals.pendingInterceptOptions.push({});
const state = {test: true};
const {committed, finished} = locals.navigation.navigate('/test', {
state,
});
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(navigateEvent.destination.getState()).toEqual(state);
const committedEntry = await committed;
expect(committedEntry.getState()).toEqual(state);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
const finishedEntry = await finished;
expect(committedEntry).toBe(finishedEntry);
});
it('replace URL with state', async () => {
locals.pendingInterceptOptions.push({});
const state = {test: true};
const {committed, finished} = locals.navigation.navigate('/test', {
state,
history: 'replace',
});
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(navigateEvent.destination.getState()).toEqual(state);
const committedEntry = await committed;
expect(committedEntry.getState()).toEqual(state);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
const finishedEntry = await finished;
expect(committedEntry).toBe(finishedEntry);
});
it('push URL with hashchange', async () => {
const {committed, finished} = locals.navigation.navigate('#test');
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(navigateEvent.destination.url).toBe('https://test.com/#test');
expect(navigateEvent.hashChange).toBeTrue();
const committedEntry = await committed;
expect(committedEntry.url).toBe('https://test.com/#test');
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
const finishedEntry = await finished;
expect(committedEntry).toBe(finishedEntry);
});
it('replace URL with hashchange', async () => {
const {committed, finished} = locals.navigation.navigate('#test', {
history: 'replace',
});
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(navigateEvent.destination.url).toBe('https://test.com/#test');
expect(navigateEvent.hashChange).toBeTrue();
const committedEntry = await committed;
expect(committedEntry.url).toBe('https://test.com/#test');
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
const finishedEntry = await finished;
expect(committedEntry).toBe(finishedEntry);
});
it('push URL with info', async () => {
locals.pendingInterceptOptions.push({});
const info = {test: true};
const {finished, committed} = locals.navigation.navigate('/test', {info});
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(navigateEvent.info).toBe(info);
await committed;
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await finished;
});
it('replace URL with info', async () => {
locals.pendingInterceptOptions.push({});
const info = {test: true};
const {finished, committed} = locals.navigation.navigate('/test', {
info,
history: 'replace',
});
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(navigateEvent.info).toBe(info);
await committed;
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await finished;
}); | {
"end_byte": 14911,
"start_byte": 5539,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/navigation/fake_platform_navigation.spec.ts"
} |
angular/packages/common/test/navigation/fake_platform_navigation.spec.ts_14917_23713 | it('push URL with handler', async () => {
let handlerFinishedResolve!: (value: Promise<undefined> | undefined) => void;
const handlerFinished = new Promise<undefined>((resolve) => {
handlerFinishedResolve = resolve;
});
locals.pendingInterceptOptions.push({
handler: () => handlerFinished,
});
const {committed, finished} = locals.navigation.navigate('/test');
expect(locals.navigateEvents.length).toBe(1);
const committedEntry = await committed;
expect(committedEntry).toEqual(
jasmine.objectContaining({
url: 'https://test.com/test',
key: '1',
id: '1',
index: 1,
sameDocument: true,
}),
);
expect(committedEntry.getState()).toBeUndefined();
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await expectAsync(finished).toBePending();
handlerFinishedResolve(undefined);
await expectAsync(finished).toBeResolvedTo(committedEntry);
});
it('replace URL with handler', async () => {
let handlerFinishedResolve!: (value: Promise<undefined> | undefined) => void;
const handlerFinished = new Promise<undefined>((resolve) => {
handlerFinishedResolve = resolve;
});
locals.pendingInterceptOptions.push({
handler: () => handlerFinished,
});
const {committed, finished} = locals.navigation.navigate('/test', {
history: 'replace',
});
expect(locals.navigateEvents.length).toBe(1);
const committedEntry = await committed;
expect(committedEntry).toEqual(
jasmine.objectContaining({
url: 'https://test.com/test',
key: '0',
id: '1',
index: 0,
sameDocument: true,
}),
);
expect(committedEntry.getState()).toBeUndefined();
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await expectAsync(finished).toBePending();
handlerFinishedResolve(undefined);
await expectAsync(finished).toBeResolvedTo(committedEntry);
});
it('deferred commit', async () => {
let handlerFinishedResolve!: (value: Promise<undefined> | undefined) => void;
const handlerFinished = new Promise<undefined>((resolve) => {
handlerFinishedResolve = resolve;
});
locals.pendingInterceptOptions.push({
handler: () => handlerFinished,
commit: 'after-transition',
});
const {committed, finished} = locals.navigation.navigate('/test');
expect(locals.navigateEvents.length).toBe(1);
await expectAsync(committed).toBePending();
expect(locals.navigation.currentEntry.url).toBe('https://test.com/');
locals.navigateEvents[0].commit();
const committedEntry = await committed;
expect(committedEntry).toEqual(
jasmine.objectContaining({
url: 'https://test.com/test',
key: '1',
id: '1',
index: 1,
sameDocument: true,
}),
);
expect(committedEntry.getState()).toBeUndefined();
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await expectAsync(finished).toBePending();
handlerFinishedResolve(undefined);
await expectAsync(finished).toBeResolvedTo(committedEntry);
});
it('deferred commit early resolve', async () => {
let handlerFinishedResolve!: (value: Promise<undefined> | undefined) => void;
const handlerFinished = new Promise<undefined>((resolve) => {
handlerFinishedResolve = resolve;
});
locals.pendingInterceptOptions.push({
handler: () => handlerFinished,
commit: 'after-transition',
});
const {committed, finished} = locals.navigation.navigate('/test');
expect(locals.navigateEvents.length).toBe(1);
await expectAsync(committed).toBePending();
expect(locals.navigation.currentEntry.url).toBe('https://test.com/');
handlerFinishedResolve(undefined);
const committedEntry = await committed;
expect(committedEntry).toEqual(
jasmine.objectContaining({
url: 'https://test.com/test',
key: '1',
id: '1',
index: 1,
sameDocument: true,
}),
);
expect(committedEntry.getState()).toBeUndefined();
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await expectAsync(finished).toBeResolvedTo(committedEntry);
});
it('deferred commit during dispatch throws', async () => {
locals.pendingInterceptOptions.push({
commit: 'after-transition',
});
let called = false;
locals.setExtraNavigateCallback((event: FakeNavigateEvent) => {
expect(() => {
called = true;
event.commit();
}).toThrowError(DOMException);
});
const {finished} = locals.navigation.navigate('/test');
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
navigateEvent.commit();
await finished;
expect(called).toBeTrue();
});
it('deferred commit with immediate throws', async () => {
locals.pendingInterceptOptions.push({});
const {finished} = locals.navigation.navigate('/test');
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(() => {
navigateEvent.commit();
}).toThrowError(DOMException);
await finished;
});
it('deferred commit twice throws', async () => {
let handlerFinishedResolve!: (value: Promise<undefined> | undefined) => void;
const handlerFinished = new Promise<undefined>((resolve) => {
handlerFinishedResolve = resolve;
});
locals.pendingInterceptOptions.push({
handler: () => handlerFinished,
commit: 'after-transition',
});
const {committed, finished} = locals.navigation.navigate('/test');
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
await expectAsync(committed).toBePending();
expect(locals.navigation.currentEntry.url).toBe('https://test.com/');
navigateEvent.commit();
expect(() => {
navigateEvent.commit();
}).toThrowError(DOMException);
handlerFinishedResolve(undefined);
await finished;
});
it('deferred commit resolves on finished', async () => {
let handlerFinishedResolve!: (value: Promise<undefined> | undefined) => void;
const handlerFinished = new Promise<undefined>((resolve) => {
handlerFinishedResolve = resolve;
});
locals.pendingInterceptOptions.push({
handler: () => handlerFinished,
commit: 'after-transition',
});
const {committed, finished} = locals.navigation.navigate('/test');
expect(locals.navigateEvents.length).toBe(1);
await expectAsync(committed).toBePending();
expect(locals.navigation.currentEntry.url).toBe('https://test.com/');
handlerFinishedResolve(undefined);
const committedEntry = await committed;
expect(committedEntry).toEqual(
jasmine.objectContaining({
url: 'https://test.com/test',
key: '1',
id: '1',
index: 1,
sameDocument: true,
}),
);
expect(committedEntry.getState()).toBeUndefined();
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await expectAsync(finished).toBeResolvedTo(committedEntry);
});
it('push with interruption', async () => {
locals.pendingInterceptOptions.push({
handler: () => new Promise(() => {}),
});
const {committed, finished} = locals.navigation.navigate('/test');
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
await committed;
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await expectAsync(finished).toBePending();
locals.pendingInterceptOptions.push({});
const interruptResult = locals.navigation.navigate('/interrupt');
await expectAsync(finished).toBeRejectedWithError(DOMException);
expect(navigateEvent.signal.aborted).toBeTrue();
await interruptResult.committed;
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(2);
expect(locals.popStateEvents.length).toBe(2);
await interruptResult.finished;
}); | {
"end_byte": 23713,
"start_byte": 14917,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/navigation/fake_platform_navigation.spec.ts"
} |
angular/packages/common/test/navigation/fake_platform_navigation.spec.ts_23719_26531 | it('replace with interruption', async () => {
locals.pendingInterceptOptions.push({
handler: () => new Promise(() => {}),
});
const {committed, finished} = locals.navigation.navigate('/test', {
history: 'replace',
});
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
await committed;
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await expectAsync(finished).toBePending();
locals.pendingInterceptOptions.push({});
const interruptResult = locals.navigation.navigate('/interrupt');
await expectAsync(finished).toBeRejectedWithError(DOMException);
expect(navigateEvent.signal.aborted).toBeTrue();
await interruptResult.committed;
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(2);
expect(locals.popStateEvents.length).toBe(2);
await interruptResult.finished;
});
it('push with handler reject', async () => {
let handlerFinishedReject!: (reason: unknown) => void;
locals.pendingInterceptOptions.push({
handler: () =>
new Promise<undefined>((resolve, reject) => {
handlerFinishedReject = reject;
}),
});
const {committed, finished} = locals.navigation.navigate('/test');
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
await committed;
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await expectAsync(finished).toBePending();
const error = new Error('rejected');
handlerFinishedReject(error);
await expectAsync(finished).toBeRejectedWith(error);
expect(navigateEvent.signal.aborted).toBeTrue();
});
it('replace with reject', async () => {
let handlerFinishedReject!: (reason: unknown) => void;
locals.pendingInterceptOptions.push({
handler: () =>
new Promise<undefined>((resolve, reject) => {
handlerFinishedReject = reject;
}),
});
const {committed, finished} = locals.navigation.navigate('/test', {
history: 'replace',
});
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
await committed;
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await expectAsync(finished).toBePending();
const error = new Error('rejected');
handlerFinishedReject(error);
await expectAsync(finished).toBeRejectedWith(error);
expect(navigateEvent.signal.aborted).toBeTrue();
});
}); | {
"end_byte": 26531,
"start_byte": 23719,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/navigation/fake_platform_navigation.spec.ts"
} |
angular/packages/common/test/navigation/fake_platform_navigation.spec.ts_26535_35439 | describe('traversal', () => {
it('traverses back', async () => {
expect(locals.navigation.canGoBack).toBeFalse();
expect(locals.navigation.canGoForward).toBeFalse();
const [firstPageEntry, , thirdPageEntry] = await setUpEntries();
expect(locals.navigation.canGoBack).toBeTrue();
expect(locals.navigation.canGoForward).toBeFalse();
const {committed, finished} = locals.navigation.traverseTo(firstPageEntry.key);
const navigateEvent = await locals.nextNavigateEvent();
expect(navigateEvent).toEqual(
jasmine.objectContaining({
canIntercept: true,
hashChange: false,
info: undefined,
navigationType: 'traverse',
signal: jasmine.any(AbortSignal),
userInitiated: false,
destination: jasmine.objectContaining({
url: firstPageEntry.url!,
key: firstPageEntry.key,
id: firstPageEntry.id,
index: firstPageEntry.index,
sameDocument: true,
}),
}),
);
expect(navigateEvent.destination.getState()).toEqual(firstPageEntry.getState());
const committedEntry = await committed;
expect(committedEntry).toBe(firstPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
const currentEntryChangeEvent = locals.navigationCurrentEntryChangeEvents[0];
expect(currentEntryChangeEvent).toEqual(
jasmine.objectContaining({
navigationType: 'traverse',
from: jasmine.objectContaining({
url: thirdPageEntry.url!,
key: thirdPageEntry.key,
id: thirdPageEntry.id,
index: thirdPageEntry.index,
sameDocument: true,
}),
}),
);
expect(currentEntryChangeEvent.from.getState()).toEqual(thirdPageEntry.getState());
expect(locals.popStateEvents.length).toBe(1);
const popStateEvent = locals.popStateEvents[0];
expect(popStateEvent.state).toBeNull();
expect(locals.navigation.canGoBack).toBeTrue();
expect(locals.navigation.canGoForward).toBeTrue();
const finishedEntry = await finished;
expect(finishedEntry).toBe(firstPageEntry);
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
expect(locals.navigateEvents.length).toBe(1);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
});
it('traverses forward', async () => {
expect(locals.navigation.canGoBack).toBeFalse();
expect(locals.navigation.canGoForward).toBeFalse();
const [firstPageEntry, , thirdPageEntry] = await setUpEntries();
expect(locals.navigation.canGoBack).toBeTrue();
expect(locals.navigation.canGoForward).toBeFalse();
await locals.navigation.traverseTo(firstPageEntry.key).finished;
locals.navigateEvents.length = 0;
locals.navigationCurrentEntryChangeEvents.length = 0;
locals.popStateEvents.length = 0;
expect(locals.navigation.canGoBack).toBeTrue();
expect(locals.navigation.canGoForward).toBeTrue();
const {committed, finished} = locals.navigation.traverseTo(thirdPageEntry.key);
const navigateEvent = await locals.nextNavigateEvent();
expect(navigateEvent).toEqual(
jasmine.objectContaining({
canIntercept: true,
hashChange: false,
info: undefined,
navigationType: 'traverse',
signal: jasmine.any(AbortSignal),
userInitiated: false,
destination: jasmine.objectContaining({
url: thirdPageEntry.url!,
key: thirdPageEntry.key,
id: thirdPageEntry.id,
index: thirdPageEntry.index,
sameDocument: true,
}),
}),
);
expect(navigateEvent.destination.getState()).toEqual(thirdPageEntry.getState());
const committedEntry = await committed;
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
const currentEntryChangeEvent = locals.navigationCurrentEntryChangeEvents[0];
expect(currentEntryChangeEvent).toEqual(
jasmine.objectContaining({
navigationType: 'traverse',
from: jasmine.objectContaining({
url: firstPageEntry.url!,
key: firstPageEntry.key,
id: firstPageEntry.id,
index: firstPageEntry.index,
sameDocument: true,
}),
}),
);
expect(currentEntryChangeEvent.from.getState()).toEqual(firstPageEntry.getState());
expect(locals.popStateEvents.length).toBe(1);
const popStateEvent = locals.popStateEvents[0];
expect(popStateEvent.state).toBeNull();
expect(committedEntry).toBe(thirdPageEntry);
const finishedEntry = await finished;
expect(finishedEntry).toBe(thirdPageEntry);
expect(locals.navigation.currentEntry).toBe(thirdPageEntry);
expect(locals.navigateEvents.length).toBe(1);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
expect(locals.navigation.canGoBack).toBeTrue();
expect(locals.navigation.canGoForward).toBeFalse();
});
it('traverses back with hashchange', async () => {
const [firstPageEntry] = await setUpEntries({hash: true});
const {finished, committed} = locals.navigation.traverseTo(firstPageEntry.key);
const navigateEvent = await locals.nextNavigateEvent();
expect(navigateEvent.hashChange).toBeTrue();
await committed;
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await finished;
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
});
it('traverses forward with hashchange', async () => {
const [firstPageEntry, thirdPageEntry] = await setUpEntries({hash: true});
await locals.navigation.traverseTo(firstPageEntry.key).finished;
locals.navigateEvents.length = 0;
locals.navigationCurrentEntryChangeEvents.length = 0;
locals.popStateEvents.length = 0;
const {finished, committed} = locals.navigation.traverseTo(thirdPageEntry.key);
const navigateEvent = await locals.nextNavigateEvent();
expect(navigateEvent.hashChange).toBeTrue();
await committed;
expect(locals.navigation.currentEntry).toBe(thirdPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await finished;
expect(locals.navigation.currentEntry).toBe(thirdPageEntry);
});
it('traverses with info', async () => {
const [firstPageEntry] = await setUpEntries();
const info = {test: true};
const {finished, committed} = locals.navigation.traverseTo(firstPageEntry.key, {info});
const navigateEvent = await locals.nextNavigateEvent();
expect(navigateEvent.info).toBe(info);
await committed;
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await finished;
});
it('traverses with history state', async () => {
const [firstPageEntry] = setUpEntriesWithHistory();
const {finished, committed} = locals.navigation.traverseTo(firstPageEntry.key);
const navigateEvent = await locals.nextNavigateEvent();
expect(navigateEvent.destination.getHistoryState()).toEqual(firstPageEntry.getHistoryState());
await committed;
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
const popStateEvent = locals.popStateEvents[0];
expect(popStateEvent.state).toEqual(firstPageEntry.getHistoryState());
await finished;
});
it('traverses with handler', async () => {
const [firstPageEntry] = await setUpEntries();
let handlerFinishedResolve!: (value: Promise<undefined> | undefined) => void;
const handlerFinished = new Promise<undefined>((resolve) => {
handlerFinishedResolve = resolve;
});
locals.pendingInterceptOptions.push({
handler: () => handlerFinished,
});
const {committed, finished} = locals.navigation.traverseTo(firstPageEntry.key);
const committedEntry = await committed;
expect(committedEntry).toBe(firstPageEntry);
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
expect(locals.navigateEvents.length).toBe(1);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await expectAsync(finished).toBePending();
handlerFinishedResolve(undefined);
await expectAsync(finished).toBeResolvedTo(firstPageEntry);
}); | {
"end_byte": 35439,
"start_byte": 26535,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/navigation/fake_platform_navigation.spec.ts"
} |
angular/packages/common/test/navigation/fake_platform_navigation.spec.ts_35445_44641 | it('traverses with interruption', async () => {
const [firstPageEntry] = await setUpEntries();
locals.pendingInterceptOptions.push({
handler: () => new Promise(() => {}),
});
const {committed, finished} = locals.navigation.traverseTo(firstPageEntry.key);
const navigateEvent = await locals.nextNavigateEvent();
await committed;
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
expect(navigateEvent.signal.aborted).toBeFalse();
await expectAsync(finished).toBePending();
locals.pendingInterceptOptions.push({});
const interruptResult = locals.navigation.navigate('/interrupt');
await expectAsync(finished).toBeRejectedWithError(DOMException);
expect(navigateEvent.signal.aborted).toBeTrue();
await interruptResult.committed;
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(2);
expect(locals.popStateEvents.length).toBe(2);
await interruptResult.finished;
});
it('traverses with reject', async () => {
const [firstPageEntry] = await setUpEntries();
let handlerFinishedReject!: (reason: unknown) => void;
locals.pendingInterceptOptions.push({
handler: () =>
new Promise<undefined>((resolve, reject) => {
handlerFinishedReject = reject;
}),
});
const {committed, finished} = locals.navigation.traverseTo(firstPageEntry.key);
const navigateEvent = await locals.nextNavigateEvent();
await committed;
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
expect(navigateEvent.signal.aborted).toBeFalse();
await expectAsync(finished).toBePending();
const error = new Error('rejected');
handlerFinishedReject(error);
await expectAsync(finished).toBeRejectedWith(error);
expect(navigateEvent.signal.aborted).toBeTrue();
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
});
it('traverses to non-existent', async () => {
const {committed, finished} = locals.navigation.traverseTo('non-existent');
await expectAsync(committed).toBeRejectedWithError(DOMException);
await expectAsync(finished).toBeRejectedWithError(DOMException);
expect(locals.navigateEvents.length).toBe(0);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(0);
expect(locals.popStateEvents.length).toBe(0);
});
it('back', async () => {
const [, secondPageEntry, thirdPageEntry] = await setUpEntries();
const {committed, finished} = locals.navigation.back();
const navigateEvent = await locals.nextNavigateEvent();
expect(navigateEvent).toEqual(
jasmine.objectContaining({
canIntercept: true,
hashChange: false,
info: undefined,
navigationType: 'traverse',
signal: jasmine.any(AbortSignal),
userInitiated: false,
destination: jasmine.objectContaining({
url: secondPageEntry.url!,
key: secondPageEntry.key,
id: secondPageEntry.id,
index: secondPageEntry.index,
sameDocument: true,
}),
}),
);
expect(navigateEvent.destination.getState()).toEqual(secondPageEntry.getState());
const committedEntry = await committed;
expect(committedEntry).toBe(secondPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
const currentEntryChangeEvent = locals.navigationCurrentEntryChangeEvents[0];
expect(currentEntryChangeEvent).toEqual(
jasmine.objectContaining({
navigationType: 'traverse',
from: jasmine.objectContaining({
url: thirdPageEntry.url!,
key: thirdPageEntry.key,
id: thirdPageEntry.id,
index: thirdPageEntry.index,
sameDocument: true,
}),
}),
);
expect(currentEntryChangeEvent.from.getState()).toEqual(thirdPageEntry.getState());
expect(locals.popStateEvents.length).toBe(1);
const popStateEvent = locals.popStateEvents[0];
expect(popStateEvent.state).toBeNull();
const finishedEntry = await finished;
expect(finishedEntry).toBe(secondPageEntry);
expect(locals.navigation.currentEntry).toBe(secondPageEntry);
});
it('back with info', async () => {
await setUpEntries();
const info = {test: true};
const {committed, finished} = locals.navigation.back({info});
const navigateEvent = await locals.nextNavigateEvent();
expect(navigateEvent.info).toBe(info);
await committed;
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await finished;
});
it('back out of bounds', async () => {
const {committed, finished} = locals.navigation.back();
await expectAsync(committed).toBeRejectedWithError(DOMException);
await expectAsync(finished).toBeRejectedWithError(DOMException);
expect(locals.navigateEvents.length).toBe(0);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(0);
expect(locals.popStateEvents.length).toBe(0);
});
it('forward', async () => {
const [firstPageEntry, secondPageEntry] = await setUpEntries();
await locals.navigation.traverseTo(firstPageEntry.key).finished;
locals.navigateEvents.length = 0;
locals.navigationCurrentEntryChangeEvents.length = 0;
locals.popStateEvents.length = 0;
const {committed, finished} = locals.navigation.forward();
const navigateEvent = await locals.nextNavigateEvent();
expect(navigateEvent).toEqual(
jasmine.objectContaining({
canIntercept: true,
hashChange: false,
info: undefined,
navigationType: 'traverse',
signal: jasmine.any(AbortSignal),
userInitiated: false,
destination: jasmine.objectContaining({
url: secondPageEntry.url!,
key: secondPageEntry.key,
id: secondPageEntry.id,
index: secondPageEntry.index,
sameDocument: true,
}),
}),
);
expect(navigateEvent.destination.getState()).toEqual(secondPageEntry.getState());
const committedEntry = await committed;
expect(committedEntry).toBe(secondPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
const currentEntryChangeEvent = locals.navigationCurrentEntryChangeEvents[0];
expect(currentEntryChangeEvent).toEqual(
jasmine.objectContaining({
navigationType: 'traverse',
from: jasmine.objectContaining({
url: firstPageEntry.url!,
key: firstPageEntry.key,
id: firstPageEntry.id,
index: firstPageEntry.index,
sameDocument: true,
}),
}),
);
expect(currentEntryChangeEvent.from.getState()).toEqual(firstPageEntry.getState());
expect(locals.popStateEvents.length).toBe(1);
const popStateEvent = locals.popStateEvents[0];
expect(popStateEvent.state).toBeNull();
const finishedEntry = await finished;
expect(finishedEntry).toBe(secondPageEntry);
expect(locals.navigation.currentEntry).toBe(secondPageEntry);
});
it('forward with info', async () => {
const [firstPageEntry] = await setUpEntries();
await locals.navigation.traverseTo(firstPageEntry.key).finished;
locals.navigateEvents.length = 0;
locals.navigationCurrentEntryChangeEvents.length = 0;
locals.popStateEvents.length = 0;
const info = {test: true};
const {committed, finished} = locals.navigation.forward({info});
const navigateEvent = await locals.nextNavigateEvent();
expect(navigateEvent.info).toBe(info);
await committed;
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await finished;
});
it('forward out of bounds', async () => {
const {committed, finished} = locals.navigation.forward();
await expectAsync(committed).toBeRejectedWithError(DOMException);
await expectAsync(finished).toBeRejectedWithError(DOMException);
expect(locals.navigateEvents.length).toBe(0);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(0);
expect(locals.popStateEvents.length).toBe(0);
});
it('traverse synchronously', async () => {
const [, secondPageEntry] = await setUpEntries();
locals.navigation.setSynchronousTraversalsForTesting(true);
const {committed, finished} = locals.navigation.back();
// Synchronously navigates.
expect(locals.navigation.currentEntry).toBe(secondPageEntry);
await expectAsync(committed).toBeResolvedTo(secondPageEntry);
await expectAsync(finished).toBeResolvedTo(secondPageEntry);
}); | {
"end_byte": 44641,
"start_byte": 35445,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/navigation/fake_platform_navigation.spec.ts"
} |
angular/packages/common/test/navigation/fake_platform_navigation.spec.ts_44647_51411 | it('traversal current entry', async () => {
const {committed, finished} = locals.navigation.traverseTo(
locals.navigation.currentEntry.key,
);
await expectAsync(committed).toBeResolvedTo(locals.navigation.currentEntry);
await expectAsync(finished).toBeResolvedTo(locals.navigation.currentEntry);
expect(locals.navigateEvents.length).toBe(0);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(0);
expect(locals.popStateEvents.length).toBe(0);
});
it('second traversal to same entry', async () => {
const [firstPageEntry] = await setUpEntries();
const traverseResult = locals.navigation.traverseTo(firstPageEntry.key);
const duplicateTraverseResult = locals.navigation.traverseTo(firstPageEntry.key);
expect(traverseResult.committed).toBe(duplicateTraverseResult.committed);
expect(traverseResult.finished).toBe(duplicateTraverseResult.finished);
await Promise.all([traverseResult.committed, duplicateTraverseResult.committed]);
// Only one NavigationCurrentEntryChangeEvent for duplicate traversals
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
await Promise.all([traverseResult.finished, duplicateTraverseResult.finished]);
// Only one NavigateEvent for duplicate traversals.
expect(locals.navigateEvents.length).toBe(1);
});
it('queues traverses', async () => {
const [firstPageEntry, secondPageEntry] = await setUpEntries();
const firstTraverseResult = locals.navigation.traverseTo(firstPageEntry.key);
const secondTraverseResult = locals.navigation.traverseTo(secondPageEntry.key);
const firstTraverseCommittedEntry = await firstTraverseResult.committed;
expect(firstTraverseCommittedEntry).toBe(firstPageEntry);
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
expect(locals.navigateEvents.length).toBe(1);
const firstNavigateEvent = locals.navigateEvents[0];
expect(firstNavigateEvent).toEqual(
jasmine.objectContaining({
navigationType: 'traverse',
destination: jasmine.objectContaining({
key: firstPageEntry.key,
}),
}),
);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
const firstTraverseFinishedEntry = await firstTraverseResult.finished;
expect(firstTraverseFinishedEntry).toBe(firstPageEntry);
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
const secondTraverseCommittedEntry = await secondTraverseResult.committed;
expect(secondTraverseCommittedEntry).toBe(secondPageEntry);
expect(locals.navigation.currentEntry).toBe(secondPageEntry);
expect(locals.navigateEvents.length).toBe(2);
const secondNavigateEvent = locals.navigateEvents[1];
expect(secondNavigateEvent).toEqual(
jasmine.objectContaining({
navigationType: 'traverse',
destination: jasmine.objectContaining({
key: secondPageEntry.key,
}),
}),
);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(2);
expect(locals.popStateEvents.length).toBe(2);
const secondTraverseFinishedEntry = await secondTraverseResult.finished;
expect(secondTraverseFinishedEntry).toBe(secondPageEntry);
expect(locals.navigation.currentEntry).toBe(secondPageEntry);
});
});
describe('integration', () => {
it('queues traverses after navigate', async () => {
const [firstPageEntry, secondPageEntry] = await setUpEntries();
const firstTraverseResult = locals.navigation.traverseTo(firstPageEntry.key);
const secondTraverseResult = locals.navigation.traverseTo(secondPageEntry.key);
locals.pendingInterceptOptions.push({});
const navigateResult = locals.navigation.navigate('/page4', {
state: {page4: true},
});
const navigateResultCommittedEntry = await navigateResult.committed;
expect(navigateResultCommittedEntry.url).toBe('https://test.com/page4');
expect(locals.navigation.currentEntry).toBe(navigateResultCommittedEntry);
expect(locals.navigateEvents.length).toBe(1);
const firstNavigateEvent = locals.navigateEvents[0];
expect(firstNavigateEvent).toEqual(
jasmine.objectContaining({
navigationType: 'push',
destination: jasmine.objectContaining({
url: 'https://test.com/page4',
}),
}),
);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
const navigateResultFinishedEntry = await navigateResult.finished;
expect(navigateResultFinishedEntry).toBe(navigateResultCommittedEntry);
expect(locals.navigation.currentEntry).toBe(navigateResultCommittedEntry);
const firstTraverseCommittedEntry = await firstTraverseResult.committed;
expect(firstTraverseCommittedEntry).toBe(firstPageEntry);
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
expect(locals.navigateEvents.length).toBe(2);
const secondNavigateEvent = locals.navigateEvents[1];
expect(secondNavigateEvent).toEqual(
jasmine.objectContaining({
navigationType: 'traverse',
destination: jasmine.objectContaining({
key: firstPageEntry.key,
}),
}),
);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(2);
expect(locals.popStateEvents.length).toBe(2);
const firstTraverseFinishedEntry = await firstTraverseResult.finished;
expect(firstTraverseFinishedEntry).toBe(firstPageEntry);
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
const secondTraverseCommittedEntry = await secondTraverseResult.committed;
expect(secondTraverseCommittedEntry).toBe(secondPageEntry);
expect(locals.navigation.currentEntry).toBe(secondPageEntry);
expect(locals.navigateEvents.length).toBe(3);
const thirdNavigateEvent = locals.navigateEvents[2];
expect(thirdNavigateEvent).toEqual(
jasmine.objectContaining({
navigationType: 'traverse',
destination: jasmine.objectContaining({
key: secondPageEntry.key,
}),
}),
);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(3);
expect(locals.popStateEvents.length).toBe(3);
const secondTraverseFinishedEntry = await secondTraverseResult.finished;
expect(secondTraverseFinishedEntry).toBe(secondPageEntry);
expect(locals.navigation.currentEntry).toBe(secondPageEntry);
});
}); | {
"end_byte": 51411,
"start_byte": 44647,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/navigation/fake_platform_navigation.spec.ts"
} |
angular/packages/common/test/navigation/fake_platform_navigation.spec.ts_51415_61197 | describe('history API', () => {
describe('push and replace', () => {
it('push URL', async () => {
const initialEntry = locals.navigation.currentEntry;
locals.navigation.pushState(undefined, '', '/test');
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(navigateEvent).toEqual(
jasmine.objectContaining({
canIntercept: true,
hashChange: false,
info: undefined,
navigationType: 'push',
userInitiated: false,
signal: jasmine.any(AbortSignal),
destination: jasmine.objectContaining({
url: 'https://test.com/test',
key: null,
id: null,
index: -1,
sameDocument: true,
}),
}),
);
expect(navigateEvent.destination.getState()).toBeUndefined();
expect(navigateEvent.destination.getHistoryState()).toBeUndefined();
const currentEntry = locals.navigation.currentEntry;
expect(currentEntry).toEqual(
jasmine.objectContaining({
url: 'https://test.com/test',
key: '1',
id: '1',
index: 1,
sameDocument: true,
}),
);
expect(currentEntry.getState()).toBeUndefined();
expect(currentEntry.getHistoryState()).toBeUndefined();
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
const currentEntryChangeEvent = locals.navigationCurrentEntryChangeEvents[0];
expect(currentEntryChangeEvent).toEqual(
jasmine.objectContaining({
navigationType: 'push',
from: jasmine.objectContaining({
url: initialEntry.url,
key: initialEntry.key,
id: initialEntry.id,
index: initialEntry.index,
sameDocument: initialEntry.sameDocument,
}),
}),
);
expect(currentEntryChangeEvent.from.getState()).toBe(initialEntry.getState());
expect(currentEntryChangeEvent.from.getHistoryState()).toBeNull();
expect(locals.popStateEvents.length).toBe(0);
});
it('replace URL', async () => {
const initialEntry = locals.navigation.currentEntry;
locals.navigation.replaceState(null, '', '/test');
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(navigateEvent).toEqual(
jasmine.objectContaining({
canIntercept: true,
hashChange: false,
info: undefined,
navigationType: 'replace',
userInitiated: false,
signal: jasmine.any(AbortSignal),
destination: jasmine.objectContaining({
url: 'https://test.com/test',
key: null,
id: null,
index: -1,
sameDocument: true,
}),
}),
);
expect(navigateEvent.destination.getState()).toBeUndefined();
expect(navigateEvent.destination.getHistoryState()).toBeNull();
const currentEntry = locals.navigation.currentEntry;
expect(currentEntry).toEqual(
jasmine.objectContaining({
url: 'https://test.com/test',
key: '0',
id: '1',
index: 0,
sameDocument: true,
}),
);
expect(currentEntry.getState()).toBeUndefined();
expect(currentEntry.getHistoryState()).toBeNull();
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
const currentEntryChangeEvent = locals.navigationCurrentEntryChangeEvents[0];
expect(currentEntryChangeEvent).toEqual(
jasmine.objectContaining({
navigationType: 'replace',
from: jasmine.objectContaining({
url: initialEntry.url,
key: initialEntry.key,
id: initialEntry.id,
index: initialEntry.index,
sameDocument: initialEntry.sameDocument,
}),
}),
);
expect(currentEntryChangeEvent.from.getState()).toBe(initialEntry.getState());
expect(currentEntryChangeEvent.from.getHistoryState()).toBeNull();
expect(locals.popStateEvents.length).toBe(0);
});
it('push URL with history state', async () => {
locals.pendingInterceptOptions.push({});
const state = {test: true};
locals.navigation.pushState(state, '', '/test');
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(navigateEvent.destination.getHistoryState()).toEqual(state);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.navigation.currentEntry.getHistoryState()).toEqual(state);
expect(locals.popStateEvents.length).toBe(0);
});
it('replace URL with history state', async () => {
locals.pendingInterceptOptions.push({});
const state = {test: true};
locals.navigation.replaceState(state, '', '/test');
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(navigateEvent.destination.getHistoryState()).toEqual(state);
expect(locals.navigation.currentEntry.getHistoryState()).toEqual(state);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(0);
});
it('push URL with hashchange', async () => {
locals.navigation.pushState(null, '', '#test');
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(navigateEvent.destination.url).toBe('https://test.com/#test');
expect(navigateEvent.hashChange).toBeTrue();
expect(locals.navigation.currentEntry.url).toBe('https://test.com/#test');
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(0);
});
it('replace URL with hashchange', async () => {
locals.navigation.replaceState(null, '', '#test');
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(navigateEvent.destination.url).toBe('https://test.com/#test');
expect(navigateEvent.hashChange).toBeTrue();
expect(locals.navigation.currentEntry.url).toBe('https://test.com/#test');
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(0);
});
it('push URL with handler', async () => {
let handlerFinishedResolve!: (value: Promise<undefined> | undefined) => void;
const handlerFinished = new Promise<undefined>((resolve) => {
handlerFinishedResolve = resolve;
});
locals.pendingInterceptOptions.push({
handler: () => handlerFinished,
});
locals.navigation.pushState(null, '', '/test');
expect(locals.navigateEvents.length).toBe(1);
const currentEntry = locals.navigation.currentEntry;
expect(currentEntry.url).toBe('https://test.com/test');
expect(currentEntry.key).toBe('1');
expect(currentEntry.id).toBe('1');
expect(currentEntry.index).toBe(1);
expect(currentEntry.sameDocument).toBeTrue();
expect(currentEntry.getState()).toBeUndefined();
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(0);
handlerFinishedResolve(undefined);
expect(locals.navigation.currentEntry).toBe(currentEntry);
});
it('replace URL with handler', async () => {
let handlerFinishedResolve!: (value: Promise<undefined> | undefined) => void;
const handlerFinished = new Promise<undefined>((resolve) => {
handlerFinishedResolve = resolve;
});
locals.pendingInterceptOptions.push({
handler: () => handlerFinished,
});
locals.navigation.replaceState(null, '', '/test');
expect(locals.navigateEvents.length).toBe(1);
const currentEntry = locals.navigation.currentEntry;
expect(currentEntry.url).toBe('https://test.com/test');
expect(currentEntry.key).toBe('0');
expect(currentEntry.id).toBe('1');
expect(currentEntry.index).toBe(0);
expect(currentEntry.sameDocument).toBeTrue();
expect(currentEntry.getState()).toBeUndefined();
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(0);
handlerFinishedResolve(undefined);
expect(locals.navigation.currentEntry).toBe(currentEntry);
});
it('push with interruption', async () => {
locals.pendingInterceptOptions.push({
handler: () => new Promise(() => {}),
});
locals.navigation.pushState(null, '', '/test');
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(0);
locals.pendingInterceptOptions.push({});
const interruptResult = locals.navigation.navigate('/interrupt');
expect(navigateEvent.signal.aborted).toBeTrue();
await interruptResult.committed;
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(2);
expect(locals.popStateEvents.length).toBe(1);
await interruptResult.finished;
}); | {
"end_byte": 61197,
"start_byte": 51415,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/navigation/fake_platform_navigation.spec.ts"
} |
angular/packages/common/test/navigation/fake_platform_navigation.spec.ts_61205_63773 | it('replace with interruption', async () => {
locals.pendingInterceptOptions.push({
handler: () => new Promise(() => {}),
});
locals.navigation.replaceState(null, '', '/test');
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(0);
locals.pendingInterceptOptions.push({});
const interruptResult = locals.navigation.navigate('/interrupt');
expect(navigateEvent.signal.aborted).toBeTrue();
await interruptResult.committed;
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(2);
expect(locals.popStateEvents.length).toBe(1);
await interruptResult.finished;
});
it('push with handler reject', async () => {
let handlerFinishedReject!: (reason: unknown) => void;
const handlerPromise = new Promise<undefined>((resolve, reject) => {
handlerFinishedReject = reject;
});
locals.pendingInterceptOptions.push({
handler: () => handlerPromise,
});
locals.navigation.pushState(null, '', '/test');
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(0);
const error = new Error('rejected');
handlerFinishedReject(error);
await expectAsync(handlerPromise).toBeRejectedWith(error);
expect(navigateEvent.signal.aborted).toBeTrue();
});
it('replace with reject', async () => {
let handlerFinishedReject!: (reason: unknown) => void;
const handlerPromise = new Promise<undefined>((resolve, reject) => {
handlerFinishedReject = reject;
});
locals.pendingInterceptOptions.push({
handler: () => handlerPromise,
});
locals.navigation.replaceState(null, '', '/test');
expect(locals.navigateEvents.length).toBe(1);
const navigateEvent = locals.navigateEvents[0];
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(0);
const error = new Error('rejected');
handlerFinishedReject(error);
await expectAsync(handlerPromise).toBeRejectedWith(error);
expect(navigateEvent.signal.aborted).toBeTrue();
});
}); | {
"end_byte": 63773,
"start_byte": 61205,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/navigation/fake_platform_navigation.spec.ts"
} |
angular/packages/common/test/navigation/fake_platform_navigation.spec.ts_63779_73639 | describe('traversal', () => {
it('go back', async () => {
expect(locals.navigation.canGoBack).toBeFalse();
expect(locals.navigation.canGoForward).toBeFalse();
const [firstPageEntry, , thirdPageEntry] = await setUpEntries();
expect(locals.navigation.canGoBack).toBeTrue();
expect(locals.navigation.canGoForward).toBeFalse();
locals.navigation.go(-2);
const navigateEvent = await locals.nextNavigateEvent();
expect(navigateEvent).toEqual(
jasmine.objectContaining({
canIntercept: true,
hashChange: false,
info: undefined,
navigationType: 'traverse',
signal: jasmine.any(AbortSignal),
userInitiated: false,
destination: jasmine.objectContaining({
url: firstPageEntry.url!,
key: firstPageEntry.key,
id: firstPageEntry.id,
index: firstPageEntry.index,
sameDocument: true,
}),
}),
);
expect(navigateEvent.destination.getState()).toEqual(firstPageEntry.getState());
expect(navigateEvent.destination.getHistoryState()).toEqual(
firstPageEntry.getHistoryState(),
);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
const currentEntryChangeEvent = locals.navigationCurrentEntryChangeEvents[0];
expect(currentEntryChangeEvent).toEqual(
jasmine.objectContaining({
navigationType: 'traverse',
from: jasmine.objectContaining({
url: thirdPageEntry.url!,
key: thirdPageEntry.key,
id: thirdPageEntry.id,
index: thirdPageEntry.index,
sameDocument: true,
}),
}),
);
expect(currentEntryChangeEvent.from.getState()).toEqual(thirdPageEntry.getState());
expect(currentEntryChangeEvent.from.getHistoryState()).toEqual(
thirdPageEntry.getHistoryState(),
);
expect(locals.popStateEvents.length).toBe(1);
const popStateEvent = locals.popStateEvents[0];
expect(popStateEvent.state).toBeNull();
expect(locals.navigation.canGoBack).toBeTrue();
expect(locals.navigation.canGoForward).toBeTrue();
});
it('go forward', async () => {
expect(locals.navigation.canGoBack).toBeFalse();
expect(locals.navigation.canGoForward).toBeFalse();
const [firstPageEntry, , thirdPageEntry] = await setUpEntries();
await locals.navigation.traverseTo(firstPageEntry.key).finished;
locals.navigateEvents.length = 0;
locals.navigationCurrentEntryChangeEvents.length = 0;
locals.popStateEvents.length = 0;
expect(locals.navigation.canGoBack).toBeTrue();
expect(locals.navigation.canGoForward).toBeTrue();
locals.navigation.go(2);
const navigateEvent = await locals.nextNavigateEvent();
expect(navigateEvent).toEqual(
jasmine.objectContaining({
canIntercept: true,
hashChange: false,
info: undefined,
navigationType: 'traverse',
signal: jasmine.any(AbortSignal),
userInitiated: false,
destination: jasmine.objectContaining({
url: thirdPageEntry.url!,
key: thirdPageEntry.key,
id: thirdPageEntry.id,
index: thirdPageEntry.index,
sameDocument: true,
}),
}),
);
expect(navigateEvent.destination.getState()).toEqual(thirdPageEntry.getState());
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
const currentEntryChangeEvent = locals.navigationCurrentEntryChangeEvents[0];
expect(currentEntryChangeEvent).toEqual(
jasmine.objectContaining({
navigationType: 'traverse',
from: jasmine.objectContaining({
url: firstPageEntry.url!,
key: firstPageEntry.key,
id: firstPageEntry.id,
index: firstPageEntry.index,
sameDocument: true,
}),
}),
);
expect(currentEntryChangeEvent.from.getState()).toEqual(firstPageEntry.getState());
expect(locals.popStateEvents.length).toBe(1);
const popStateEvent = locals.popStateEvents[0];
expect(popStateEvent.state).toBeNull();
expect(locals.navigation.currentEntry).toBe(thirdPageEntry);
expect(locals.navigateEvents.length).toBe(1);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
expect(locals.navigation.canGoBack).toBeTrue();
expect(locals.navigation.canGoForward).toBeFalse();
});
it('go back with hashchange', async () => {
await setUpEntries({hash: true});
locals.navigation.go(-2);
const navigateEvent = await locals.nextNavigateEvent();
expect(navigateEvent.hashChange).toBeTrue();
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
});
it('go back with history state', async () => {
const [firstPageEntry] = setUpEntriesWithHistory();
locals.navigation.go(-2);
const navigateEvent = await locals.nextNavigateEvent();
expect(navigateEvent.destination.getHistoryState()).toEqual(
firstPageEntry.getHistoryState(),
);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
const popStateEvent = locals.popStateEvents[0];
expect(popStateEvent.state).toEqual(firstPageEntry.getHistoryState());
});
it('go forward with hashchange', async () => {
const [firstPageEntry] = await setUpEntries({hash: true});
await locals.navigation.traverseTo(firstPageEntry.key).finished;
locals.navigateEvents.length = 0;
locals.navigationCurrentEntryChangeEvents.length = 0;
locals.popStateEvents.length = 0;
locals.navigation.go(2);
const navigateEvent = await locals.nextNavigateEvent();
expect(navigateEvent.hashChange).toBeTrue();
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
});
it('go with handler', async () => {
const [firstPageEntry] = await setUpEntries();
let handlerFinishedResolve!: (value: Promise<undefined> | undefined) => void;
const handlerFinished = new Promise<undefined>((resolve) => {
handlerFinishedResolve = resolve;
});
locals.pendingInterceptOptions.push({
handler: () => handlerFinished,
});
locals.navigation.go(-2);
await locals.nextNavigateEvent();
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
handlerFinishedResolve(undefined);
});
it('go with interruption', async () => {
const [firstPageEntry] = await setUpEntries();
locals.pendingInterceptOptions.push({
handler: () => new Promise(() => {}),
});
locals.navigation.go(-2);
const navigateEvent = await locals.nextNavigateEvent();
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
expect(navigateEvent.signal.aborted).toBeFalse();
locals.pendingInterceptOptions.push({});
const interruptResult = locals.navigation.navigate('/interrupt');
await interruptResult.committed;
expect(navigateEvent.signal.aborted).toBeTrue();
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(2);
expect(locals.popStateEvents.length).toBe(2);
await interruptResult.finished;
});
it('go with reject', async () => {
const [firstPageEntry] = await setUpEntries();
let handlerFinishedReject!: (reason: unknown) => void;
locals.pendingInterceptOptions.push({
handler: () =>
new Promise<undefined>((resolve, reject) => {
handlerFinishedReject = reject;
}),
});
locals.navigation.go(-2);
const navigateEvent = await locals.nextNavigateEvent();
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
expect(navigateEvent.signal.aborted).toBeFalse();
const error = new Error('rejected');
handlerFinishedReject(error);
await new Promise((resolve) => {
navigateEvent.signal.addEventListener('abort', resolve);
});
expect(navigateEvent.signal.aborted).toBeTrue();
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
});
it('go synchronously', async () => {
const [, secondPageEntry] = await setUpEntries();
locals.navigation.setSynchronousTraversalsForTesting(true);
locals.navigation.go(-1);
// Synchronously navigates.
expect(locals.navigation.currentEntry).toBe(secondPageEntry);
await expectAsync(locals.nextNavigateEvent()).toBePending();
});
it('go out of bounds', async () => {
locals.navigation.go(-1);
await expectAsync(locals.nextNavigateEvent()).toBePending();
locals.navigation.go(1);
await expectAsync(locals.nextNavigateEvent()).toBePending();
}); | {
"end_byte": 73639,
"start_byte": 63779,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/navigation/fake_platform_navigation.spec.ts"
} |
angular/packages/common/test/navigation/fake_platform_navigation.spec.ts_73647_78811 | it('go queues', async () => {
const [firstPageEntry, secondPageEntry] = await setUpEntries();
locals.navigation.go(-1);
locals.navigation.go(-1);
const firstNavigateEvent = await locals.nextNavigateEvent();
expect(firstNavigateEvent.destination.key).toBe(secondPageEntry.key);
expect(locals.navigation.currentEntry).toBe(secondPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
const secondNavigateEvent = await locals.nextNavigateEvent();
expect(secondNavigateEvent.destination.key).toBe(firstPageEntry.key);
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(2);
expect(locals.popStateEvents.length).toBe(2);
});
it('go queues both directions', async () => {
const [firstPageEntry, secondPageEntry] = await setUpEntries();
locals.navigation.go(-2);
locals.navigation.go(1);
const firstNavigateEvent = await locals.nextNavigateEvent();
expect(firstNavigateEvent.destination.key).toBe(firstPageEntry.key);
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
const secondNavigateEvent = await locals.nextNavigateEvent();
expect(secondNavigateEvent.destination.key).toBe(secondPageEntry.key);
expect(locals.navigation.currentEntry).toBe(secondPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(2);
expect(locals.popStateEvents.length).toBe(2);
});
it('go queues with back', async () => {
const [firstPageEntry, secondPageEntry] = await setUpEntries();
locals.navigation.back();
locals.navigation.go(-1);
const firstNavigateEvent = await locals.nextNavigateEvent();
expect(firstNavigateEvent.destination.key).toBe(secondPageEntry.key);
expect(locals.navigation.currentEntry).toBe(secondPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
const secondNavigateEvent = await locals.nextNavigateEvent();
expect(secondNavigateEvent.destination.key).toBe(firstPageEntry.key);
expect(locals.navigation.currentEntry).toBe(firstPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(2);
expect(locals.popStateEvents.length).toBe(2);
});
it('go queues with forward', async () => {
const [, secondPageEntry, thirdPageEntry] = await setUpEntries();
await locals.navigation.back().finished;
locals.navigateEvents.length = 0;
locals.navigationCurrentEntryChangeEvents.length = 0;
locals.popStateEvents.length = 0;
locals.navigation.forward();
locals.navigation.go(-1);
const firstNavigateEvent = await locals.nextNavigateEvent();
expect(firstNavigateEvent.destination.key).toBe(thirdPageEntry.key);
expect(locals.navigation.currentEntry).toBe(thirdPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
const secondNavigateEvent = await locals.nextNavigateEvent();
expect(secondNavigateEvent.destination.key).toBe(secondPageEntry.key);
expect(locals.navigation.currentEntry).toBe(secondPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(2);
expect(locals.popStateEvents.length).toBe(2);
});
it('go after synchronous navigate', async () => {
const [, secondPageEntry, thirdPageEntry] = await setUpEntries();
// Back to /page2
locals.navigation.go(-1);
// Push /interrupt on top of current /page3
locals.pendingInterceptOptions.push({});
const interruptResult = locals.navigation.navigate('/interrupt');
// Back from /interrupt to /page3.
locals.navigation.go(-1);
const interruptEntry = await interruptResult.finished;
expect(locals.navigation.currentEntry).toBe(interruptEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(1);
expect(locals.popStateEvents.length).toBe(1);
const firstNavigateEvent = await locals.nextNavigateEvent();
expect(firstNavigateEvent.destination.key).toBe(secondPageEntry.key);
expect(locals.navigation.currentEntry).toBe(secondPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(2);
expect(locals.popStateEvents.length).toBe(2);
const secondNavigateEvent = await locals.nextNavigateEvent();
expect(secondNavigateEvent.destination.key).toBe(thirdPageEntry.key);
expect(locals.navigation.currentEntry).toBe(thirdPageEntry);
expect(locals.navigationCurrentEntryChangeEvents.length).toBe(3);
expect(locals.popStateEvents.length).toBe(3);
});
});
});
}); | {
"end_byte": 78811,
"start_byte": 73647,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/navigation/fake_platform_navigation.spec.ts"
} |
angular/packages/common/test/pipes/case_conversion_pipes_spec.ts_0_5696 | /**
* @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 {LowerCasePipe, TitleCasePipe, UpperCasePipe} from '@angular/common';
import {Component} from '@angular/core';
import {TestBed} from '@angular/core/testing';
describe('LowerCasePipe', () => {
let pipe: LowerCasePipe;
beforeEach(() => {
pipe = new LowerCasePipe();
});
it('should return lowercase', () => {
expect(pipe.transform('FOO')).toEqual('foo');
});
it('should lowercase when there is a new value', () => {
expect(pipe.transform('FOO')).toEqual('foo');
expect(pipe.transform('BAr')).toEqual('bar');
});
it('should map null to null', () => {
expect(pipe.transform(null)).toEqual(null);
});
it('should map undefined to null', () => {
expect(pipe.transform(undefined)).toEqual(null);
});
it('should not support numbers', () => {
expect(() => pipe.transform(0 as any)).toThrowError();
});
it('should not support other objects', () => {
expect(() => pipe.transform({} as any)).toThrowError();
});
it('should be available as a standalone pipe', () => {
@Component({
selector: 'test-component',
imports: [LowerCasePipe],
template: '{{ value | lowercase }}',
standalone: true,
})
class TestComponent {
value = 'FOO';
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content).toBe('foo');
});
});
describe('TitleCasePipe', () => {
let pipe: TitleCasePipe;
beforeEach(() => {
pipe = new TitleCasePipe();
});
it('should return titlecase', () => {
expect(pipe.transform('foo')).toEqual('Foo');
});
it('should return titlecase for subsequent words', () => {
expect(pipe.transform('one TWO Three fouR')).toEqual('One Two Three Four');
});
it('should support empty strings', () => {
expect(pipe.transform('')).toEqual('');
});
it('should persist whitespace', () => {
expect(pipe.transform('one two')).toEqual('One Two');
});
it('should titlecase when there is a new value', () => {
expect(pipe.transform('bar')).toEqual('Bar');
expect(pipe.transform('foo')).toEqual('Foo');
});
it('should not capitalize letter after the quotes', () => {
expect(pipe.transform("it's complicated")).toEqual("It's Complicated");
});
it('should not treat non-space character as a separator', () => {
expect(pipe.transform('one,two,three')).toEqual('One,two,three');
expect(pipe.transform('true|false')).toEqual('True|false');
expect(pipe.transform('foo-vs-bar')).toEqual('Foo-vs-bar');
});
it('should support support all whitespace characters', () => {
expect(pipe.transform('one\ttwo')).toEqual('One\tTwo');
expect(pipe.transform('three\rfour')).toEqual('Three\rFour');
expect(pipe.transform('five\nsix')).toEqual('Five\nSix');
});
it('should work properly for non-latin alphabet', () => {
expect(pipe.transform('føderation')).toEqual('Føderation');
expect(pipe.transform('poniedziałek')).toEqual('Poniedziałek');
expect(pipe.transform('éric')).toEqual('Éric');
});
it('should handle numbers at the beginning of words', () => {
expect(pipe.transform('frodo was 1st and bilbo was 2nd')).toEqual(
'Frodo Was 1st And Bilbo Was 2nd',
);
expect(pipe.transform('1ST')).toEqual('1st');
});
it('should map null to null', () => {
expect(pipe.transform(null)).toEqual(null);
});
it('should map undefined to null', () => {
expect(pipe.transform(undefined)).toEqual(null);
});
it('should not support numbers', () => {
expect(() => pipe.transform(0 as any)).toThrowError();
});
it('should not support other objects', () => {
expect(() => pipe.transform({} as any)).toThrowError();
});
it('should be available as a standalone pipe', () => {
@Component({
selector: 'test-component',
imports: [TitleCasePipe],
template: '{{ value | titlecase }}',
standalone: true,
})
class TestComponent {
value = 'foo';
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content).toBe('Foo');
});
});
describe('UpperCasePipe', () => {
let pipe: UpperCasePipe;
beforeEach(() => {
pipe = new UpperCasePipe();
});
it('should return uppercase', () => {
expect(pipe.transform('foo')).toEqual('FOO');
});
it('should uppercase when there is a new value', () => {
expect(pipe.transform('foo')).toEqual('FOO');
expect(pipe.transform('bar')).toEqual('BAR');
});
it('should map null to null', () => {
expect(pipe.transform(null)).toEqual(null);
});
it('should map undefined to null', () => {
expect(pipe.transform(undefined)).toEqual(null);
});
it('should not support numbers', () => {
expect(() => pipe.transform(0 as any)).toThrowError();
});
it('should not support other objects', () => {
expect(() => pipe.transform({} as any)).toThrowError();
});
it('should be available as a standalone pipe', () => {
@Component({
selector: 'test-component',
imports: [UpperCasePipe],
template: '{{ value | uppercase }}',
standalone: true,
})
class TestComponent {
value = 'foo';
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content).toBe('FOO');
});
});
| {
"end_byte": 5696,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/pipes/case_conversion_pipes_spec.ts"
} |
angular/packages/common/test/pipes/json_pipe_spec.ts_0_2835 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {CommonModule, JsonPipe} from '@angular/common';
import {Component} from '@angular/core';
import {TestBed, waitForAsync} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers';
describe('JsonPipe', () => {
const regNewLine = '\n';
let inceptionObj: any;
let inceptionObjString: string;
let pipe: JsonPipe;
function normalize(obj: string): string {
return obj.replace(regNewLine, '');
}
beforeEach(() => {
inceptionObj = {dream: {dream: {dream: 'Limbo'}}};
inceptionObjString =
'{\n' +
' "dream": {\n' +
' "dream": {\n' +
' "dream": "Limbo"\n' +
' }\n' +
' }\n' +
'}';
pipe = new JsonPipe();
});
describe('transform', () => {
it('should return JSON-formatted string', () => {
expect(pipe.transform(inceptionObj)).toEqual(inceptionObjString);
});
it('should return JSON-formatted string even when normalized', () => {
const dream1 = normalize(pipe.transform(inceptionObj));
const dream2 = normalize(inceptionObjString);
expect(dream1).toEqual(dream2);
});
it('should return JSON-formatted string similar to Json.stringify', () => {
const dream1 = normalize(pipe.transform(inceptionObj));
const dream2 = normalize(JSON.stringify(inceptionObj, null, 2));
expect(dream1).toEqual(dream2);
});
});
describe('integration', () => {
@Component({
selector: 'test-comp',
template: '{{data | json}}',
standalone: false,
})
class TestComp {
data: any;
}
beforeEach(() => {
TestBed.configureTestingModule({declarations: [TestComp], imports: [CommonModule]});
});
it('should work with mutable objects', waitForAsync(() => {
const fixture = TestBed.createComponent(TestComp);
const mutable: number[] = [1];
fixture.componentInstance.data = mutable;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('[\n 1\n]');
mutable.push(2);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('[\n 1,\n 2\n]');
}));
});
it('should be available as a standalone pipe', () => {
@Component({
selector: 'test-component',
imports: [JsonPipe],
template: '{{ value | json }}',
standalone: true,
})
class TestComponent {
value = {'a': 1};
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content.replace(/\s/g, '')).toBe('{"a":1}');
});
});
| {
"end_byte": 2835,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/pipes/json_pipe_spec.ts"
} |
angular/packages/common/test/pipes/keyvalue_pipe_spec.ts_0_543 | /**
* @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 {KeyValuePipe} from '@angular/common';
import {JsonPipe} from '@angular/common/public_api';
import {defaultComparator} from '@angular/common/src/pipes/keyvalue_pipe';
import {Component, ɵdefaultKeyValueDiffers as defaultKeyValueDiffers} from '@angular/core';
import {TestBed} from '@angular/core/testing';
describe('KeyValuePipe', | {
"end_byte": 543,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/pipes/keyvalue_pipe_spec.ts"
} |
angular/packages/common/test/pipes/keyvalue_pipe_spec.ts_544_8296 | ) => {
it('should return null when given null', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
expect(pipe.transform(null)).toEqual(null);
});
it('should return null when given undefined', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
expect(pipe.transform(undefined)).toEqual(null);
});
it('should return null for an unsupported type', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
const fn = () => {};
expect(pipe.transform(fn as any as null)).toEqual(null);
});
describe('object dictionary', () => {
it('should return empty array of an empty dictionary', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
expect(pipe.transform({})).toEqual([]);
});
it('should transform a basic dictionary', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
expect(pipe.transform({1: 2})).toEqual([{key: '1', value: 2}]);
});
it('should order by alpha', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
expect(pipe.transform({'b': 1, 'a': 1})).toEqual([
{key: 'a', value: 1},
{key: 'b', value: 1},
]);
});
it('should order by numerical', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
expect(pipe.transform({2: 1, 1: 1})).toEqual([
{key: '1', value: 1},
{key: '2', value: 1},
]);
});
it('should order by numerical and alpha', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
const input = {2: 1, 1: 1, 'b': 1, 0: 1, 3: 1, 'a': 1};
expect(pipe.transform(input)).toEqual([
{key: '0', value: 1},
{key: '1', value: 1},
{key: '2', value: 1},
{key: '3', value: 1},
{key: 'a', value: 1},
{key: 'b', value: 1},
]);
});
it('should not order by alpha when compareFn is null', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
expect(pipe.transform({'b': 1, 'a': 1}, null)).toEqual([
{key: 'b', value: 1},
{key: 'a', value: 1},
]);
});
it('should reorder when compareFn changes', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
const input = {'b': 1, 'a': 2};
pipe.transform<string, number>(input);
expect(pipe.transform<string, number>(input, (a, b) => a.value - b.value)).toEqual([
{key: 'b', value: 1},
{key: 'a', value: 2},
]);
});
it('should return the same ref if nothing changes', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
const transform1 = pipe.transform({1: 2});
const transform2 = pipe.transform({1: 2});
expect(transform1 === transform2).toEqual(true);
});
it('should return a new ref if something changes', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
const transform1 = pipe.transform({1: 2});
const transform2 = pipe.transform({1: 3});
expect(transform1 !== transform2).toEqual(true);
});
it('should accept a type union of an object with string keys and null', () => {
let value!: {[key: string]: string} | null;
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
expect(pipe.transform(value)).toEqual(null);
});
it('should accept a type union of an object with number keys and null', () => {
let value!: {[key: number]: string} | null;
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
expect(pipe.transform(value)).toEqual(null);
});
});
describe('Map', () => {
it('should return an empty array for an empty Map', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
expect(pipe.transform(new Map())).toEqual([]);
});
it('should transform a basic Map', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
expect(pipe.transform(new Map([[1, 2]]))).toEqual([{key: 1, value: 2}]);
});
it('should order by alpha', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
expect(
pipe.transform(
new Map([
['b', 1],
['a', 1],
]),
),
).toEqual([
{key: 'a', value: 1},
{key: 'b', value: 1},
]);
});
it('should order by numerical', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
expect(
pipe.transform(
new Map([
[2, 1],
[1, 1],
]),
),
).toEqual([
{key: 1, value: 1},
{key: 2, value: 1},
]);
});
it('should order by numerical and alpha', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
const input = [
[2, 1],
[1, 1],
['b', 1],
[0, 1],
[3, 1],
['a', 1],
] as Array<[number | string, number]>;
expect(pipe.transform(new Map(input))).toEqual([
{key: 0, value: 1},
{key: 1, value: 1},
{key: 2, value: 1},
{key: 3, value: 1},
{key: 'a', value: 1},
{key: 'b', value: 1},
]);
});
it('should order by complex types with compareFn', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
const input = new Map([
[{id: 1}, 1],
[{id: 0}, 1],
]);
expect(
pipe.transform<{id: number}, number>(input, (a, b) => (a.key.id > b.key.id ? 1 : -1)),
).toEqual([
{key: {id: 0}, value: 1},
{key: {id: 1}, value: 1},
]);
});
it('should not order by alpha when compareFn is null', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
expect(
pipe.transform(
new Map([
['b', 1],
['a', 1],
]),
null,
),
).toEqual([
{key: 'b', value: 1},
{key: 'a', value: 1},
]);
});
it('should reorder when compareFn changes', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
const input = new Map([
['b', 1],
['a', 2],
]);
pipe.transform<string, number>(input);
expect(pipe.transform<string, number>(input, (a, b) => a.value - b.value)).toEqual([
{key: 'b', value: 1},
{key: 'a', value: 2},
]);
});
it('should return the same ref if nothing changes', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
const transform1 = pipe.transform(new Map([[1, 2]]));
const transform2 = pipe.transform(new Map([[1, 2]]));
expect(transform1 === transform2).toEqual(true);
});
it('should return a new ref if something changes', () => {
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
const transform1 = pipe.transform(new Map([[1, 2]]));
const transform2 = pipe.transform(new Map([[1, 3]]));
expect(transform1 !== transform2).toEqual(true);
});
it('should accept a type union of a Map and null', () => {
let value!: Map<number, number> | null;
const pipe = new KeyValuePipe(defaultKeyValueDiffers);
expect(pipe.transform(value)).toEqual(null);
});
});
it('should be available as a standalone pipe', () => {
@Component({
selector: 'test-component',
imports: [KeyValuePipe, JsonPipe],
template: '{{ value | keyvalue | json }}',
standalone: true,
})
class TestComponent {
value = {'b': 1, 'a': 2};
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content.replace(/\s/g, '')).toBe('[{"key":"a","value":2},{"key":"b","value":1}]');
});
}) | {
"end_byte": 8296,
"start_byte": 544,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/pipes/keyvalue_pipe_spec.ts"
} |
angular/packages/common/test/pipes/keyvalue_pipe_spec.ts_8296_10474 | ;
describe('defaultComparator', () => {
it('should remain the same order when keys are equal', () => {
const key = 1;
const values = [
{key, value: 2},
{key, value: 1},
];
expect(values.sort(defaultComparator)).toEqual(values);
});
it('should sort undefined keys to the end', () => {
const values = [
{key: 3, value: 1},
{key: undefined, value: 3},
{key: 1, value: 2},
];
expect(values.sort(defaultComparator)).toEqual([
{key: 1, value: 2},
{key: 3, value: 1},
{key: undefined, value: 3},
]);
});
it('should sort null keys to the end', () => {
const values = [
{key: 3, value: 1},
{key: null, value: 3},
{key: 1, value: 2},
];
expect(values.sort(defaultComparator)).toEqual([
{key: 1, value: 2},
{key: 3, value: 1},
{key: null, value: 3},
]);
});
it('should sort strings in alpha ascending', () => {
const values = [
{key: 'b', value: 1},
{key: 'a', value: 3},
];
expect(values.sort(defaultComparator)).toEqual([
{key: 'a', value: 3},
{key: 'b', value: 1},
]);
});
it('should sort numbers in numerical ascending', () => {
const values = [
{key: 2, value: 1},
{key: 1, value: 3},
];
expect(values.sort(defaultComparator)).toEqual([
{key: 1, value: 3},
{key: 2, value: 1},
]);
});
it('should sort boolean in false (0) -> true (1)', () => {
const values = [
{key: true, value: 3},
{key: false, value: 1},
];
expect(values.sort(defaultComparator)).toEqual([
{key: false, value: 1},
{key: true, value: 3},
]);
});
it('should sort numbers as strings in numerical ascending', () => {
// We need to cast the values array to "any[]" because the object keys
// have no type overlap and the "Array.sort" expects all keys to have the
// same type when passed to the sort comparator.
const values = [
{key: '2', value: 1},
{key: 1, value: 3},
] as any[];
expect(values.sort(defaultComparator)).toEqual([
{key: 1, value: 3},
{key: '2', value: 1},
]);
});
});
| {
"end_byte": 10474,
"start_byte": 8296,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/pipes/keyvalue_pipe_spec.ts"
} |
angular/packages/common/test/pipes/slice_pipe_spec.ts_0_4414 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {CommonModule, SlicePipe} from '@angular/common';
import {Component} from '@angular/core';
import {TestBed, waitForAsync} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers';
describe('SlicePipe', () => {
let list: number[];
let str: string;
let pipe: SlicePipe;
beforeEach(() => {
list = [1, 2, 3, 4, 5];
str = 'tuvwxyz';
pipe = new SlicePipe();
});
describe('supports', () => {
it('should support strings', () => {
expect(() => pipe.transform(str, 0)).not.toThrow();
});
it('should support lists', () => {
expect(() => pipe.transform(list, 0)).not.toThrow();
});
it('should support readonly lists', () => {
expect(() => pipe.transform(list as ReadonlyArray<number>, 0)).not.toThrow();
});
it('should not support other objects', () => {
// so we cast as `any` to check that it throws for unsupported objects // this would not compile
expect(() => pipe.transform({} as any, 0)).toThrow();
});
});
describe('transform', () => {
it('should return null if the value is null', () => {
expect(pipe.transform(null, 1)).toBe(null);
});
it('should return null if the value is undefined', () => {
expect(pipe.transform(undefined, 1)).toBe(null);
});
it('should return all items after START index when START is positive and END is omitted', () => {
expect(pipe.transform(list, 3)).toEqual([4, 5]);
expect(pipe.transform(str, 3)).toEqual('wxyz');
});
it('should return last START items when START is negative and END is omitted', () => {
expect(pipe.transform(list, -3)).toEqual([3, 4, 5]);
expect(pipe.transform(str, -3)).toEqual('xyz');
});
it('should return all items between START and END index when START and END are positive', () => {
expect(pipe.transform(list, 1, 3)).toEqual([2, 3]);
expect(pipe.transform(str, 1, 3)).toEqual('uv');
});
it('should return all items between START and END from the end when START and END are negative', () => {
expect(pipe.transform(list, -4, -2)).toEqual([2, 3]);
expect(pipe.transform(str, -4, -2)).toEqual('wx');
});
it('should return an empty value if START is greater than END', () => {
expect(pipe.transform(list, 4, 2)).toEqual([]);
expect(pipe.transform(str, 4, 2)).toEqual('');
});
it('should return an empty value if START greater than input length', () => {
expect(pipe.transform(list, 99)).toEqual([]);
expect(pipe.transform(str, 99)).toEqual('');
});
it('should return entire input if START is negative and greater than input length', () => {
expect(pipe.transform(list, -99)).toEqual([1, 2, 3, 4, 5]);
expect(pipe.transform(str, -99)).toEqual('tuvwxyz');
});
it('should not modify the input list', () => {
expect(pipe.transform(list, 2)).toEqual([3, 4, 5]);
expect(list).toEqual([1, 2, 3, 4, 5]);
});
});
describe('integration', () => {
@Component({
selector: 'test-comp',
template: '{{(data | slice:1).join(",") }}',
standalone: false,
})
class TestComp {
data: any;
}
beforeEach(() => {
TestBed.configureTestingModule({declarations: [TestComp], imports: [CommonModule]});
});
it('should work with mutable arrays', waitForAsync(() => {
const fixture = TestBed.createComponent(TestComp);
const mutable: number[] = [1, 2];
fixture.componentInstance.data = mutable;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('2');
mutable.push(3);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('2,3');
}));
});
it('should be available as a standalone pipe', () => {
@Component({
selector: 'test-component',
imports: [SlicePipe],
template: '{{ title | slice:0:5 }}',
standalone: true,
})
class TestComponent {
title = 'Hello World!';
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content).toBe('Hello');
});
});
| {
"end_byte": 4414,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/pipes/slice_pipe_spec.ts"
} |
angular/packages/common/test/pipes/i18n_select_pipe_spec.ts_0_1948 | /**
* @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 {I18nSelectPipe} from '@angular/common';
import {Component} from '@angular/core';
import {TestBed} from '@angular/core/testing';
describe('I18nSelectPipe', () => {
const pipe: I18nSelectPipe = new I18nSelectPipe();
const mapping = {'male': 'Invite him.', 'female': 'Invite her.', 'other': 'Invite them.'};
describe('transform', () => {
it('should return the "male" text if value is "male"', () => {
const val = pipe.transform('male', mapping);
expect(val).toEqual('Invite him.');
});
it('should return the "female" text if value is "female"', () => {
const val = pipe.transform('female', mapping);
expect(val).toEqual('Invite her.');
});
it('should return the "other" text if value is neither "male" nor "female"', () => {
expect(pipe.transform('Anything else', mapping)).toEqual('Invite them.');
});
it('should return an empty text if value is null or undefined', () => {
expect(pipe.transform(null, mapping)).toEqual('');
expect(pipe.transform(void 0, mapping)).toEqual('');
});
it('should throw on bad arguments', () => {
expect(() => pipe.transform('male', 'hey' as any)).toThrowError();
});
it('should be available as a standalone pipe', () => {
@Component({
selector: 'test-component',
imports: [I18nSelectPipe],
template: '{{ value | i18nSelect:mapping }}',
standalone: true,
})
class TestComponent {
value = 'other';
mapping = mapping;
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content).toBe('Invite them.');
});
});
});
| {
"end_byte": 1948,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/pipes/i18n_select_pipe_spec.ts"
} |
angular/packages/common/test/pipes/date_pipe_spec.ts_0_519 | /**
* @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 {DATE_PIPE_DEFAULT_OPTIONS, DatePipe} from '@angular/common';
import localeEn from '@angular/common/locales/en';
import localeEnExtra from '@angular/common/locales/extra/en';
import {Component, ɵregisterLocaleData, ɵunregisterLocaleData} from '@angular/core';
import {TestBed} from '@angular/core/testing';
| {
"end_byte": 519,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/pipes/date_pipe_spec.ts"
} |
angular/packages/common/test/pipes/date_pipe_spec.ts_521_8247 | scribe('DatePipe', () => {
const isoStringWithoutTime = '2015-01-01';
let pipe: DatePipe;
let date: Date;
beforeAll(() => ɵregisterLocaleData(localeEn, localeEnExtra));
afterAll(() => ɵunregisterLocaleData());
beforeEach(() => {
date = new Date(2015, 5, 15, 9, 3, 1, 550);
pipe = new DatePipe('en-US', null);
});
describe('supports', () => {
it('should support date', () => {
expect(() => pipe.transform(date)).not.toThrow();
});
it('should support int', () => {
expect(() => pipe.transform(123456789)).not.toThrow();
});
it('should support numeric strings', () => {
expect(() => pipe.transform('123456789')).not.toThrow();
});
it('should support decimal strings', () => {
expect(() => pipe.transform('123456789.11')).not.toThrow();
});
it('should support ISO string', () =>
expect(() => pipe.transform('2015-06-15T21:43:11Z')).not.toThrow());
it('should return null for empty string', () => {
expect(pipe.transform('')).toEqual(null);
});
it('should return null for NaN', () => {
expect(pipe.transform(Number.NaN)).toEqual(null);
});
it('should return null for null', () => {
expect(pipe.transform(null)).toEqual(null);
});
it('should return null for undefined', () => {
expect(pipe.transform(undefined)).toEqual(null);
});
it('should support ISO string without time', () => {
expect(() => pipe.transform(isoStringWithoutTime)).not.toThrow();
});
it('should not support other objects', () => {
expect(() => pipe.transform({} as any)).toThrowError(/InvalidPipeArgument/);
});
});
describe('transform', () => {
it('should use "mediumDate" as the default format if no format is provided', () =>
expect(pipe.transform('2017-01-11T10:14:39+0000')).toEqual('Jan 11, 2017'));
it('should give precedence to the passed in format', () =>
expect(pipe.transform('2017-01-11T10:14:39+0000', 'shortDate')).toEqual('1/11/17'));
it('should use format provided in component as default format when no format is passed in', () => {
@Component({
selector: 'test-component',
imports: [DatePipe],
template: '{{ value | date }}',
standalone: true,
providers: [{provide: DATE_PIPE_DEFAULT_OPTIONS, useValue: {dateFormat: 'shortDate'}}],
})
class TestComponent {
value = '2017-01-11T10:14:39+0000';
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content).toBe('1/11/17');
});
it('should use format provided in module as default format when no format is passed in', () => {
@Component({
selector: 'test-component',
imports: [DatePipe],
template: '{{ value | date }}',
standalone: true,
})
class TestComponent {
value = '2017-01-11T10:14:39+0000';
}
TestBed.configureTestingModule({
imports: [TestComponent],
providers: [{provide: DATE_PIPE_DEFAULT_OPTIONS, useValue: {dateFormat: 'shortDate'}}],
});
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content).toBe('1/11/17');
});
it('should return first week if some dates fall in previous year but belong to next year according to ISO 8601 format', () => {
expect(pipe.transform('2019-12-28T00:00:00', 'w')).toEqual('52');
// December 29th is a Sunday, week number is from previous thursday
expect(pipe.transform('2019-12-29T00:00:00', 'w')).toEqual('52');
// December 30th is a monday, week number is from next thursday
expect(pipe.transform('2019-12-30T00:00:00', 'w')).toEqual('1');
});
it('should return first week if some dates fall in previous leap year but belong to next year according to ISO 8601 format', () => {
expect(pipe.transform('2012-12-29T00:00:00', 'w')).toEqual('52');
// December 30th is a Sunday, week number is from previous thursday
expect(pipe.transform('2012-12-30T00:00:00', 'w')).toEqual('52');
// December 31th is a monday, week number is from next thursday
expect(pipe.transform('2012-12-31T00:00:00', 'w')).toEqual('1');
});
it('should round milliseconds down to the nearest millisecond', () => {
expect(pipe.transform('2020-08-01T23:59:59.999', 'yyyy-MM-dd')).toEqual('2020-08-01');
expect(pipe.transform('2020-08-01T23:59:59.9999', 'yyyy-MM-dd, h:mm:ss SSS')).toEqual(
'2020-08-01, 11:59:59 999',
);
});
it('should take timezone into account with timezone offset', () => {
expect(pipe.transform('2017-01-11T00:00:00', 'mediumDate', '-1200')).toEqual('Jan 10, 2017');
});
it('should support an empty string for the timezone', () => {
expect(pipe.transform('2017-01-11T00:00:00', 'mediumDate', '')).toEqual('Jan 11, 2017');
});
it('should take timezone into account', () => {
expect(pipe.transform('2017-01-11T00:00:00', 'mediumDate', '-1200')).toEqual('Jan 10, 2017');
});
it('should take timezone into account with timezone offset', () => {
expect(pipe.transform('2017-01-11T00:00:00', 'mediumDate', '-1200')).toEqual('Jan 10, 2017');
});
it('should take the default timezone into account when no timezone is passed in', () => {
pipe = new DatePipe('en-US', '-1200');
expect(pipe.transform('2017-01-11T00:00:00', 'mediumDate')).toEqual('Jan 10, 2017');
});
it('should give precedence to the passed in timezone over the default one', () => {
pipe = new DatePipe('en-US', '-1200');
expect(pipe.transform('2017-01-11T00:00:00', 'mediumDate', '+0100')).toEqual('Jan 11, 2017');
});
it('should use timezone provided in component as default timezone when no format is passed in', () => {
@Component({
selector: 'test-component',
imports: [DatePipe],
template: '{{ value | date }}',
standalone: true,
providers: [{provide: DATE_PIPE_DEFAULT_OPTIONS, useValue: {timezone: '-1200'}}],
})
class TestComponent {
value = '2017-01-11T00:00:00';
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content).toBe('Jan 10, 2017');
});
it('should use timezone provided in module as default timezone when no format is passed in', () => {
@Component({
selector: 'test-component',
imports: [DatePipe],
template: '{{ value | date }}',
standalone: true,
})
class TestComponent {
value = '2017-01-11T00:00:00';
}
TestBed.configureTestingModule({
imports: [TestComponent],
providers: [{provide: DATE_PIPE_DEFAULT_OPTIONS, useValue: {timezone: '-1200'}}],
});
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content).toBe('Jan 10, 2017');
});
});
it('should be available as a standalone pipe', () => {
@Component({
selector: 'test-component',
imports: [DatePipe],
template: '{{ value | date }}',
standalone: true,
})
class TestComponent {
value = '2017-01-11T10:14:39+0000';
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content).toBe('Jan 11, 2017');
});
});
| {
"end_byte": 8247,
"start_byte": 521,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/pipes/date_pipe_spec.ts"
} |
angular/packages/common/test/pipes/i18n_plural_pipe_spec.ts_0_2488 | /**
* @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 {I18nPluralPipe, NgLocalization} from '@angular/common';
import {Component} from '@angular/core';
import {TestBed} from '@angular/core/testing';
describe('I18nPluralPipe', () => {
let localization: NgLocalization;
let pipe: I18nPluralPipe;
const mapping = {
'=0': 'No messages.',
'=1': 'One message.',
'many': 'Many messages.',
'other': 'There are # messages, that is #.',
};
beforeEach(() => {
localization = new TestLocalization();
pipe = new I18nPluralPipe(localization);
});
describe('transform', () => {
it('should return 0 text if value is 0', () => {
const val = pipe.transform(0, mapping);
expect(val).toEqual('No messages.');
});
it('should return 1 text if value is 1', () => {
const val = pipe.transform(1, mapping);
expect(val).toEqual('One message.');
});
it('should return category messages', () => {
const val = pipe.transform(4, mapping);
expect(val).toEqual('Many messages.');
});
it('should interpolate the value into the text where indicated', () => {
const val = pipe.transform(6, mapping);
expect(val).toEqual('There are 6 messages, that is 6.');
});
it('should use "" if value is undefined', () => {
const val = pipe.transform(undefined, mapping);
expect(val).toEqual('');
});
it('should use "" if value is null', () => {
const val = pipe.transform(null, mapping);
expect(val).toEqual('');
});
it('should not support bad arguments', () => {
expect(() => pipe.transform(0, 'hey' as any)).toThrowError();
});
});
it('should be available as a standalone pipe', () => {
@Component({
selector: 'test-component',
imports: [I18nPluralPipe],
template: '{{ value | i18nPlural:mapping }}',
standalone: true,
})
class TestComponent {
value = 1;
mapping = mapping;
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content).toBe('One message.');
});
});
class TestLocalization extends NgLocalization {
override getPluralCategory(value: number): string {
return value > 1 && value < 6 ? 'many' : 'other';
}
}
| {
"end_byte": 2488,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/pipes/i18n_plural_pipe_spec.ts"
} |
angular/packages/common/test/pipes/number_pipe_spec.ts_0_725 | /**
* @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 {CurrencyPipe, DecimalPipe, PercentPipe} from '@angular/common';
import localeAr from '@angular/common/locales/ar';
import localeDa from '@angular/common/locales/da';
import localeDeAt from '@angular/common/locales/de-AT';
import localeEn from '@angular/common/locales/en';
import localeEsUS from '@angular/common/locales/es-US';
import localeFr from '@angular/common/locales/fr';
import {Component, ɵregisterLocaleData, ɵunregisterLocaleData} from '@angular/core';
import {TestBed} from '@angular/core/testing';
| {
"end_byte": 725,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/pipes/number_pipe_spec.ts"
} |
angular/packages/common/test/pipes/number_pipe_spec.ts_727_9023 | scribe('Number pipes', () => {
beforeAll(() => {
ɵregisterLocaleData(localeEn);
ɵregisterLocaleData(localeEsUS);
ɵregisterLocaleData(localeFr);
ɵregisterLocaleData(localeAr);
ɵregisterLocaleData(localeDeAt);
ɵregisterLocaleData(localeDa);
});
afterAll(() => ɵunregisterLocaleData());
describe('DecimalPipe', () => {
describe('transform', () => {
let pipe: DecimalPipe;
beforeEach(() => {
pipe = new DecimalPipe('en-US');
});
it('should return correct value for numbers', () => {
expect(pipe.transform(12345)).toEqual('12,345');
expect(pipe.transform(1.123456, '3.4-5')).toEqual('001.12346');
});
it('should support strings', () => {
expect(pipe.transform('12345')).toEqual('12,345');
expect(pipe.transform('123', '.2')).toEqual('123.00');
expect(pipe.transform('1', '3.')).toEqual('001');
expect(pipe.transform('1.1', '3.4-5')).toEqual('001.1000');
expect(pipe.transform('1.123456', '3.4-5')).toEqual('001.12346');
expect(pipe.transform('1.1234')).toEqual('1.123');
});
it('should return null for NaN', () => {
expect(pipe.transform(Number.NaN)).toEqual(null);
});
it('should return null for null', () => {
expect(pipe.transform(null)).toEqual(null);
});
it('should return null for undefined', () => {
expect(pipe.transform(undefined)).toEqual(null);
});
it('should not support other objects', () => {
expect(() => pipe.transform({} as any)).toThrowError(
`NG02100: InvalidPipeArgument: '[object Object] is not a number' for pipe 'DecimalPipe'`,
);
expect(() => pipe.transform('123abc')).toThrowError(
`NG02100: InvalidPipeArgument: '123abc is not a number' for pipe 'DecimalPipe'`,
);
});
});
describe('transform with custom locales', () => {
it('should return the correct format for es-US', () => {
const pipe = new DecimalPipe('es-US');
expect(pipe.transform('9999999.99', '1.2-2')).toEqual('9,999,999.99');
});
});
it('should be available as a standalone pipe', () => {
@Component({
selector: 'test-component',
imports: [DecimalPipe],
template: '{{ value | number }}',
standalone: true,
})
class TestComponent {
value = 12345;
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content).toBe('12,345');
});
});
describe('PercentPipe', () => {
let pipe: PercentPipe;
beforeEach(() => {
pipe = new PercentPipe('en-US');
});
describe('transform', () => {
it('should return correct value for numbers', () => {
expect(pipe.transform(1.23)).toEqual('123%');
expect(pipe.transform(1.234)).toEqual('123%');
expect(pipe.transform(1.236)).toEqual('124%');
expect(pipe.transform(12.3456, '0.0-10')).toEqual('1,234.56%');
});
it('should return null for NaN', () => {
expect(pipe.transform(Number.NaN)).toEqual(null);
});
it('should return null for null', () => {
expect(pipe.transform(null)).toEqual(null);
});
it('should return null for undefined', () => {
expect(pipe.transform(undefined)).toEqual(null);
});
it('should not support other objects', () => {
expect(() => pipe.transform({} as any)).toThrowError(
`NG02100: InvalidPipeArgument: '[object Object] is not a number' for pipe 'PercentPipe'`,
);
});
});
it('should be available as a standalone pipe', () => {
@Component({
selector: 'test-component',
imports: [PercentPipe],
template: '{{ value | percent }}',
standalone: true,
})
class TestComponent {
value = 15;
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content).toBe('1,500%');
});
});
describe('CurrencyPipe', () => {
let pipe: CurrencyPipe;
beforeEach(() => {
pipe = new CurrencyPipe('en-US', 'USD');
});
describe('transform', () => {
it('should return correct value for numbers', () => {
expect(pipe.transform(123)).toEqual('$123.00');
expect(pipe.transform(12, 'EUR', 'code', '.1')).toEqual('EUR12.0');
expect(pipe.transform(5.1234, 'USD', 'code', '.0-3')).toEqual('USD5.123');
expect(pipe.transform(5.1234, 'USD', 'code')).toEqual('USD5.12');
expect(pipe.transform(5.1234, 'USD', '')).toEqual('5.12');
expect(pipe.transform(5.1234, 'USD', 'symbol')).toEqual('$5.12');
expect(pipe.transform(5.1234, 'CAD', 'symbol')).toEqual('CA$5.12');
expect(pipe.transform(5.1234, 'CAD', 'symbol-narrow')).toEqual('$5.12');
expect(pipe.transform(5.1234, 'CAD', 'symbol-narrow', '5.2-2')).toEqual('$00,005.12');
expect(pipe.transform(5.1234, 'CAD', 'symbol-narrow', '5.2-2', 'fr')).toEqual(
'00\u202f005,12 $',
);
expect(pipe.transform(5, 'USD', 'symbol', '', 'fr')).toEqual('5,00 $US');
expect(pipe.transform(123456789, 'EUR', 'symbol', '', 'de-at')).toEqual('€ 123.456.789,00');
expect(pipe.transform(5.1234, 'EUR', '', '', 'de-at')).toEqual('5,12');
expect(pipe.transform(5.1234, 'DKK', '', '', 'da')).toEqual('5,12');
// CLP doesn't have a subdivision, so it should not display decimals unless explicitly
// told so
expect(pipe.transform(5.1234, 'CLP', '')).toEqual('5');
expect(pipe.transform(5.1234, 'CLP', '', '2.0-3')).toEqual('05.123');
});
it('should use the injected default currency code if none is provided', () => {
const clpPipe = new CurrencyPipe('en-US', 'CLP');
expect(clpPipe.transform(1234)).toEqual('CLP1,234');
});
it('should support any currency code name', () => {
// currency code is unknown, default formatting options will be used
expect(pipe.transform(5.1234, 'unexisting_ISO_code', 'symbol')).toEqual(
'unexisting_ISO_code5.12',
);
// currency code is USD, the pipe will format based on USD but will display "Custom name"
expect(pipe.transform(5.1234, 'USD', 'Custom name')).toEqual('Custom name5.12');
// currency code is unknown, default formatting options will be used and will display
// "Custom name"
expect(pipe.transform(5.1234, 'unexisting_ISO_code', 'Custom name')).toEqual(
'Custom name5.12',
);
});
it('should return null for NaN', () => {
expect(pipe.transform(Number.NaN)).toEqual(null);
});
it('should return null for null', () => {
expect(pipe.transform(null)).toEqual(null);
});
it('should return null for undefined', () => {
expect(pipe.transform(undefined)).toEqual(null);
});
it('should not support other objects', () => {
expect(() => pipe.transform({} as any)).toThrowError(
`NG02100: InvalidPipeArgument: '[object Object] is not a number' for pipe 'CurrencyPipe'`,
);
});
it('should warn if you are using the v4 signature', () => {
const warnSpy = spyOn(console, 'warn');
pipe.transform(123, 'USD', true);
expect(warnSpy).toHaveBeenCalledWith(
`Warning: the currency pipe has been changed in Angular v5. The symbolDisplay option (third parameter) is now a string instead of a boolean. The accepted values are "code", "symbol" or "symbol-narrow".`,
);
});
});
it('should be available as a standalone pipe', () => {
@Component({
selector: 'test-component',
imports: [CurrencyPipe],
template: '{{ value | currency }}',
standalone: true,
})
class TestComponent {
value = 15;
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content).toBe('$15.00');
});
});
});
| {
"end_byte": 9023,
"start_byte": 727,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/pipes/number_pipe_spec.ts"
} |
angular/packages/common/test/pipes/async_pipe_spec.ts_0_8764 | /**
* @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 {ChangeDetectorRef, Component, computed, EventEmitter, signal} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {Observable, of, Subscribable, Unsubscribable} from 'rxjs';
describe('AsyncPipe', () => {
let pipe: AsyncPipe;
let ref: ChangeDetectorRef & jasmine.SpyObj<ChangeDetectorRef>;
function getChangeDetectorRefSpy() {
return jasmine.createSpyObj('ChangeDetectorRef', ['markForCheck', 'detectChanges']);
}
beforeEach(() => {
ref = getChangeDetectorRefSpy();
pipe = new AsyncPipe(ref);
});
afterEach(() => {
pipe.ngOnDestroy(); // Close all subscriptions.
});
describe('Observable', () => {
// only expose methods from the Subscribable interface, to ensure that
// the implementation does not rely on other methods:
const wrapSubscribable = <T>(input: Subscribable<T>): Subscribable<T> => ({
subscribe(...args: any): Unsubscribable {
const subscription = input.subscribe.apply(input, args);
return {
unsubscribe() {
subscription.unsubscribe();
},
};
},
});
let emitter: EventEmitter<any>;
let subscribable: Subscribable<any>;
const message = {};
beforeEach(() => {
emitter = new EventEmitter();
subscribable = wrapSubscribable(emitter);
});
describe('transform', () => {
it('should return null when subscribing to an observable', () => {
expect(pipe.transform(subscribable)).toBe(null);
});
it('should return the latest available value', (done) => {
pipe.transform(subscribable);
emitter.emit(message);
setTimeout(() => {
expect(pipe.transform(subscribable)).toEqual(message);
done();
}, 0);
});
it('should return same value when nothing has changed since the last call', (done) => {
pipe.transform(subscribable);
emitter.emit(message);
setTimeout(() => {
pipe.transform(subscribable);
expect(pipe.transform(subscribable)).toBe(message);
done();
}, 0);
});
it('should dispose of the existing subscription when subscribing to a new observable', (done) => {
pipe.transform(subscribable);
const newEmitter = new EventEmitter();
const newSubscribable = wrapSubscribable(newEmitter);
expect(pipe.transform(newSubscribable)).toBe(null);
emitter.emit(message);
// this should not affect the pipe
setTimeout(() => {
expect(pipe.transform(newSubscribable)).toBe(null);
done();
}, 0);
});
it('should request a change detection check upon receiving a new value', (done) => {
pipe.transform(subscribable);
emitter.emit(message);
setTimeout(() => {
expect(ref.markForCheck).toHaveBeenCalled();
done();
}, 10);
});
it('should return value for unchanged NaN', () => {
emitter.emit(null);
pipe.transform(subscribable);
emitter.next(NaN);
const firstResult = pipe.transform(subscribable);
const secondResult = pipe.transform(subscribable);
expect(firstResult).toBeNaN();
expect(secondResult).toBeNaN();
});
it('should not track signal reads in subscriptions', () => {
const trigger = signal(false);
const obs = new Observable(() => {
// Whenever `obs` is subscribed, synchronously read `trigger`.
trigger();
});
let trackCount = 0;
const tracker = computed(() => {
// Subscribe to `obs` within this `computed`. If the subscription side effect runs
// within the computed, then changes to `trigger` will invalidate this computed.
pipe.transform(obs);
// The computed returns how many times it's run.
return ++trackCount;
});
expect(tracker()).toBe(1);
trigger.set(true);
expect(tracker()).toBe(1);
});
});
describe('ngOnDestroy', () => {
it('should do nothing when no subscription', () => {
expect(() => pipe.ngOnDestroy()).not.toThrow();
});
it('should dispose of the existing subscription', (done) => {
pipe.transform(subscribable);
pipe.ngOnDestroy();
emitter.emit(message);
setTimeout(() => {
expect(pipe.transform(subscribable)).toBe(null);
done();
}, 0);
});
});
});
describe('Subscribable', () => {
it('should infer the type from the subscribable', () => {
const emitter = new EventEmitter<{name: 'T'}>();
// The following line will fail to compile if the type cannot be inferred.
const name = pipe.transform(emitter)?.name;
});
});
describe('Promise', () => {
const message = {};
let resolve: (result: any) => void;
let reject: (error: any) => void;
let promise: Promise<any>;
// adds longer timers for passing tests in IE
const timer = 10;
beforeEach(() => {
promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
});
describe('transform', () => {
it('should return null when subscribing to a promise', () => {
expect(pipe.transform(promise)).toBe(null);
});
it('should return the latest available value', (done) => {
pipe.transform(promise);
resolve(message);
setTimeout(() => {
expect(pipe.transform(promise)).toEqual(message);
done();
}, timer);
});
it('should return value when nothing has changed since the last call', (done) => {
pipe.transform(promise);
resolve(message);
setTimeout(() => {
pipe.transform(promise);
expect(pipe.transform(promise)).toBe(message);
done();
}, timer);
});
it('should dispose of the existing subscription when subscribing to a new promise', (done) => {
pipe.transform(promise);
promise = new Promise<any>(() => {});
expect(pipe.transform(promise)).toBe(null);
resolve(message);
setTimeout(() => {
expect(pipe.transform(promise)).toBe(null);
done();
}, timer);
});
it('should request a change detection check upon receiving a new value', (done) => {
pipe.transform(promise);
resolve(message);
setTimeout(() => {
expect(ref.markForCheck).toHaveBeenCalled();
done();
}, timer);
});
describe('ngOnDestroy', () => {
it('should do nothing when no source', () => {
expect(() => pipe.ngOnDestroy()).not.toThrow();
});
it('should dispose of the existing source', (done) => {
pipe.transform(promise);
expect(pipe.transform(promise)).toBe(null);
resolve(message);
setTimeout(() => {
expect(pipe.transform(promise)).toEqual(message);
pipe.ngOnDestroy();
expect(pipe.transform(promise)).toBe(null);
done();
}, timer);
});
it('should ignore signals after the pipe has been destroyed', (done) => {
pipe.transform(promise);
expect(pipe.transform(promise)).toBe(null);
pipe.ngOnDestroy();
resolve(message);
setTimeout(() => {
expect(pipe.transform(promise)).toBe(null);
done();
}, timer);
});
});
});
});
describe('null', () => {
it('should return null when given null', () => {
expect(pipe.transform(null)).toEqual(null);
});
});
describe('undefined', () => {
it('should return null when given undefined', () => {
expect(pipe.transform(undefined)).toEqual(null);
});
});
describe('other types', () => {
it('should throw when given an invalid object', () => {
expect(() => pipe.transform('some bogus object' as any)).toThrowError();
});
});
it('should be available as a standalone pipe', () => {
@Component({
selector: 'test-component',
imports: [AsyncPipe],
template: '{{ value | async }}',
standalone: true,
})
class TestComponent {
value = of('foo');
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content).toBe('foo');
});
});
| {
"end_byte": 8764,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/pipes/async_pipe_spec.ts"
} |
angular/packages/common/test/i18n/format_number_spec.ts_0_586 | /**
* @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 {formatCurrency, formatNumber, formatPercent} from '@angular/common';
import localeAr from '@angular/common/locales/ar';
import localeEn from '@angular/common/locales/en';
import localeEsUS from '@angular/common/locales/es-US';
import localeFr from '@angular/common/locales/fr';
import {ɵDEFAULT_LOCALE_ID, ɵregisterLocaleData, ɵunregisterLocaleData} from '@angular/core';
d | {
"end_byte": 586,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/i18n/format_number_spec.ts"
} |
angular/packages/common/test/i18n/format_number_spec.ts_588_7538 | cribe('Format number', () => {
beforeAll(() => {
ɵregisterLocaleData(localeEn);
ɵregisterLocaleData(localeEsUS);
ɵregisterLocaleData(localeFr);
ɵregisterLocaleData(localeAr);
});
afterAll(() => ɵunregisterLocaleData());
describe('Number', () => {
describe('transform', () => {
it('should return correct value for numbers', () => {
expect(formatNumber(12345, ɵDEFAULT_LOCALE_ID)).toEqual('12,345');
expect(formatNumber(123, ɵDEFAULT_LOCALE_ID, '.2')).toEqual('123.00');
expect(formatNumber(1, ɵDEFAULT_LOCALE_ID, '3.')).toEqual('001');
expect(formatNumber(1.1, ɵDEFAULT_LOCALE_ID, '3.4-5')).toEqual('001.1000');
expect(formatNumber(1.123456, ɵDEFAULT_LOCALE_ID, '3.4-5')).toEqual('001.12346');
expect(formatNumber(1.1234, ɵDEFAULT_LOCALE_ID)).toEqual('1.123');
expect(formatNumber(1.123456, ɵDEFAULT_LOCALE_ID, '.2')).toEqual('1.123');
expect(formatNumber(1.123456, ɵDEFAULT_LOCALE_ID, '.4')).toEqual('1.1235');
expect(formatNumber(1e100, ɵDEFAULT_LOCALE_ID)).toEqual('1E+100');
});
it('should throw if minFractionDigits is explicitly higher than maxFractionDigits', () => {
expect(() => formatNumber(1.1, ɵDEFAULT_LOCALE_ID, '3.4-2')).toThrowError(
/is higher than the maximum/,
);
});
});
describe('transform with custom locales', () => {
it('should return the correct format for es-US', () => {
expect(formatNumber(9999999.99, 'es-US', '1.2-2')).toEqual('9,999,999.99');
});
it('should support non-normalized locales', () => {
expect(formatNumber(12345, 'en-US')).toEqual('12,345');
expect(formatNumber(12345, 'en_US')).toEqual('12,345');
expect(formatNumber(12345, 'en_us')).toEqual('12,345');
});
});
});
describe('Percent', () => {
describe('transform', () => {
it('should return correct value for numbers', () => {
expect(formatPercent(1.23, ɵDEFAULT_LOCALE_ID)).toEqual('123%');
expect(formatPercent(1.2, ɵDEFAULT_LOCALE_ID, '.2')).toEqual('120.00%');
expect(formatPercent(1.2, ɵDEFAULT_LOCALE_ID, '4.2')).toEqual('0,120.00%');
expect(formatPercent(0, ɵDEFAULT_LOCALE_ID)).toEqual('0%');
expect(formatPercent(-0, ɵDEFAULT_LOCALE_ID)).toEqual('0%');
expect(formatPercent(1.2, 'fr', '4.2')).toEqual('0\u202f120,00 %');
expect(formatPercent(1.2, 'ar', '4.2')).toEqual('0,120.00%');
// see issue #20136
expect(formatPercent(0.12345674, ɵDEFAULT_LOCALE_ID, '0.0-10')).toEqual('12.345674%');
expect(formatPercent(0, ɵDEFAULT_LOCALE_ID, '0.0-10')).toEqual('0%');
expect(formatPercent(0.0, ɵDEFAULT_LOCALE_ID, '0.0-10')).toEqual('0%');
expect(formatPercent(1, ɵDEFAULT_LOCALE_ID, '0.0-10')).toEqual('100%');
expect(formatPercent(0.1, ɵDEFAULT_LOCALE_ID, '0.0-10')).toEqual('10%');
expect(formatPercent(0.12, ɵDEFAULT_LOCALE_ID, '0.0-10')).toEqual('12%');
expect(formatPercent(0.123, ɵDEFAULT_LOCALE_ID, '0.0-10')).toEqual('12.3%');
expect(formatPercent(12.3456, ɵDEFAULT_LOCALE_ID, '0.0-10')).toEqual('1,234.56%');
expect(formatPercent(12.3456, ɵDEFAULT_LOCALE_ID, '0.0-10')).toEqual('1,234.56%');
expect(formatPercent(12.345699999, ɵDEFAULT_LOCALE_ID, '0.0-6')).toEqual('1,234.57%');
expect(formatPercent(12.345699999, ɵDEFAULT_LOCALE_ID, '0.4-6')).toEqual('1,234.5700%');
expect(formatPercent(100, ɵDEFAULT_LOCALE_ID, '0.4-6')).toEqual('10,000.0000%');
expect(formatPercent(100, ɵDEFAULT_LOCALE_ID, '0.0-10')).toEqual('10,000%');
expect(formatPercent(1.5e2, ɵDEFAULT_LOCALE_ID)).toEqual('15,000%');
expect(formatPercent(1e100, ɵDEFAULT_LOCALE_ID)).toEqual('1E+102%');
});
it('should support non-normalized locales', () => {
expect(formatPercent(1.23, 'en-US')).toEqual('123%');
expect(formatPercent(1.23, 'en_US')).toEqual('123%');
expect(formatPercent(1.23, 'en_us')).toEqual('123%');
});
});
});
describe('Currency', () => {
const defaultCurrencyCode = 'USD';
describe('transform', () => {
it('should return correct value for numbers', () => {
expect(formatCurrency(123, ɵDEFAULT_LOCALE_ID, '$')).toEqual('$123.00');
expect(formatCurrency(12, ɵDEFAULT_LOCALE_ID, 'EUR', 'EUR', '.1')).toEqual('EUR12.0');
expect(
formatCurrency(
5.1234,
ɵDEFAULT_LOCALE_ID,
defaultCurrencyCode,
defaultCurrencyCode,
'.0-3',
),
).toEqual('USD5.123');
expect(formatCurrency(5.1234, ɵDEFAULT_LOCALE_ID, defaultCurrencyCode)).toEqual('USD5.12');
expect(formatCurrency(5.1234, ɵDEFAULT_LOCALE_ID, '$')).toEqual('$5.12');
expect(formatCurrency(5.1234, ɵDEFAULT_LOCALE_ID, 'CA$')).toEqual('CA$5.12');
expect(formatCurrency(5.1234, ɵDEFAULT_LOCALE_ID, '$')).toEqual('$5.12');
expect(
formatCurrency(5.1234, ɵDEFAULT_LOCALE_ID, '$', defaultCurrencyCode, '5.2-2'),
).toEqual('$00,005.12');
expect(formatCurrency(5.1234, 'fr', '$', defaultCurrencyCode, '5.2-2')).toEqual(
'00\u202f005,12 $',
);
expect(formatCurrency(5, 'fr', '$US', defaultCurrencyCode)).toEqual('5,00 $US');
});
it('should support any currency code name', () => {
// currency code is unknown, default formatting options will be used
expect(formatCurrency(5.1234, ɵDEFAULT_LOCALE_ID, 'unexisting_ISO_code')).toEqual(
'unexisting_ISO_code5.12',
);
// currency code is USD, the pipe will format based on USD but will display "Custom name"
expect(formatCurrency(5.1234, ɵDEFAULT_LOCALE_ID, 'Custom name')).toEqual(
'Custom name5.12',
);
});
it('should round to the default number of digits if no digitsInfo', () => {
// GNF has a default number of digits of 0
expect(formatCurrency(5.1234, ɵDEFAULT_LOCALE_ID, 'GNF', 'GNF')).toEqual('GNF5');
expect(formatCurrency(5.1234, ɵDEFAULT_LOCALE_ID, 'GNF', 'GNF', '.2')).toEqual('GNF5.12');
expect(formatCurrency(5.1234, ɵDEFAULT_LOCALE_ID, 'Custom name', 'GNF')).toEqual(
'Custom name5',
);
// BHD has a default number of digits of 3
expect(formatCurrency(5.1234, ɵDEFAULT_LOCALE_ID, 'BHD', 'BHD')).toEqual('BHD5.123');
expect(formatCurrency(5.1234, ɵDEFAULT_LOCALE_ID, 'BHD', 'BHD', '.1-2')).toEqual('BHD5.12');
});
it('should support non-normalized locales', () => {
expect(formatCurrency(12345, 'en-US', 'USD')).toEqual('USD12,345.00');
expect(formatCurrency(12345, 'en_US', 'USD')).toEqual('USD12,345.00');
expect(formatCurrency(12345, 'en_us', 'USD')).toEqual('USD12,345.00');
});
});
});
});
| {
"end_byte": 7538,
"start_byte": 588,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/i18n/format_number_spec.ts"
} |
angular/packages/common/test/i18n/locale_data_api_spec.ts_0_6862 | /**
* @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 localeEn from '@angular/common/locales/en';
import localeEnAU from '@angular/common/locales/en-AU';
import localeFr from '@angular/common/locales/fr';
import localeHe from '@angular/common/locales/he';
import localeZh from '@angular/common/locales/zh';
import {ɵregisterLocaleData, ɵunregisterLocaleData} from '@angular/core';
import {
FormatWidth,
FormStyle,
getCurrencySymbol,
getLocaleDateFormat,
getLocaleDayNames,
getLocaleDirection,
getLocaleMonthNames,
getNumberOfCurrencyDigits,
TranslationWidth,
} from '@angular/common';
describe('locale data api', () => {
beforeAll(() => {
ɵregisterLocaleData(localeEn);
ɵregisterLocaleData(localeFr);
ɵregisterLocaleData(localeZh);
ɵregisterLocaleData(localeEnAU);
ɵregisterLocaleData(localeHe);
});
afterAll(() => {
ɵunregisterLocaleData();
});
describe('getting currency symbol', () => {
it('should return the correct symbol', () => {
expect(getCurrencySymbol('USD', 'wide')).toEqual('$');
expect(getCurrencySymbol('USD', 'narrow')).toEqual('$');
expect(getCurrencySymbol('AUD', 'wide')).toEqual('A$');
expect(getCurrencySymbol('AUD', 'narrow')).toEqual('$');
expect(getCurrencySymbol('CRC', 'wide')).toEqual('CRC');
expect(getCurrencySymbol('CRC', 'narrow')).toEqual('₡');
expect(getCurrencySymbol('unexisting_ISO_code', 'wide')).toEqual('unexisting_ISO_code');
expect(getCurrencySymbol('unexisting_ISO_code', 'narrow')).toEqual('unexisting_ISO_code');
expect(getCurrencySymbol('USD', 'wide', 'en-AU')).toEqual('USD');
expect(getCurrencySymbol('USD', 'narrow', 'en-AU')).toEqual('$');
expect(getCurrencySymbol('AUD', 'wide', 'en-AU')).toEqual('$');
expect(getCurrencySymbol('AUD', 'narrow', 'en-AU')).toEqual('$');
expect(getCurrencySymbol('USD', 'wide', 'fr')).toEqual('$US');
});
});
describe('getNbOfCurrencyDigits', () => {
it('should return the correct value', () => {
expect(getNumberOfCurrencyDigits('USD')).toEqual(2);
expect(getNumberOfCurrencyDigits('GNF')).toEqual(0);
expect(getNumberOfCurrencyDigits('BHD')).toEqual(3);
expect(getNumberOfCurrencyDigits('unexisting_ISO_code')).toEqual(2);
});
});
describe('getLastDefinedValue', () => {
it('should find the last defined date format when format not defined', () => {
expect(getLocaleDateFormat('zh', FormatWidth.Long)).toEqual('y年M月d日');
});
});
describe('getDirectionality', () => {
it('should have correct direction for rtl languages', () => {
expect(getLocaleDirection('he')).toEqual('rtl');
});
it('should have correct direction for ltr languages', () => {
expect(getLocaleDirection('en')).toEqual('ltr');
});
});
describe('getLocaleDayNames', () => {
it('should return english short list of days', () => {
expect(getLocaleDayNames('en-US', FormStyle.Format, TranslationWidth.Short)).toEqual([
'Su',
'Mo',
'Tu',
'We',
'Th',
'Fr',
'Sa',
]);
});
it('should return french short list of days', () => {
expect(getLocaleDayNames('fr-CA', FormStyle.Format, TranslationWidth.Short)).toEqual([
'di',
'lu',
'ma',
'me',
'je',
've',
'sa',
]);
});
it('should return english wide list of days', () => {
expect(getLocaleDayNames('en-US', FormStyle.Format, TranslationWidth.Wide)).toEqual([
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
]);
});
it('should return french wide list of days', () => {
expect(getLocaleDayNames('fr-CA', FormStyle.Format, TranslationWidth.Wide)).toEqual([
'dimanche',
'lundi',
'mardi',
'mercredi',
'jeudi',
'vendredi',
'samedi',
]);
});
it('should return the full short list of days after manipulations', () => {
const days = Array.from(getLocaleDayNames('en-US', FormStyle.Format, TranslationWidth.Short));
days.splice(2);
days.push('unexisting_day');
const newDays = getLocaleDayNames('en-US', FormStyle.Format, TranslationWidth.Short);
expect(newDays.length).toBe(7);
expect(newDays).toEqual(['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']);
});
});
describe('getLocaleMonthNames', () => {
it('should return english abbreviated list of month', () => {
expect(getLocaleMonthNames('en-US', FormStyle.Format, TranslationWidth.Abbreviated)).toEqual([
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
]);
});
it('should return french abbreviated list of month', () => {
expect(getLocaleMonthNames('fr-CA', FormStyle.Format, TranslationWidth.Abbreviated)).toEqual([
'janv.',
'févr.',
'mars',
'avr.',
'mai',
'juin',
'juil.',
'août',
'sept.',
'oct.',
'nov.',
'déc.',
]);
});
it('should return english wide list of month', () => {
expect(getLocaleMonthNames('en-US', FormStyle.Format, TranslationWidth.Wide)).toEqual([
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
]);
});
it('should return french wide list of month', () => {
expect(getLocaleMonthNames('fr-CA', FormStyle.Format, TranslationWidth.Wide)).toEqual([
'janvier',
'février',
'mars',
'avril',
'mai',
'juin',
'juillet',
'août',
'septembre',
'octobre',
'novembre',
'décembre',
]);
});
it('should return the full abbreviated list of month after manipulations', () => {
const month = Array.from(
getLocaleMonthNames('en-US', FormStyle.Format, TranslationWidth.Abbreviated),
);
month.splice(2);
month.push('unexisting_month');
const newMonth = getLocaleMonthNames('en-US', FormStyle.Format, TranslationWidth.Abbreviated);
expect(newMonth.length).toBe(12);
expect(newMonth).toEqual([
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
]);
});
});
});
| {
"end_byte": 6862,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/i18n/locale_data_api_spec.ts"
} |
angular/packages/common/test/i18n/localization_spec.ts_0_7445 | /**
* @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 localeFr from '@angular/common/locales/fr';
import localeRo from '@angular/common/locales/ro';
import localeSr from '@angular/common/locales/sr';
import localeZgh from '@angular/common/locales/zgh';
import {
getPluralCategory,
NgLocaleLocalization,
NgLocalization,
} from '@angular/common/src/i18n/localization';
import {LOCALE_ID, ɵregisterLocaleData, ɵunregisterLocaleData} from '@angular/core';
import {inject, TestBed} from '@angular/core/testing';
describe('l10n', () => {
beforeAll(() => {
ɵregisterLocaleData(localeRo);
ɵregisterLocaleData(localeSr);
ɵregisterLocaleData(localeZgh);
ɵregisterLocaleData(localeFr);
});
afterAll(() => ɵunregisterLocaleData());
describe('NgLocalization', () => {
function roTests() {
it('should return plural cases for the provided locale', inject(
[NgLocalization],
(l10n: NgLocalization) => {
expect(l10n.getPluralCategory(0)).toEqual('few');
expect(l10n.getPluralCategory(1)).toEqual('one');
expect(l10n.getPluralCategory(1212)).toEqual('few');
expect(l10n.getPluralCategory(1223)).toEqual('other');
},
));
}
describe('ro', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{provide: LOCALE_ID, useValue: 'ro'}],
});
});
roTests();
});
function srTests() {
it('should return plural cases for the provided locale', inject(
[NgLocalization],
(l10n: NgLocalization) => {
expect(l10n.getPluralCategory(1)).toEqual('one');
expect(l10n.getPluralCategory(2.1)).toEqual('one');
expect(l10n.getPluralCategory(3)).toEqual('few');
expect(l10n.getPluralCategory(0.2)).toEqual('few');
expect(l10n.getPluralCategory(2.11)).toEqual('other');
expect(l10n.getPluralCategory(2.12)).toEqual('other');
},
));
}
describe('sr', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{provide: LOCALE_ID, useValue: 'sr'}],
});
});
srTests();
});
});
describe('NgLocaleLocalization', () => {
it('should return the correct values for the "en" locale', () => {
const l10n = new NgLocaleLocalization('en-US');
expect(l10n.getPluralCategory(0)).toEqual('other');
expect(l10n.getPluralCategory(1)).toEqual('one');
expect(l10n.getPluralCategory(2)).toEqual('other');
});
it('should return the correct values for the "ro" locale', () => {
const l10n = new NgLocaleLocalization('ro');
expect(l10n.getPluralCategory(0)).toEqual('few');
expect(l10n.getPluralCategory(1)).toEqual('one');
expect(l10n.getPluralCategory(2)).toEqual('few');
expect(l10n.getPluralCategory(12)).toEqual('few');
expect(l10n.getPluralCategory(23)).toEqual('other');
expect(l10n.getPluralCategory(1212)).toEqual('few');
expect(l10n.getPluralCategory(1223)).toEqual('other');
});
it('should return the correct values for the "sr" locale', () => {
const l10n = new NgLocaleLocalization('sr');
expect(l10n.getPluralCategory(1)).toEqual('one');
expect(l10n.getPluralCategory(31)).toEqual('one');
expect(l10n.getPluralCategory(0.1)).toEqual('one');
expect(l10n.getPluralCategory(1.1)).toEqual('one');
expect(l10n.getPluralCategory(2.1)).toEqual('one');
expect(l10n.getPluralCategory(3)).toEqual('few');
expect(l10n.getPluralCategory(33)).toEqual('few');
expect(l10n.getPluralCategory(0.2)).toEqual('few');
expect(l10n.getPluralCategory(0.3)).toEqual('few');
expect(l10n.getPluralCategory(0.4)).toEqual('few');
expect(l10n.getPluralCategory(2.2)).toEqual('few');
expect(l10n.getPluralCategory(2.11)).toEqual('other');
expect(l10n.getPluralCategory(2.12)).toEqual('other');
expect(l10n.getPluralCategory(2.13)).toEqual('other');
expect(l10n.getPluralCategory(2.14)).toEqual('other');
expect(l10n.getPluralCategory(2.15)).toEqual('other');
expect(l10n.getPluralCategory(0)).toEqual('other');
expect(l10n.getPluralCategory(5)).toEqual('other');
expect(l10n.getPluralCategory(10)).toEqual('other');
expect(l10n.getPluralCategory(35)).toEqual('other');
expect(l10n.getPluralCategory(37)).toEqual('other');
expect(l10n.getPluralCategory(40)).toEqual('other');
expect(l10n.getPluralCategory(0.0)).toEqual('other');
expect(l10n.getPluralCategory(0.5)).toEqual('other');
expect(l10n.getPluralCategory(0.6)).toEqual('other');
expect(l10n.getPluralCategory(2)).toEqual('few');
expect(l10n.getPluralCategory(2.1)).toEqual('one');
expect(l10n.getPluralCategory(2.2)).toEqual('few');
expect(l10n.getPluralCategory(2.3)).toEqual('few');
expect(l10n.getPluralCategory(2.4)).toEqual('few');
expect(l10n.getPluralCategory(2.5)).toEqual('other');
expect(l10n.getPluralCategory(20)).toEqual('other');
expect(l10n.getPluralCategory(21)).toEqual('one');
expect(l10n.getPluralCategory(22)).toEqual('few');
expect(l10n.getPluralCategory(23)).toEqual('few');
expect(l10n.getPluralCategory(24)).toEqual('few');
expect(l10n.getPluralCategory(25)).toEqual('other');
});
it('should return the default value for a locale with no rule', () => {
const l10n = new NgLocaleLocalization('zgh');
expect(l10n.getPluralCategory(0)).toEqual('other');
expect(l10n.getPluralCategory(1)).toEqual('other');
expect(l10n.getPluralCategory(3)).toEqual('other');
expect(l10n.getPluralCategory(5)).toEqual('other');
expect(l10n.getPluralCategory(10)).toEqual('other');
});
});
describe('getPluralCategory', () => {
it('should return plural category', () => {
const l10n = new NgLocaleLocalization('fr');
expect(getPluralCategory(0, ['one', 'other'], l10n)).toEqual('one');
expect(getPluralCategory(1, ['one', 'other'], l10n)).toEqual('one');
expect(getPluralCategory(5, ['one', 'other'], l10n)).toEqual('other');
});
it('should return discrete cases', () => {
const l10n = new NgLocaleLocalization('fr');
expect(getPluralCategory(0, ['one', 'other', '=0'], l10n)).toEqual('=0');
expect(getPluralCategory(1, ['one', 'other'], l10n)).toEqual('one');
expect(getPluralCategory(5, ['one', 'other', '=5'], l10n)).toEqual('=5');
expect(getPluralCategory(6, ['one', 'other', '=5'], l10n)).toEqual('other');
});
it('should fallback to other when the case is not present', () => {
const l10n = new NgLocaleLocalization('ro');
expect(getPluralCategory(1, ['one', 'other'], l10n)).toEqual('one');
// 2 -> 'few'
expect(getPluralCategory(2, ['one', 'other'], l10n)).toEqual('other');
});
describe('errors', () => {
it('should report an error when the "other" category is not present', () => {
expect(() => {
const l10n = new NgLocaleLocalization('ro');
// 2 -> 'few'
getPluralCategory(2, ['one'], l10n);
}).toThrowError('No plural message found for value "2"');
});
});
});
});
| {
"end_byte": 7445,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/i18n/localization_spec.ts"
} |
angular/packages/common/test/i18n/format_date_spec.ts_0_2126 | /**
* @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 localeAr from '@angular/common/locales/ar';
import localeDe from '@angular/common/locales/de';
import localeEn from '@angular/common/locales/en';
import localeEnExtra from '@angular/common/locales/extra/en';
import localeFi from '@angular/common/locales/fi';
import localeHu from '@angular/common/locales/hu';
import localeSr from '@angular/common/locales/sr';
import localeTh from '@angular/common/locales/th';
import {
formatDate,
getThursdayThisIsoWeek,
isDate,
toDate,
} from '@angular/common/src/i18n/format_date';
import {ɵDEFAULT_LOCALE_ID, ɵregisterLocaleData, ɵunregisterLocaleData} from '@angular/core';
describe('Format date', () => {
describe('toDate', () => {
it('should support date', () => {
expect(isDate(toDate(new Date()))).toBeTruthy();
});
it('should support int', () => {
expect(isDate(toDate(123456789))).toBeTruthy();
});
it('should support numeric strings', () => {
expect(isDate(toDate('123456789'))).toBeTruthy();
});
it('should support decimal strings', () => {
expect(isDate(toDate('123456789.11'))).toBeTruthy();
});
it('should support ISO string', () => {
expect(isDate(toDate('2015-06-15T21:43:11Z'))).toBeTruthy();
});
it('should support strings with a 5-digit date', () => {
expect(isDate(toDate('22015-06-15'))).toBeTruthy();
});
it('should throw for empty string', () => {
expect(() => toDate('')).toThrow();
});
it('should throw for alpha numeric strings', () => {
expect(() => toDate('123456789 hello')).toThrow();
});
it('should throw for NaN', () => {
expect(() => toDate(Number.NaN)).toThrow();
});
it('should support ISO string without time', () => {
expect(isDate(toDate('2015-01-01'))).toBeTruthy();
});
it('should throw for objects', () => {
expect(() => toDate({} as any)).toThrow();
});
});
| {
"end_byte": 2126,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/i18n/format_date_spec.ts"
} |
angular/packages/common/test/i18n/format_date_spec.ts_2130_8103 | cribe('formatDate', () => {
const isoStringWithoutTime = '2015-01-01';
const isoStringWithoutTimeOrDate = '2015-01';
const isoStringWithoutTimeOrDateOrMonth = '2015';
const defaultFormat = 'mediumDate';
const date = new Date(2015, 5, 15, 9, 3, 1, 550);
// Check the transformation of a date into a pattern
function expectDateFormatAs(date: Date | string, pattern: any, output: string): void {
expect(formatDate(date, pattern, ɵDEFAULT_LOCALE_ID)).toEqual(
output,
`pattern: "${pattern}"`,
);
}
beforeAll(() => {
ɵregisterLocaleData(localeEn, localeEnExtra);
ɵregisterLocaleData(localeDe);
ɵregisterLocaleData(localeHu);
ɵregisterLocaleData(localeSr);
ɵregisterLocaleData(localeTh);
ɵregisterLocaleData(localeAr);
ɵregisterLocaleData(localeFi);
});
afterAll(() => ɵunregisterLocaleData());
it('should format each component correctly', () => {
const dateFixtures: any = {
G: 'AD',
GG: 'AD',
GGG: 'AD',
GGGG: 'Anno Domini',
GGGGG: 'A',
y: '2015',
yy: '15',
yyy: '2015',
yyyy: '2015',
Y: '2015',
YY: '15',
YYY: '2015',
YYYY: '2015',
M: '6',
MM: '06',
MMM: 'Jun',
MMMM: 'June',
MMMMM: 'J',
L: '6',
LL: '06',
LLL: 'Jun',
LLLL: 'June',
LLLLL: 'J',
w: '25',
ww: '25',
W: '3',
d: '15',
dd: '15',
c: '1',
cc: '1',
ccc: 'Mon',
cccc: 'Monday',
ccccc: 'M',
cccccc: 'Mo',
E: 'Mon',
EE: 'Mon',
EEE: 'Mon',
EEEE: 'Monday',
EEEEEE: 'Mo',
h: '9',
hh: '09',
H: '9',
HH: '09',
m: '3',
mm: '03',
s: '1',
ss: '01',
S: '5',
SS: '55',
SSS: '550',
a: 'AM',
aa: 'AM',
aaa: 'AM',
aaaa: 'AM',
aaaaa: 'a',
b: 'morning',
bb: 'morning',
bbb: 'morning',
bbbb: 'morning',
bbbbb: 'morning',
B: 'in the morning',
BB: 'in the morning',
BBB: 'in the morning',
BBBB: 'in the morning',
BBBBB: 'in the morning',
};
const isoStringWithoutTimeFixtures: any = {
G: 'AD',
GG: 'AD',
GGG: 'AD',
GGGG: 'Anno Domini',
GGGGG: 'A',
y: '2015',
yy: '15',
yyy: '2015',
yyyy: '2015',
Y: '2015',
YY: '15',
YYY: '2015',
YYYY: '2015',
M: '1',
MM: '01',
MMM: 'Jan',
MMMM: 'January',
MMMMM: 'J',
L: '1',
LL: '01',
LLL: 'Jan',
LLLL: 'January',
LLLLL: 'J',
w: '1',
ww: '01',
W: '1',
d: '1',
dd: '01',
c: '4',
cc: '4',
ccc: 'Thu',
cccc: 'Thursday',
ccccc: 'T',
cccccc: 'Th',
E: 'Thu',
EE: 'Thu',
EEE: 'Thu',
EEEE: 'Thursday',
EEEEE: 'T',
EEEEEE: 'Th',
h: '12',
hh: '12',
H: '0',
HH: '00',
m: '0',
mm: '00',
s: '0',
ss: '00',
S: '0',
SS: '00',
SSS: '000',
a: 'AM',
aa: 'AM',
aaa: 'AM',
aaaa: 'AM',
aaaaa: 'a',
b: 'midnight',
bb: 'midnight',
bbb: 'midnight',
bbbb: 'midnight',
bbbbb: 'midnight',
B: 'midnight',
BB: 'midnight',
BBB: 'midnight',
BBBB: 'midnight',
BBBBB: 'mi',
};
const midnightCrossingPeriods: any = {
b: 'night',
bb: 'night',
bbb: 'night',
bbbb: 'night',
bbbbb: 'night',
B: 'at night',
BB: 'at night',
BBB: 'at night',
BBBB: 'at night',
BBBBB: 'at night',
};
Object.keys(dateFixtures).forEach((pattern: string) => {
expectDateFormatAs(date, pattern, dateFixtures[pattern]);
});
Object.keys(isoStringWithoutTimeFixtures).forEach((pattern: string) => {
expectDateFormatAs(isoStringWithoutTime, pattern, isoStringWithoutTimeFixtures[pattern]);
});
Object.keys(isoStringWithoutTimeFixtures).forEach((pattern: string) => {
expectDateFormatAs(
isoStringWithoutTimeOrDate,
pattern,
isoStringWithoutTimeFixtures[pattern],
);
});
Object.keys(isoStringWithoutTimeFixtures).forEach((pattern: string) => {
expectDateFormatAs(
isoStringWithoutTimeOrDateOrMonth,
pattern,
isoStringWithoutTimeFixtures[pattern],
);
});
const nightTime = new Date(2015, 5, 15, 2, 3, 1, 550);
Object.keys(midnightCrossingPeriods).forEach((pattern) => {
expectDateFormatAs(nightTime, pattern, midnightCrossingPeriods[pattern]);
});
});
it('should support non-normalized locales', () => {
expect(formatDate(date, 'short', 'de-DE')).toEqual('15.06.15, 09:03');
expect(formatDate(date, 'short', 'de_DE')).toEqual('15.06.15, 09:03');
expect(formatDate(date, 'short', 'de-de')).toEqual('15.06.15, 09:03');
});
it('should format with timezones', () => {
const dateFixtures: any = {
z: /GMT(\+|-)\d/,
zz: /GMT(\+|-)\d/,
zzz: /GMT(\+|-)\d/,
zzzz: /GMT(\+|-)\d{2}\:30/,
Z: /(\+|-)\d{2}30/,
ZZ: /(\+|-)\d{2}30/,
ZZZ: /(\+|-)\d{2}30/,
ZZZZ: /GMT(\+|-)\d{2}\:30/,
ZZZZZ: /(\+|-)\d{2}\:30/,
O: /GMT(\+|-)\d/,
OOOO: /GMT(\+|-)\d{2}\:30/,
};
Object.keys(dateFixtures).forEach((pattern: string) => {
expect(formatDate(date, pattern, ɵDEFAULT_LOCALE_ID, '+0430')).toMatch(
dateFixtures[pattern],
);
});
});
it('sho | {
"end_byte": 8103,
"start_byte": 2130,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/i18n/format_date_spec.ts"
} |
angular/packages/common/test/i18n/format_date_spec.ts_8109_13726 | rmat common multi component patterns', () => {
const dateFixtures: any = {
'EEE, M/d/y': 'Mon, 6/15/2015',
'EEE, M/d': 'Mon, 6/15',
'MMM d': 'Jun 15',
'dd/MM/yyyy': '15/06/2015',
'MM/dd/yyyy': '06/15/2015',
'yMEEEd': '20156Mon15',
'MEEEd': '6Mon15',
'MMMd': 'Jun15',
'EEEE, MMMM d, y': 'Monday, June 15, 2015',
'H:mm a': '9:03 AM',
'ms': '31',
'MM/dd/yy hh:mm': '06/15/15 09:03',
'MM/dd/y': '06/15/2015',
};
Object.keys(dateFixtures).forEach((pattern: string) => {
expectDateFormatAs(date, pattern, dateFixtures[pattern]);
});
});
it('should format with pattern aliases', () => {
const dateFixtures: any = {
'MM/dd/yyyy': '06/15/2015',
shortDate: '6/15/15',
mediumDate: 'Jun 15, 2015',
longDate: 'June 15, 2015',
fullDate: 'Monday, June 15, 2015',
short: '6/15/15, 9:03 AM',
medium: 'Jun 15, 2015, 9:03:01 AM',
long: /June 15, 2015 at 9:03:01 AM GMT(\+|-)\d/,
full: /Monday, June 15, 2015 at 9:03:01 AM GMT(\+|-)\d{2}:\d{2}/,
shortTime: '9:03 AM',
mediumTime: '9:03:01 AM',
longTime: /9:03:01 AM GMT(\+|-)\d/,
fullTime: /9:03:01 AM GMT(\+|-)\d{2}:\d{2}/,
};
Object.keys(dateFixtures).forEach((pattern: string) => {
expect(formatDate(date, pattern, ɵDEFAULT_LOCALE_ID)).toMatch(dateFixtures[pattern]);
});
});
it('should format invalid in IE ISO date', () =>
expect(formatDate('2017-01-11T12:00:00.014-0500', defaultFormat, ɵDEFAULT_LOCALE_ID)).toEqual(
'Jan 11, 2017',
));
it('should format invalid in Safari ISO date', () =>
expect(formatDate('2017-01-20T12:00:00+0000', defaultFormat, ɵDEFAULT_LOCALE_ID)).toEqual(
'Jan 20, 2017',
));
// https://github.com/angular/angular/issues/9524
// https://github.com/angular/angular/issues/9524
it('should format correctly with iso strings that contain time', () =>
expect(formatDate('2017-05-07T22:14:39', 'dd-MM-yyyy HH:mm', ɵDEFAULT_LOCALE_ID)).toMatch(
/07-05-2017 \d{2}:\d{2}/,
));
// https://github.com/angular/angular/issues/21491
it('should not assume UTC for iso strings in Safari if the timezone is not defined', () => {
// this test only works if the timezone is not in UTC
if (new Date().getTimezoneOffset() !== 0) {
expect(formatDate('2018-01-11T13:00:00', 'HH', ɵDEFAULT_LOCALE_ID)).not.toEqual(
formatDate('2018-01-11T13:00:00Z', 'HH', ɵDEFAULT_LOCALE_ID),
);
}
});
// https://github.com/angular/angular/issues/16624
// https://github.com/angular/angular/issues/17478
it('should show the correct time when the timezone is fixed', () => {
expect(
formatDate('2017-06-13T10:14:39+0000', 'shortTime', ɵDEFAULT_LOCALE_ID, '+0000'),
).toEqual('10:14 AM');
expect(formatDate('2017-06-13T10:14:39+0000', 'h:mm a', ɵDEFAULT_LOCALE_ID, '+0000')).toEqual(
'10:14 AM',
);
});
// The following test is disabled because backwards compatibility requires that date-only ISO
// strings are parsed with the local timezone.
// it('should create UTC date objects when an ISO string is passed with no time components',
// () => {
// expect(formatDate('2019-09-20', `MMM d, y, h:mm:ss a ZZZZZ`, ɵDEFAULT_LOCALE_ID))
// .toEqual('Sep 20, 2019, 12:00:00 AM Z');
// });
// This test is to ensure backward compatibility for parsing date-only ISO strings.
it('should create local timezone date objects when an ISO string is passed with no time components', () => {
// Dates created with individual components are evaluated against the local timezone. See
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#Individual_date_and_time_component_values
const localDate = new Date(2019, 8, 20, 0, 0, 0, 0);
expect(formatDate('2019-09-20', `MMM d, y, h:mm:ss a ZZZZZ`, ɵDEFAULT_LOCALE_ID)).toEqual(
formatDate(localDate, `MMM d, y, h:mm:ss a ZZZZZ`, ɵDEFAULT_LOCALE_ID),
);
});
it('should create local timezone date objects when an ISO string is passed with time components', () => {
const localDate = new Date(2019, 8, 20, 0, 0, 0, 0);
expect(
formatDate('2019-09-20T00:00:00', `MMM d, y, h:mm:ss a ZZZZZ`, ɵDEFAULT_LOCALE_ID),
).toEqual(formatDate(localDate, `MMM d, y, h:mm:ss a ZZZZZ`, ɵDEFAULT_LOCALE_ID));
});
it('should remove bidi control characters', () =>
expect(formatDate(date, 'MM/dd/yyyy', ɵDEFAULT_LOCALE_ID)!.length).toEqual(10));
it(`should format the date correctly in various locales`, () => {
expect(formatDate(date, 'short', 'de')).toEqual('15.06.15, 09:03');
expect(formatDate(date, 'short', 'ar')).toEqual('15/6/2015, 9:03 ص');
expect(formatDate(date, 'dd-MM-yy', 'th')).toEqual('15-06-15');
expect(formatDate(date, 'a', 'hu')).toEqual('de.');
expect(formatDate(date, 'a', 'sr')).toEqual('AM');
// TODO(ocombe): activate this test when we support local numbers
// expect(formatDate(date, 'hh', 'mr')).toEqual('०९');
});
it('should throw if we use getExtraDayPeriods without loading extra locale data', () => {
expect(() => formatDate(date, 'b', 'de')).toThrowError(
/Missing extra locale data for the locale "de"/,
);
});
// https://github.com/angular/angular/issues/24384
it('should not round fractional | {
"end_byte": 13726,
"start_byte": 8109,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/i18n/format_date_spec.ts"
} |
angular/packages/common/test/i18n/format_date_spec.ts_13731_18473 | nds', () => {
expect(formatDate(3999, 'm:ss', 'en')).toEqual('0:03');
expect(formatDate(3999, 'm:ss.S', 'en')).toEqual('0:03.9');
expect(formatDate(3999, 'm:ss.SS', 'en')).toEqual('0:03.99');
expect(formatDate(3999, 'm:ss.SSS', 'en')).toEqual('0:03.999');
expect(formatDate(3000, 'm:ss', 'en')).toEqual('0:03');
expect(formatDate(3000, 'm:ss.S', 'en')).toEqual('0:03.0');
expect(formatDate(3000, 'm:ss.SS', 'en')).toEqual('0:03.00');
expect(formatDate(3000, 'm:ss.SSS', 'en')).toEqual('0:03.000');
expect(formatDate(3001, 'm:ss', 'en')).toEqual('0:03');
expect(formatDate(3001, 'm:ss.S', 'en')).toEqual('0:03.0');
expect(formatDate(3001, 'm:ss.SS', 'en')).toEqual('0:03.00');
expect(formatDate(3001, 'm:ss.SSS', 'en')).toEqual('0:03.001');
});
// https://github.com/angular/angular/issues/38739
it('should return correct ISO 8601 week-numbering year for dates close to year end/beginning', () => {
expect(formatDate('2013-12-27', 'YYYY', 'en')).toEqual('2013');
expect(formatDate('2013-12-29', 'YYYY', 'en')).toEqual('2013');
expect(formatDate('2013-12-31', 'YYYY', 'en')).toEqual('2014');
// Dec. 31st is a Sunday, last day of the last week of 2023
expect(formatDate('2023-12-31', 'YYYY', 'en')).toEqual('2023');
expect(formatDate('2010-01-02', 'YYYY', 'en')).toEqual('2009');
expect(formatDate('2010-01-04', 'YYYY', 'en')).toEqual('2010');
expect(formatDate('0049-01-01', 'YYYY', 'en')).toEqual('0048');
expect(formatDate('0049-01-04', 'YYYY', 'en')).toEqual('0049');
});
// https://github.com/angular/angular/issues/53813
it('should return correct ISO 8601 week number close to year end/beginning', () => {
expect(formatDate('2013-12-27', 'w', 'en')).toEqual('52');
expect(formatDate('2013-12-29', 'w', 'en')).toEqual('52');
expect(formatDate('2013-12-31', 'w', 'en')).toEqual('1');
// Dec. 31st is a Sunday, last day of the last week of 2023
expect(formatDate('2023-12-31', 'w', 'en')).toEqual('52');
expect(formatDate('2010-01-02', 'w', 'en')).toEqual('53');
expect(formatDate('2010-01-04', 'w', 'en')).toEqual('1');
expect(formatDate('0049-01-01', 'w', 'en')).toEqual('53');
expect(formatDate('0049-01-04', 'w', 'en')).toEqual('1');
});
// https://github.com/angular/angular/issues/40377
it('should format date with year between 0 and 99 correctly', () => {
expect(formatDate('0098-01-11', 'YYYY', ɵDEFAULT_LOCALE_ID)).toEqual('0098');
expect(formatDate('0099-01-11', 'YYYY', ɵDEFAULT_LOCALE_ID)).toEqual('0099');
expect(formatDate('0100-01-11', 'YYYY', ɵDEFAULT_LOCALE_ID)).toEqual('0100');
expect(formatDate('0001-01-11', 'YYYY', ɵDEFAULT_LOCALE_ID)).toEqual('0001');
expect(formatDate('0000-01-11', 'YYYY', ɵDEFAULT_LOCALE_ID)).toEqual('0000');
});
// https://github.com/angular/angular/issues/26922
it('should support fullDate in finnish, which uses standalone week day', () => {
expect(formatDate(date, 'fullDate', 'fi')).toMatch('maanantai 15. kesäkuuta 2015');
});
it('should wrap negative years', () => {
const date = new Date(new Date('2024-01-13').setFullYear(-1)); // Year -1
expect(formatDate(date, 'yyyy', ɵDEFAULT_LOCALE_ID)).toEqual('0002');
});
it('should support years < 1000', () => {
expect(formatDate(new Date('0054-02-18'), 'yyy', ɵDEFAULT_LOCALE_ID)).toEqual('054');
expect(formatDate(new Date('0054-02-18'), 'yyyy', ɵDEFAULT_LOCALE_ID)).toEqual('0054');
expect(formatDate(new Date('0803-02-18'), 'yyyy', ɵDEFAULT_LOCALE_ID)).toEqual('0803');
});
it('should support timezones', () => {
const isoDate = '2024-02-17T12:00:00Z';
const date1 = formatDate(isoDate, 'long', 'en', 'America/New_York');
const date2 = formatDate(isoDate, 'long', 'en', 'EST');
expect(date1).toBe('February 17, 2024 at 12:00:00 PM GMT+0');
expect(date2).toBe('February 17, 2024 at 7:00:00 AM GMT-5');
const date3 = formatDate(isoDate, 'long', 'en', '+0500');
expect(date3).toBe('February 17, 2024 at 5:00:00 PM GMT+5');
});
it('should return thursday date of the same week', () => {
// Dec. 31st is a Sunday, last day of the last week of 2023
expect(getThursdayThisIsoWeek(new Date('2023-12-31'))).toEqual(new Date('2023-12-28'));
// Dec. 29th is a Thursday
expect(getThursdayThisIsoWeek(new Date('2022-12-29'))).toEqual(new Date('2022-12-29'));
// Jan 01st is a Monday
expect(getThursdayThisIsoWeek(new Date('2024-01-01'))).toEqual(new Date('2024-01-04'));
});
});
});
| {
"end_byte": 18473,
"start_byte": 13731,
"url": "https://github.com/angular/angular/blob/main/packages/common/test/i18n/format_date_spec.ts"
} |
angular/packages/common/testing/PACKAGE.md_0_80 | Supplies infrastructure for testing functionality supplied by `@angular/common`. | {
"end_byte": 80,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/PACKAGE.md"
} |
angular/packages/common/testing/BUILD.bazel_0_676 | load("//tools:defaults.bzl", "generate_api_docs", "ng_module")
package(default_visibility = ["//visibility:public"])
exports_files(["package.json"])
ng_module(
name = "testing",
srcs = glob(["**/*.ts"]),
deps = [
"//packages/common",
"//packages/core",
"@npm//rxjs",
],
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
generate_api_docs(
name = "common_testing_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
],
entry_point = ":index.ts",
module_name = "@angular/common/testing",
)
| {
"end_byte": 676,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/BUILD.bazel"
} |
angular/packages/common/testing/index.ts_0_481 | /**
* @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 file is not used to build this module. It is only used during editing
// by the TypeScript language service and during build for verification. `ngc`
// replaces this file with production index.ts when it rewrites private symbol
// names.
export * from './public_api';
| {
"end_byte": 481,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/index.ts"
} |
angular/packages/common/testing/public_api.ts_0_398 | /**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of this package.
*/
export * from './src/testing';
// This file only reexports content of the `src` folder. Keep it that way.
| {
"end_byte": 398,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/public_api.ts"
} |
angular/packages/common/testing/src/location_mock.ts_0_5920 | /**
* @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 {
Location,
LocationStrategy,
PopStateEvent,
ɵnormalizeQueryParams as normalizeQueryParams,
} from '@angular/common';
import {Injectable} from '@angular/core';
import {Subject, SubscriptionLike} from 'rxjs';
/**
* A spy for {@link Location} that allows tests to fire simulated location events.
*
* @publicApi
*/
@Injectable()
export class SpyLocation implements Location {
urlChanges: string[] = [];
private _history: LocationState[] = [new LocationState('', '', null)];
private _historyIndex: number = 0;
/** @internal */
_subject = new Subject<PopStateEvent>();
/** @internal */
_basePath: string = '';
/** @internal */
_locationStrategy: LocationStrategy = null!;
/** @internal */
_urlChangeListeners: ((url: string, state: unknown) => void)[] = [];
/** @internal */
_urlChangeSubscription: SubscriptionLike | null = null;
/** @nodoc */
ngOnDestroy(): void {
this._urlChangeSubscription?.unsubscribe();
this._urlChangeListeners = [];
}
setInitialPath(url: string) {
this._history[this._historyIndex].path = url;
}
setBaseHref(url: string) {
this._basePath = url;
}
path(): string {
return this._history[this._historyIndex].path;
}
getState(): unknown {
return this._history[this._historyIndex].state;
}
isCurrentPathEqualTo(path: string, query: string = ''): boolean {
const givenPath = path.endsWith('/') ? path.substring(0, path.length - 1) : path;
const currPath = this.path().endsWith('/')
? this.path().substring(0, this.path().length - 1)
: this.path();
return currPath == givenPath + (query.length > 0 ? '?' + query : '');
}
simulateUrlPop(pathname: string) {
this._subject.next({'url': pathname, 'pop': true, 'type': 'popstate'});
}
simulateHashChange(pathname: string) {
const path = this.prepareExternalUrl(pathname);
this.pushHistory(path, '', null);
this.urlChanges.push('hash: ' + pathname);
// the browser will automatically fire popstate event before each `hashchange` event, so we need
// to simulate it.
this._subject.next({'url': pathname, 'pop': true, 'type': 'popstate'});
this._subject.next({'url': pathname, 'pop': true, 'type': 'hashchange'});
}
prepareExternalUrl(url: string): string {
if (url.length > 0 && !url.startsWith('/')) {
url = '/' + url;
}
return this._basePath + url;
}
go(path: string, query: string = '', state: any = null) {
path = this.prepareExternalUrl(path);
this.pushHistory(path, query, state);
const locationState = this._history[this._historyIndex - 1];
if (locationState.path == path && locationState.query == query) {
return;
}
const url = path + (query.length > 0 ? '?' + query : '');
this.urlChanges.push(url);
this._notifyUrlChangeListeners(path + normalizeQueryParams(query), state);
}
replaceState(path: string, query: string = '', state: any = null) {
path = this.prepareExternalUrl(path);
const history = this._history[this._historyIndex];
history.state = state;
if (history.path == path && history.query == query) {
return;
}
history.path = path;
history.query = query;
const url = path + (query.length > 0 ? '?' + query : '');
this.urlChanges.push('replace: ' + url);
this._notifyUrlChangeListeners(path + normalizeQueryParams(query), state);
}
forward() {
if (this._historyIndex < this._history.length - 1) {
this._historyIndex++;
this._subject.next({
'url': this.path(),
'state': this.getState(),
'pop': true,
'type': 'popstate',
});
}
}
back() {
if (this._historyIndex > 0) {
this._historyIndex--;
this._subject.next({
'url': this.path(),
'state': this.getState(),
'pop': true,
'type': 'popstate',
});
}
}
historyGo(relativePosition: number = 0): void {
const nextPageIndex = this._historyIndex + relativePosition;
if (nextPageIndex >= 0 && nextPageIndex < this._history.length) {
this._historyIndex = nextPageIndex;
this._subject.next({
'url': this.path(),
'state': this.getState(),
'pop': true,
'type': 'popstate',
});
}
}
onUrlChange(fn: (url: string, state: unknown) => void): VoidFunction {
this._urlChangeListeners.push(fn);
this._urlChangeSubscription ??= this.subscribe((v) => {
this._notifyUrlChangeListeners(v.url, v.state);
});
return () => {
const fnIndex = this._urlChangeListeners.indexOf(fn);
this._urlChangeListeners.splice(fnIndex, 1);
if (this._urlChangeListeners.length === 0) {
this._urlChangeSubscription?.unsubscribe();
this._urlChangeSubscription = null;
}
};
}
/** @internal */
_notifyUrlChangeListeners(url: string = '', state: unknown) {
this._urlChangeListeners.forEach((fn) => fn(url, state));
}
subscribe(
onNext: (value: any) => void,
onThrow?: ((error: any) => void) | null,
onReturn?: (() => void) | null,
): SubscriptionLike {
return this._subject.subscribe({
next: onNext,
error: onThrow ?? undefined,
complete: onReturn ?? undefined,
});
}
normalize(url: string): string {
return null!;
}
private pushHistory(path: string, query: string, state: any) {
if (this._historyIndex > 0) {
this._history.splice(this._historyIndex + 1);
}
this._history.push(new LocationState(path, query, state));
this._historyIndex = this._history.length - 1;
}
}
class LocationState {
constructor(
public path: string,
public query: string,
public state: any,
) {}
}
| {
"end_byte": 5920,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/src/location_mock.ts"
} |
angular/packages/common/testing/src/testing.ts_0_642 | /**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of the common/testing package.
*/
export * from './private_export';
export {SpyLocation} from './location_mock';
export {MockLocationStrategy} from './mock_location_strategy';
export {
MOCK_PLATFORM_LOCATION_CONFIG,
MockPlatformLocation,
MockPlatformLocationConfig,
} from './mock_platform_location';
export {provideLocationMocks} from './provide_location_mocks';
| {
"end_byte": 642,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/src/testing.ts"
} |
angular/packages/common/testing/src/mock_platform_location.ts_0_2913 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
DOCUMENT,
LocationChangeEvent,
LocationChangeListener,
PlatformLocation,
ɵPlatformNavigation as PlatformNavigation,
} from '@angular/common';
import {Inject, inject, Injectable, InjectionToken, Optional} from '@angular/core';
import {Subject} from 'rxjs';
import {FakeNavigation} from './navigation/fake_navigation';
/**
* Parser from https://tools.ietf.org/html/rfc3986#appendix-B
* ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
* 12 3 4 5 6 7 8 9
*
* Example: http://www.ics.uci.edu/pub/ietf/uri/#Related
*
* Results in:
*
* $1 = http:
* $2 = http
* $3 = //www.ics.uci.edu
* $4 = www.ics.uci.edu
* $5 = /pub/ietf/uri/
* $6 = <undefined>
* $7 = <undefined>
* $8 = #Related
* $9 = Related
*/
const urlParse = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
function parseUrl(urlStr: string, baseHref: string) {
const verifyProtocol = /^((http[s]?|ftp):\/\/)/;
let serverBase: string | undefined;
// URL class requires full URL. If the URL string doesn't start with protocol, we need to add
// an arbitrary base URL which can be removed afterward.
if (!verifyProtocol.test(urlStr)) {
serverBase = 'http://empty.com/';
}
let parsedUrl: {
protocol: string;
hostname: string;
port: string;
pathname: string;
search: string;
hash: string;
};
try {
parsedUrl = new URL(urlStr, serverBase);
} catch (e) {
const result = urlParse.exec(serverBase || '' + urlStr);
if (!result) {
throw new Error(`Invalid URL: ${urlStr} with base: ${baseHref}`);
}
const hostSplit = result[4].split(':');
parsedUrl = {
protocol: result[1],
hostname: hostSplit[0],
port: hostSplit[1] || '',
pathname: result[5],
search: result[6],
hash: result[8],
};
}
if (parsedUrl.pathname && parsedUrl.pathname.indexOf(baseHref) === 0) {
parsedUrl.pathname = parsedUrl.pathname.substring(baseHref.length);
}
return {
hostname: (!serverBase && parsedUrl.hostname) || '',
protocol: (!serverBase && parsedUrl.protocol) || '',
port: (!serverBase && parsedUrl.port) || '',
pathname: parsedUrl.pathname || '/',
search: parsedUrl.search || '',
hash: parsedUrl.hash || '',
};
}
/**
* Mock platform location config
*
* @publicApi
*/
export interface MockPlatformLocationConfig {
startUrl?: string;
appBaseHref?: string;
}
/**
* Provider for mock platform location config
*
* @publicApi
*/
export const MOCK_PLATFORM_LOCATION_CONFIG = new InjectionToken<MockPlatformLocationConfig>(
'MOCK_PLATFORM_LOCATION_CONFIG',
);
/**
* Mock implementation of URL state.
*
* @publicApi
*/
| {
"end_byte": 2913,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/src/mock_platform_location.ts"
} |
angular/packages/common/testing/src/mock_platform_location.ts_2914_10232 | Injectable()
export class MockPlatformLocation implements PlatformLocation {
private baseHref: string = '';
private hashUpdate = new Subject<LocationChangeEvent>();
private popStateSubject = new Subject<LocationChangeEvent>();
private urlChangeIndex: number = 0;
private urlChanges: {
hostname: string;
protocol: string;
port: string;
pathname: string;
search: string;
hash: string;
state: unknown;
}[] = [{hostname: '', protocol: '', port: '', pathname: '/', search: '', hash: '', state: null}];
constructor(
@Inject(MOCK_PLATFORM_LOCATION_CONFIG) @Optional() config?: MockPlatformLocationConfig,
) {
if (config) {
this.baseHref = config.appBaseHref || '';
const parsedChanges = this.parseChanges(
null,
config.startUrl || 'http://_empty_/',
this.baseHref,
);
this.urlChanges[0] = {...parsedChanges};
}
}
get hostname() {
return this.urlChanges[this.urlChangeIndex].hostname;
}
get protocol() {
return this.urlChanges[this.urlChangeIndex].protocol;
}
get port() {
return this.urlChanges[this.urlChangeIndex].port;
}
get pathname() {
return this.urlChanges[this.urlChangeIndex].pathname;
}
get search() {
return this.urlChanges[this.urlChangeIndex].search;
}
get hash() {
return this.urlChanges[this.urlChangeIndex].hash;
}
get state() {
return this.urlChanges[this.urlChangeIndex].state;
}
getBaseHrefFromDOM(): string {
return this.baseHref;
}
onPopState(fn: LocationChangeListener): VoidFunction {
const subscription = this.popStateSubject.subscribe(fn);
return () => subscription.unsubscribe();
}
onHashChange(fn: LocationChangeListener): VoidFunction {
const subscription = this.hashUpdate.subscribe(fn);
return () => subscription.unsubscribe();
}
get href(): string {
let url = `${this.protocol}//${this.hostname}${this.port ? ':' + this.port : ''}`;
url += `${this.pathname === '/' ? '' : this.pathname}${this.search}${this.hash}`;
return url;
}
get url(): string {
return `${this.pathname}${this.search}${this.hash}`;
}
private parseChanges(state: unknown, url: string, baseHref: string = '') {
// When the `history.state` value is stored, it is always copied.
state = JSON.parse(JSON.stringify(state));
return {...parseUrl(url, baseHref), state};
}
replaceState(state: any, title: string, newUrl: string): void {
const {pathname, search, state: parsedState, hash} = this.parseChanges(state, newUrl);
this.urlChanges[this.urlChangeIndex] = {
...this.urlChanges[this.urlChangeIndex],
pathname,
search,
hash,
state: parsedState,
};
}
pushState(state: any, title: string, newUrl: string): void {
const {pathname, search, state: parsedState, hash} = this.parseChanges(state, newUrl);
if (this.urlChangeIndex > 0) {
this.urlChanges.splice(this.urlChangeIndex + 1);
}
this.urlChanges.push({
...this.urlChanges[this.urlChangeIndex],
pathname,
search,
hash,
state: parsedState,
});
this.urlChangeIndex = this.urlChanges.length - 1;
}
forward(): void {
const oldUrl = this.url;
const oldHash = this.hash;
if (this.urlChangeIndex < this.urlChanges.length) {
this.urlChangeIndex++;
}
this.emitEvents(oldHash, oldUrl);
}
back(): void {
const oldUrl = this.url;
const oldHash = this.hash;
if (this.urlChangeIndex > 0) {
this.urlChangeIndex--;
}
this.emitEvents(oldHash, oldUrl);
}
historyGo(relativePosition: number = 0): void {
const oldUrl = this.url;
const oldHash = this.hash;
const nextPageIndex = this.urlChangeIndex + relativePosition;
if (nextPageIndex >= 0 && nextPageIndex < this.urlChanges.length) {
this.urlChangeIndex = nextPageIndex;
}
this.emitEvents(oldHash, oldUrl);
}
getState(): unknown {
return this.state;
}
/**
* Browsers are inconsistent in when they fire events and perform the state updates
* The most easiest thing to do in our mock is synchronous and that happens to match
* Firefox and Chrome, at least somewhat closely
*
* https://github.com/WICG/navigation-api#watching-for-navigations
* https://docs.google.com/document/d/1Pdve-DJ1JCGilj9Yqf5HxRJyBKSel5owgOvUJqTauwU/edit#heading=h.3ye4v71wsz94
* popstate is always sent before hashchange:
* https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event#when_popstate_is_sent
*/
private emitEvents(oldHash: string, oldUrl: string) {
this.popStateSubject.next({
type: 'popstate',
state: this.getState(),
oldUrl,
newUrl: this.url,
} as LocationChangeEvent);
if (oldHash !== this.hash) {
this.hashUpdate.next({
type: 'hashchange',
state: null,
oldUrl,
newUrl: this.url,
} as LocationChangeEvent);
}
}
}
/**
* Mock implementation of URL state.
*/
@Injectable()
export class FakeNavigationPlatformLocation implements PlatformLocation {
private _platformNavigation = inject(PlatformNavigation) as FakeNavigation;
private window = inject(DOCUMENT).defaultView!;
constructor() {
if (!(this._platformNavigation instanceof FakeNavigation)) {
throw new Error(
'FakePlatformNavigation cannot be used without FakeNavigation. Use ' +
'`provideFakeNavigation` to have all these services provided together.',
);
}
}
private config = inject(MOCK_PLATFORM_LOCATION_CONFIG, {optional: true});
getBaseHrefFromDOM(): string {
return this.config?.appBaseHref ?? '';
}
onPopState(fn: LocationChangeListener): VoidFunction {
this.window.addEventListener('popstate', fn);
return () => this.window.removeEventListener('popstate', fn);
}
onHashChange(fn: LocationChangeListener): VoidFunction {
this.window.addEventListener('hashchange', fn as any);
return () => this.window.removeEventListener('hashchange', fn as any);
}
get href(): string {
return this._platformNavigation.currentEntry.url!;
}
get protocol(): string {
return new URL(this._platformNavigation.currentEntry.url!).protocol;
}
get hostname(): string {
return new URL(this._platformNavigation.currentEntry.url!).hostname;
}
get port(): string {
return new URL(this._platformNavigation.currentEntry.url!).port;
}
get pathname(): string {
return new URL(this._platformNavigation.currentEntry.url!).pathname;
}
get search(): string {
return new URL(this._platformNavigation.currentEntry.url!).search;
}
get hash(): string {
return new URL(this._platformNavigation.currentEntry.url!).hash;
}
pushState(state: any, title: string, url: string): void {
this._platformNavigation.pushState(state, title, url);
}
replaceState(state: any, title: string, url: string): void {
this._platformNavigation.replaceState(state, title, url);
}
forward(): void {
this._platformNavigation.forward();
}
back(): void {
this._platformNavigation.back();
}
historyGo(relativePosition: number = 0): void {
this._platformNavigation.go(relativePosition);
}
getState(): unknown {
return this._platformNavigation.currentEntry.getHistoryState();
}
}
| {
"end_byte": 10232,
"start_byte": 2914,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/src/mock_platform_location.ts"
} |
angular/packages/common/testing/src/private_export.ts_0_332 | /**
* @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
*/
export {provideFakePlatformNavigation as ɵprovideFakePlatformNavigation} from './navigation/provide_fake_platform_navigation';
| {
"end_byte": 332,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/src/private_export.ts"
} |
angular/packages/common/testing/src/provide_location_mocks.ts_0_769 | /**
* @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 {Location, LocationStrategy} from '@angular/common';
import {Provider} from '@angular/core';
import {SpyLocation} from './location_mock';
import {MockLocationStrategy} from './mock_location_strategy';
/**
* Returns mock providers for the `Location` and `LocationStrategy` classes.
* The mocks are helpful in tests to fire simulated location events.
*
* @publicApi
*/
export function provideLocationMocks(): Provider[] {
return [
{provide: Location, useClass: SpyLocation},
{provide: LocationStrategy, useClass: MockLocationStrategy},
];
}
| {
"end_byte": 769,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/src/provide_location_mocks.ts"
} |
angular/packages/common/testing/src/mock_location_strategy.ts_0_2855 | /**
* @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 {LocationStrategy} from '@angular/common';
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs';
/**
* A mock implementation of {@link LocationStrategy} that allows tests to fire simulated
* location events.
*
* @publicApi
*/
@Injectable()
export class MockLocationStrategy extends LocationStrategy {
internalBaseHref: string = '/';
internalPath: string = '/';
internalTitle: string = '';
urlChanges: string[] = [];
/** @internal */
_subject = new Subject<_MockPopStateEvent>();
private stateChanges: any[] = [];
constructor() {
super();
}
simulatePopState(url: string): void {
this.internalPath = url;
this._subject.next(new _MockPopStateEvent(this.path()));
}
override path(includeHash: boolean = false): string {
return this.internalPath;
}
override prepareExternalUrl(internal: string): string {
if (internal.startsWith('/') && this.internalBaseHref.endsWith('/')) {
return this.internalBaseHref + internal.substring(1);
}
return this.internalBaseHref + internal;
}
override pushState(ctx: any, title: string, path: string, query: string): void {
// Add state change to changes array
this.stateChanges.push(ctx);
this.internalTitle = title;
const url = path + (query.length > 0 ? '?' + query : '');
this.internalPath = url;
const externalUrl = this.prepareExternalUrl(url);
this.urlChanges.push(externalUrl);
}
override replaceState(ctx: any, title: string, path: string, query: string): void {
// Reset the last index of stateChanges to the ctx (state) object
this.stateChanges[(this.stateChanges.length || 1) - 1] = ctx;
this.internalTitle = title;
const url = path + (query.length > 0 ? '?' + query : '');
this.internalPath = url;
const externalUrl = this.prepareExternalUrl(url);
this.urlChanges.push('replace: ' + externalUrl);
}
override onPopState(fn: (value: any) => void): void {
this._subject.subscribe({next: fn});
}
override getBaseHref(): string {
return this.internalBaseHref;
}
override back(): void {
if (this.urlChanges.length > 0) {
this.urlChanges.pop();
this.stateChanges.pop();
const nextUrl = this.urlChanges.length > 0 ? this.urlChanges[this.urlChanges.length - 1] : '';
this.simulatePopState(nextUrl);
}
}
override forward(): void {
throw 'not implemented';
}
override getState(): unknown {
return this.stateChanges[(this.stateChanges.length || 1) - 1];
}
}
class _MockPopStateEvent {
pop: boolean = true;
type: string = 'popstate';
constructor(public newUrl: string) {}
}
| {
"end_byte": 2855,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/src/mock_location_strategy.ts"
} |
angular/packages/common/testing/src/navigation/fake_navigation.ts_0_772 | /**
* @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 {
NavigateEvent,
Navigation,
NavigationCurrentEntryChangeEvent,
NavigationDestination,
NavigationHistoryEntry,
NavigationInterceptOptions,
NavigationNavigateOptions,
NavigationOptions,
NavigationReloadOptions,
NavigationResult,
NavigationTransition,
NavigationTypeString,
NavigationUpdateCurrentEntryOptions,
} from './navigation_types';
/**
* Fake implementation of user agent history and navigation behavior. This is a
* high-fidelity implementation of browser behavior that attempts to emulate
* things like traversal delay.
*/ | {
"end_byte": 772,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/src/navigation/fake_navigation.ts"
} |
angular/packages/common/testing/src/navigation/fake_navigation.ts_773_9185 | export class FakeNavigation implements Navigation {
/**
* The fake implementation of an entries array. Only same-document entries
* allowed.
*/
private readonly entriesArr: FakeNavigationHistoryEntry[] = [];
/**
* The current active entry index into `entriesArr`.
*/
private currentEntryIndex = 0;
/**
* The current navigate event.
*/
private navigateEvent: InternalFakeNavigateEvent | undefined = undefined;
/**
* A Map of pending traversals, so that traversals to the same entry can be
* re-used.
*/
private readonly traversalQueue = new Map<string, InternalNavigationResult>();
/**
* A Promise that resolves when the previous traversals have finished. Used to
* simulate the cross-process communication necessary for traversals.
*/
private nextTraversal = Promise.resolve();
/**
* A prospective current active entry index, which includes unresolved
* traversals. Used by `go` to determine where navigations are intended to go.
*/
private prospectiveEntryIndex = 0;
/**
* A test-only option to make traversals synchronous, rather than emulate
* cross-process communication.
*/
private synchronousTraversals = false;
/** Whether to allow a call to setInitialEntryForTesting. */
private canSetInitialEntry = true;
/** `EventTarget` to dispatch events. */
private eventTarget: EventTarget;
/** The next unique id for created entries. Replace recreates this id. */
private nextId = 0;
/** The next unique key for created entries. Replace inherits this id. */
private nextKey = 0;
/** Whether this fake is disposed. */
private disposed = false;
/** Equivalent to `navigation.currentEntry`. */
get currentEntry(): FakeNavigationHistoryEntry {
return this.entriesArr[this.currentEntryIndex];
}
get canGoBack(): boolean {
return this.currentEntryIndex > 0;
}
get canGoForward(): boolean {
return this.currentEntryIndex < this.entriesArr.length - 1;
}
constructor(
private readonly window: Window,
startURL: `http${string}`,
) {
this.eventTarget = this.window.document.createElement('div');
// First entry.
this.setInitialEntryForTesting(startURL);
}
/**
* Sets the initial entry.
*/
private setInitialEntryForTesting(
url: `http${string}`,
options: {historyState: unknown; state?: unknown} = {historyState: null},
) {
if (!this.canSetInitialEntry) {
throw new Error(
'setInitialEntryForTesting can only be called before any ' + 'navigation has occurred',
);
}
const currentInitialEntry = this.entriesArr[0];
this.entriesArr[0] = new FakeNavigationHistoryEntry(new URL(url).toString(), {
index: 0,
key: currentInitialEntry?.key ?? String(this.nextKey++),
id: currentInitialEntry?.id ?? String(this.nextId++),
sameDocument: true,
historyState: options?.historyState,
state: options.state,
});
}
/** Returns whether the initial entry is still eligible to be set. */
canSetInitialEntryForTesting(): boolean {
return this.canSetInitialEntry;
}
/**
* Sets whether to emulate traversals as synchronous rather than
* asynchronous.
*/
setSynchronousTraversalsForTesting(synchronousTraversals: boolean) {
this.synchronousTraversals = synchronousTraversals;
}
/** Equivalent to `navigation.entries()`. */
entries(): FakeNavigationHistoryEntry[] {
return this.entriesArr.slice();
}
/** Equivalent to `navigation.navigate()`. */
navigate(url: string, options?: NavigationNavigateOptions): FakeNavigationResult {
const fromUrl = new URL(this.currentEntry.url!);
const toUrl = new URL(url, this.currentEntry.url!);
let navigationType: NavigationTypeString;
if (!options?.history || options.history === 'auto') {
// Auto defaults to push, but if the URLs are the same, is a replace.
if (fromUrl.toString() === toUrl.toString()) {
navigationType = 'replace';
} else {
navigationType = 'push';
}
} else {
navigationType = options.history;
}
const hashChange = isHashChange(fromUrl, toUrl);
const destination = new FakeNavigationDestination({
url: toUrl.toString(),
state: options?.state,
sameDocument: hashChange,
historyState: null,
});
const result = new InternalNavigationResult();
this.userAgentNavigate(destination, result, {
navigationType,
cancelable: true,
canIntercept: true,
// Always false for navigate().
userInitiated: false,
hashChange,
info: options?.info,
});
return {
committed: result.committed,
finished: result.finished,
};
}
/** Equivalent to `history.pushState()`. */
pushState(data: unknown, title: string, url?: string): void {
this.pushOrReplaceState('push', data, title, url);
}
/** Equivalent to `history.replaceState()`. */
replaceState(data: unknown, title: string, url?: string): void {
this.pushOrReplaceState('replace', data, title, url);
}
private pushOrReplaceState(
navigationType: NavigationTypeString,
data: unknown,
_title: string,
url?: string,
): void {
const fromUrl = new URL(this.currentEntry.url!);
const toUrl = url ? new URL(url, this.currentEntry.url!) : fromUrl;
const hashChange = isHashChange(fromUrl, toUrl);
const destination = new FakeNavigationDestination({
url: toUrl.toString(),
sameDocument: true,
historyState: data,
});
const result = new InternalNavigationResult();
this.userAgentNavigate(destination, result, {
navigationType,
cancelable: true,
canIntercept: true,
// Always false for pushState() or replaceState().
userInitiated: false,
hashChange,
skipPopState: true,
});
}
/** Equivalent to `navigation.traverseTo()`. */
traverseTo(key: string, options?: NavigationOptions): FakeNavigationResult {
const fromUrl = new URL(this.currentEntry.url!);
const entry = this.findEntry(key);
if (!entry) {
const domException = new DOMException('Invalid key', 'InvalidStateError');
const committed = Promise.reject(domException);
const finished = Promise.reject(domException);
committed.catch(() => {});
finished.catch(() => {});
return {
committed,
finished,
};
}
if (entry === this.currentEntry) {
return {
committed: Promise.resolve(this.currentEntry),
finished: Promise.resolve(this.currentEntry),
};
}
if (this.traversalQueue.has(entry.key)) {
const existingResult = this.traversalQueue.get(entry.key)!;
return {
committed: existingResult.committed,
finished: existingResult.finished,
};
}
const hashChange = isHashChange(fromUrl, new URL(entry.url!, this.currentEntry.url!));
const destination = new FakeNavigationDestination({
url: entry.url!,
state: entry.getState(),
historyState: entry.getHistoryState(),
key: entry.key,
id: entry.id,
index: entry.index,
sameDocument: entry.sameDocument,
});
this.prospectiveEntryIndex = entry.index;
const result = new InternalNavigationResult();
this.traversalQueue.set(entry.key, result);
this.runTraversal(() => {
this.traversalQueue.delete(entry.key);
this.userAgentNavigate(destination, result, {
navigationType: 'traverse',
cancelable: true,
canIntercept: true,
// Always false for traverseTo().
userInitiated: false,
hashChange,
info: options?.info,
});
});
return {
committed: result.committed,
finished: result.finished,
};
}
/** Equivalent to `navigation.back()`. */
back(options?: NavigationOptions): FakeNavigationResult {
if (this.currentEntryIndex === 0) {
const domException = new DOMException('Cannot go back', 'InvalidStateError');
const committed = Promise.reject(domException);
const finished = Promise.reject(domException);
committed.catch(() => {});
finished.catch(() => {});
return {
committed,
finished,
};
}
const entry = this.entriesArr[this.currentEntryIndex - 1];
return this.traverseTo(entry.key, options);
}
/** Equivalent to `navigation.forward()`. */ | {
"end_byte": 9185,
"start_byte": 773,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/src/navigation/fake_navigation.ts"
} |
angular/packages/common/testing/src/navigation/fake_navigation.ts_9188_18235 | forward(options?: NavigationOptions): FakeNavigationResult {
if (this.currentEntryIndex === this.entriesArr.length - 1) {
const domException = new DOMException('Cannot go forward', 'InvalidStateError');
const committed = Promise.reject(domException);
const finished = Promise.reject(domException);
committed.catch(() => {});
finished.catch(() => {});
return {
committed,
finished,
};
}
const entry = this.entriesArr[this.currentEntryIndex + 1];
return this.traverseTo(entry.key, options);
}
/**
* Equivalent to `history.go()`.
* Note that this method does not actually work precisely to how Chrome
* does, instead choosing a simpler model with less unexpected behavior.
* Chrome has a few edge case optimizations, for instance with repeated
* `back(); forward()` chains it collapses certain traversals.
*/
go(direction: number): void {
const targetIndex = this.prospectiveEntryIndex + direction;
if (targetIndex >= this.entriesArr.length || targetIndex < 0) {
return;
}
this.prospectiveEntryIndex = targetIndex;
this.runTraversal(() => {
// Check again that destination is in the entries array.
if (targetIndex >= this.entriesArr.length || targetIndex < 0) {
return;
}
const fromUrl = new URL(this.currentEntry.url!);
const entry = this.entriesArr[targetIndex];
const hashChange = isHashChange(fromUrl, new URL(entry.url!, this.currentEntry.url!));
const destination = new FakeNavigationDestination({
url: entry.url!,
state: entry.getState(),
historyState: entry.getHistoryState(),
key: entry.key,
id: entry.id,
index: entry.index,
sameDocument: entry.sameDocument,
});
const result = new InternalNavigationResult();
this.userAgentNavigate(destination, result, {
navigationType: 'traverse',
cancelable: true,
canIntercept: true,
// Always false for go().
userInitiated: false,
hashChange,
});
});
}
/** Runs a traversal synchronously or asynchronously */
private runTraversal(traversal: () => void) {
if (this.synchronousTraversals) {
traversal();
return;
}
// Each traversal occupies a single timeout resolution.
// This means that Promises added to commit and finish should resolve
// before the next traversal.
this.nextTraversal = this.nextTraversal.then(() => {
return new Promise<void>((resolve) => {
setTimeout(() => {
resolve();
traversal();
});
});
});
}
/** Equivalent to `navigation.addEventListener()`. */
addEventListener(
type: string,
callback: EventListenerOrEventListenerObject,
options?: AddEventListenerOptions | boolean,
) {
this.eventTarget.addEventListener(type, callback, options);
}
/** Equivalent to `navigation.removeEventListener()`. */
removeEventListener(
type: string,
callback: EventListenerOrEventListenerObject,
options?: EventListenerOptions | boolean,
) {
this.eventTarget.removeEventListener(type, callback, options);
}
/** Equivalent to `navigation.dispatchEvent()` */
dispatchEvent(event: Event): boolean {
return this.eventTarget.dispatchEvent(event);
}
/** Cleans up resources. */
dispose() {
// Recreate eventTarget to release current listeners.
// `document.createElement` because NodeJS `EventTarget` is incompatible with Domino's `Event`.
this.eventTarget = this.window.document.createElement('div');
this.disposed = true;
}
/** Returns whether this fake is disposed. */
isDisposed() {
return this.disposed;
}
/** Implementation for all navigations and traversals. */
private userAgentNavigate(
destination: FakeNavigationDestination,
result: InternalNavigationResult,
options: InternalNavigateOptions,
) {
// The first navigation should disallow any future calls to set the initial
// entry.
this.canSetInitialEntry = false;
if (this.navigateEvent) {
this.navigateEvent.cancel(new DOMException('Navigation was aborted', 'AbortError'));
this.navigateEvent = undefined;
}
const navigateEvent = createFakeNavigateEvent({
navigationType: options.navigationType,
cancelable: options.cancelable,
canIntercept: options.canIntercept,
userInitiated: options.userInitiated,
hashChange: options.hashChange,
signal: result.signal,
destination,
info: options.info,
sameDocument: destination.sameDocument,
skipPopState: options.skipPopState,
result,
userAgentCommit: () => {
this.userAgentCommit();
},
});
this.navigateEvent = navigateEvent;
this.eventTarget.dispatchEvent(navigateEvent);
navigateEvent.dispatchedNavigateEvent();
if (navigateEvent.commitOption === 'immediate') {
navigateEvent.commit(/* internal= */ true);
}
}
/** Implementation to commit a navigation. */
private userAgentCommit() {
if (!this.navigateEvent) {
return;
}
const from = this.currentEntry;
if (!this.navigateEvent.sameDocument) {
const error = new Error('Cannot navigate to a non-same-document URL.');
this.navigateEvent.cancel(error);
throw error;
}
if (
this.navigateEvent.navigationType === 'push' ||
this.navigateEvent.navigationType === 'replace'
) {
this.userAgentPushOrReplace(this.navigateEvent.destination, {
navigationType: this.navigateEvent.navigationType,
});
} else if (this.navigateEvent.navigationType === 'traverse') {
this.userAgentTraverse(this.navigateEvent.destination);
}
this.navigateEvent.userAgentNavigated(this.currentEntry);
const currentEntryChangeEvent = createFakeNavigationCurrentEntryChangeEvent({
from,
navigationType: this.navigateEvent.navigationType,
});
this.eventTarget.dispatchEvent(currentEntryChangeEvent);
if (!this.navigateEvent.skipPopState) {
const popStateEvent = createPopStateEvent({
state: this.navigateEvent.destination.getHistoryState(),
});
this.window.dispatchEvent(popStateEvent);
}
}
/** Implementation for a push or replace navigation. */
private userAgentPushOrReplace(
destination: FakeNavigationDestination,
{navigationType}: {navigationType: NavigationTypeString},
) {
if (navigationType === 'push') {
this.currentEntryIndex++;
this.prospectiveEntryIndex = this.currentEntryIndex;
}
const index = this.currentEntryIndex;
const key = navigationType === 'push' ? String(this.nextKey++) : this.currentEntry.key;
const entry = new FakeNavigationHistoryEntry(destination.url, {
id: String(this.nextId++),
key,
index,
sameDocument: true,
state: destination.getState(),
historyState: destination.getHistoryState(),
});
if (navigationType === 'push') {
this.entriesArr.splice(index, Infinity, entry);
} else {
this.entriesArr[index] = entry;
}
}
/** Implementation for a traverse navigation. */
private userAgentTraverse(destination: FakeNavigationDestination) {
this.currentEntryIndex = destination.index;
}
/** Utility method for finding entries with the given `key`. */
private findEntry(key: string) {
for (const entry of this.entriesArr) {
if (entry.key === key) return entry;
}
return undefined;
}
set onnavigate(_handler: ((this: Navigation, ev: NavigateEvent) => any) | null) {
throw new Error('unimplemented');
}
get onnavigate(): ((this: Navigation, ev: NavigateEvent) => any) | null {
throw new Error('unimplemented');
}
set oncurrententrychange(
_handler: ((this: Navigation, ev: NavigationCurrentEntryChangeEvent) => any) | null,
) {
throw new Error('unimplemented');
}
get oncurrententrychange():
| ((this: Navigation, ev: NavigationCurrentEntryChangeEvent) => any)
| null {
throw new Error('unimplemented');
}
set onnavigatesuccess(_handler: ((this: Navigation, ev: Event) => any) | null) {
throw new Error('unimplemented');
}
get onnavigatesuccess(): ((this: Navigation, ev: Event) => any) | null {
throw new Error('unimplemented');
}
set onnavigateerror(_handler: ((this: Navigation, ev: ErrorEvent) => any) | null) {
throw new Error('unimplemented');
}
get onnavigateerror(): ((this: Navigation, ev: ErrorEvent) => any) | null {
throw new Error('unimplemented');
}
get transition(): NavigationTransition | null {
throw new Error('unimplemented');
}
updateCurrentEntry(_options: NavigationUpdateCurrentEntryOptions): void {
throw new Error('unimplemented');
}
reload(_options?: NavigationReloadOptions): NavigationResult {
throw new Error('unimplemented');
}
}
/**
* Fake equivalent of the `NavigationResult` interface with
* `FakeNavigationHistoryEntry`.
*/ | {
"end_byte": 18235,
"start_byte": 9188,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/src/navigation/fake_navigation.ts"
} |
angular/packages/common/testing/src/navigation/fake_navigation.ts_18236_27139 | interface FakeNavigationResult extends NavigationResult {
readonly committed: Promise<FakeNavigationHistoryEntry>;
readonly finished: Promise<FakeNavigationHistoryEntry>;
}
/**
* Fake equivalent of `NavigationHistoryEntry`.
*/
export class FakeNavigationHistoryEntry implements NavigationHistoryEntry {
readonly sameDocument;
readonly id: string;
readonly key: string;
readonly index: number;
private readonly state: unknown;
private readonly historyState: unknown;
// tslint:disable-next-line:no-any
ondispose: ((this: NavigationHistoryEntry, ev: Event) => any) | null = null;
constructor(
readonly url: string | null,
{
id,
key,
index,
sameDocument,
state,
historyState,
}: {
id: string;
key: string;
index: number;
sameDocument: boolean;
historyState: unknown;
state?: unknown;
},
) {
this.id = id;
this.key = key;
this.index = index;
this.sameDocument = sameDocument;
this.state = state;
this.historyState = historyState;
}
getState(): unknown {
// Budget copy.
return this.state ? JSON.parse(JSON.stringify(this.state)) : this.state;
}
getHistoryState(): unknown {
// Budget copy.
return this.historyState ? JSON.parse(JSON.stringify(this.historyState)) : this.historyState;
}
addEventListener(
type: string,
callback: EventListenerOrEventListenerObject,
options?: AddEventListenerOptions | boolean,
) {
throw new Error('unimplemented');
}
removeEventListener(
type: string,
callback: EventListenerOrEventListenerObject,
options?: EventListenerOptions | boolean,
) {
throw new Error('unimplemented');
}
dispatchEvent(event: Event): boolean {
throw new Error('unimplemented');
}
}
/** `NavigationInterceptOptions` with experimental commit option. */
export interface ExperimentalNavigationInterceptOptions extends NavigationInterceptOptions {
commit?: 'immediate' | 'after-transition';
}
/** `NavigateEvent` with experimental commit function. */
export interface ExperimentalNavigateEvent extends NavigateEvent {
intercept(options?: ExperimentalNavigationInterceptOptions): void;
commit(): void;
}
/**
* Fake equivalent of `NavigateEvent`.
*/
export interface FakeNavigateEvent extends ExperimentalNavigateEvent {
readonly destination: FakeNavigationDestination;
}
interface InternalFakeNavigateEvent extends FakeNavigateEvent {
readonly sameDocument: boolean;
readonly skipPopState?: boolean;
readonly commitOption: 'after-transition' | 'immediate';
readonly result: InternalNavigationResult;
commit(internal?: boolean): void;
cancel(reason: Error): void;
dispatchedNavigateEvent(): void;
userAgentNavigated(entry: FakeNavigationHistoryEntry): void;
}
/**
* Create a fake equivalent of `NavigateEvent`. This is not a class because ES5
* transpiled JavaScript cannot extend native Event.
*/
function createFakeNavigateEvent({
cancelable,
canIntercept,
userInitiated,
hashChange,
navigationType,
signal,
destination,
info,
sameDocument,
skipPopState,
result,
userAgentCommit,
}: {
cancelable: boolean;
canIntercept: boolean;
userInitiated: boolean;
hashChange: boolean;
navigationType: NavigationTypeString;
signal: AbortSignal;
destination: FakeNavigationDestination;
info: unknown;
sameDocument: boolean;
skipPopState?: boolean;
result: InternalNavigationResult;
userAgentCommit: () => void;
}) {
const event = new Event('navigate', {bubbles: false, cancelable}) as {
-readonly [P in keyof InternalFakeNavigateEvent]: InternalFakeNavigateEvent[P];
};
event.canIntercept = canIntercept;
event.userInitiated = userInitiated;
event.hashChange = hashChange;
event.navigationType = navigationType;
event.signal = signal;
event.destination = destination;
event.info = info;
event.downloadRequest = null;
event.formData = null;
event.sameDocument = sameDocument;
event.skipPopState = skipPopState;
event.commitOption = 'immediate';
let handlerFinished: Promise<void> | undefined = undefined;
let interceptCalled = false;
let dispatchedNavigateEvent = false;
let commitCalled = false;
event.intercept = function (
this: InternalFakeNavigateEvent,
options?: ExperimentalNavigationInterceptOptions,
): void {
interceptCalled = true;
event.sameDocument = true;
const handler = options?.handler;
if (handler) {
handlerFinished = handler();
}
if (options?.commit) {
event.commitOption = options.commit;
}
if (options?.focusReset !== undefined || options?.scroll !== undefined) {
throw new Error('unimplemented');
}
};
event.scroll = function (this: InternalFakeNavigateEvent): void {
throw new Error('unimplemented');
};
event.commit = function (this: InternalFakeNavigateEvent, internal = false) {
if (!internal && !interceptCalled) {
throw new DOMException(
`Failed to execute 'commit' on 'NavigateEvent': intercept() must be ` +
`called before commit().`,
'InvalidStateError',
);
}
if (!dispatchedNavigateEvent) {
throw new DOMException(
`Failed to execute 'commit' on 'NavigateEvent': commit() may not be ` +
`called during event dispatch.`,
'InvalidStateError',
);
}
if (commitCalled) {
throw new DOMException(
`Failed to execute 'commit' on 'NavigateEvent': commit() already ` + `called.`,
'InvalidStateError',
);
}
commitCalled = true;
userAgentCommit();
};
// Internal only.
event.cancel = function (this: InternalFakeNavigateEvent, reason: Error) {
result.committedReject(reason);
result.finishedReject(reason);
};
// Internal only.
event.dispatchedNavigateEvent = function (this: InternalFakeNavigateEvent) {
dispatchedNavigateEvent = true;
if (event.commitOption === 'after-transition') {
// If handler finishes before commit, call commit.
handlerFinished?.then(
() => {
if (!commitCalled) {
event.commit(/* internal */ true);
}
},
() => {},
);
}
Promise.all([result.committed, handlerFinished]).then(
([entry]) => {
result.finishedResolve(entry);
},
(reason) => {
result.finishedReject(reason);
},
);
};
// Internal only.
event.userAgentNavigated = function (
this: InternalFakeNavigateEvent,
entry: FakeNavigationHistoryEntry,
) {
result.committedResolve(entry);
};
return event as InternalFakeNavigateEvent;
}
/** Fake equivalent of `NavigationCurrentEntryChangeEvent`. */
export interface FakeNavigationCurrentEntryChangeEvent extends NavigationCurrentEntryChangeEvent {
readonly from: FakeNavigationHistoryEntry;
}
/**
* Create a fake equivalent of `NavigationCurrentEntryChange`. This does not use
* a class because ES5 transpiled JavaScript cannot extend native Event.
*/
function createFakeNavigationCurrentEntryChangeEvent({
from,
navigationType,
}: {
from: FakeNavigationHistoryEntry;
navigationType: NavigationTypeString;
}) {
const event = new Event('currententrychange', {
bubbles: false,
cancelable: false,
}) as {
-readonly [P in keyof NavigationCurrentEntryChangeEvent]: NavigationCurrentEntryChangeEvent[P];
};
event.from = from;
event.navigationType = navigationType;
return event as FakeNavigationCurrentEntryChangeEvent;
}
/**
* Create a fake equivalent of `PopStateEvent`. This does not use a class
* because ES5 transpiled JavaScript cannot extend native Event.
*/
function createPopStateEvent({state}: {state: unknown}) {
const event = new Event('popstate', {
bubbles: false,
cancelable: false,
}) as {-readonly [P in keyof PopStateEvent]: PopStateEvent[P]};
event.state = state;
return event as PopStateEvent;
}
/**
* Fake equivalent of `NavigationDestination`.
*/
export class FakeNavigationDestination implements NavigationDestination {
readonly url: string;
readonly sameDocument: boolean;
readonly key: string | null;
readonly id: string | null;
readonly index: number;
private readonly state?: unknown;
private readonly historyState: unknown;
constructor({
url,
sameDocument,
historyState,
state,
key = null,
id = null,
index = -1,
}: {
url: string;
sameDocument: boolean;
historyState: unknown;
state?: unknown;
key?: string | null;
id?: string | null;
index?: number;
}) {
this.url = url;
this.sameDocument = sameDocument;
this.state = state;
this.historyState = historyState;
this.key = key;
this.id = id;
this.index = index;
}
getState(): unknown {
return this.state;
}
getHistoryState(): unknown {
return this.historyState;
}
} | {
"end_byte": 27139,
"start_byte": 18236,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/src/navigation/fake_navigation.ts"
} |
angular/packages/common/testing/src/navigation/fake_navigation.ts_27141_28834 | /** Utility function to determine whether two UrlLike have the same hash. */
function isHashChange(from: URL, to: URL): boolean {
return (
to.hash !== from.hash &&
to.hostname === from.hostname &&
to.pathname === from.pathname &&
to.search === from.search
);
}
/** Internal utility class for representing the result of a navigation. */
class InternalNavigationResult {
committedResolve!: (entry: FakeNavigationHistoryEntry) => void;
committedReject!: (reason: Error) => void;
finishedResolve!: (entry: FakeNavigationHistoryEntry) => void;
finishedReject!: (reason: Error) => void;
readonly committed: Promise<FakeNavigationHistoryEntry>;
readonly finished: Promise<FakeNavigationHistoryEntry>;
get signal(): AbortSignal {
return this.abortController.signal;
}
private readonly abortController = new AbortController();
constructor() {
this.committed = new Promise<FakeNavigationHistoryEntry>((resolve, reject) => {
this.committedResolve = resolve;
this.committedReject = reject;
});
this.finished = new Promise<FakeNavigationHistoryEntry>(async (resolve, reject) => {
this.finishedResolve = resolve;
this.finishedReject = (reason: Error) => {
reject(reason);
this.abortController.abort(reason);
};
});
// All rejections are handled.
this.committed.catch(() => {});
this.finished.catch(() => {});
}
}
/** Internal options for performing a navigate. */
interface InternalNavigateOptions {
navigationType: NavigationTypeString;
cancelable: boolean;
canIntercept: boolean;
userInitiated: boolean;
hashChange: boolean;
info?: unknown;
skipPopState?: boolean;
} | {
"end_byte": 28834,
"start_byte": 27141,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/src/navigation/fake_navigation.ts"
} |
angular/packages/common/testing/src/navigation/navigation_types.ts_0_5583 | /**
* @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
*/
export interface NavigationEventMap {
navigate: NavigateEvent;
navigatesuccess: Event;
navigateerror: ErrorEvent;
currententrychange: NavigationCurrentEntryChangeEvent;
}
export interface NavigationResult {
committed: Promise<NavigationHistoryEntry>;
finished: Promise<NavigationHistoryEntry>;
}
export declare class Navigation extends EventTarget {
entries(): NavigationHistoryEntry[];
readonly currentEntry: NavigationHistoryEntry | null;
updateCurrentEntry(options: NavigationUpdateCurrentEntryOptions): void;
readonly transition: NavigationTransition | null;
readonly canGoBack: boolean;
readonly canGoForward: boolean;
navigate(url: string, options?: NavigationNavigateOptions): NavigationResult;
reload(options?: NavigationReloadOptions): NavigationResult;
traverseTo(key: string, options?: NavigationOptions): NavigationResult;
back(options?: NavigationOptions): NavigationResult;
forward(options?: NavigationOptions): NavigationResult;
onnavigate: ((this: Navigation, ev: NavigateEvent) => any) | null;
onnavigatesuccess: ((this: Navigation, ev: Event) => any) | null;
onnavigateerror: ((this: Navigation, ev: ErrorEvent) => any) | null;
oncurrententrychange: ((this: Navigation, ev: NavigationCurrentEntryChangeEvent) => any) | null;
addEventListener<K extends keyof NavigationEventMap>(
type: K,
listener: (this: Navigation, ev: NavigationEventMap[K]) => any,
options?: boolean | AddEventListenerOptions,
): void;
addEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | AddEventListenerOptions,
): void;
removeEventListener<K extends keyof NavigationEventMap>(
type: K,
listener: (this: Navigation, ev: NavigationEventMap[K]) => any,
options?: boolean | EventListenerOptions,
): void;
removeEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | EventListenerOptions,
): void;
}
export declare class NavigationTransition {
readonly navigationType: NavigationTypeString;
readonly from: NavigationHistoryEntry;
readonly finished: Promise<void>;
}
export interface NavigationHistoryEntryEventMap {
dispose: Event;
}
export declare class NavigationHistoryEntry extends EventTarget {
readonly key: string;
readonly id: string;
readonly url: string | null;
readonly index: number;
readonly sameDocument: boolean;
getState(): unknown;
ondispose: ((this: NavigationHistoryEntry, ev: Event) => any) | null;
addEventListener<K extends keyof NavigationHistoryEntryEventMap>(
type: K,
listener: (this: NavigationHistoryEntry, ev: NavigationHistoryEntryEventMap[K]) => any,
options?: boolean | AddEventListenerOptions,
): void;
addEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | AddEventListenerOptions,
): void;
removeEventListener<K extends keyof NavigationHistoryEntryEventMap>(
type: K,
listener: (this: NavigationHistoryEntry, ev: NavigationHistoryEntryEventMap[K]) => any,
options?: boolean | EventListenerOptions,
): void;
removeEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | EventListenerOptions,
): void;
}
export type NavigationTypeString = 'reload' | 'push' | 'replace' | 'traverse';
export interface NavigationUpdateCurrentEntryOptions {
state: unknown;
}
export interface NavigationOptions {
info?: unknown;
}
export interface NavigationNavigateOptions extends NavigationOptions {
state?: unknown;
history?: 'auto' | 'push' | 'replace';
}
export interface NavigationReloadOptions extends NavigationOptions {
state?: unknown;
}
export declare class NavigationCurrentEntryChangeEvent extends Event {
constructor(type: string, eventInit?: NavigationCurrentEntryChangeEventInit);
readonly navigationType: NavigationTypeString | null;
readonly from: NavigationHistoryEntry;
}
export interface NavigationCurrentEntryChangeEventInit extends EventInit {
navigationType?: NavigationTypeString | null;
from: NavigationHistoryEntry;
}
export declare class NavigateEvent extends Event {
constructor(type: string, eventInit?: NavigateEventInit);
readonly navigationType: NavigationTypeString;
readonly canIntercept: boolean;
readonly userInitiated: boolean;
readonly hashChange: boolean;
readonly destination: NavigationDestination;
readonly signal: AbortSignal;
readonly formData: FormData | null;
readonly downloadRequest: string | null;
readonly info?: unknown;
intercept(options?: NavigationInterceptOptions): void;
scroll(): void;
}
export interface NavigateEventInit extends EventInit {
navigationType?: NavigationTypeString;
canIntercept?: boolean;
userInitiated?: boolean;
hashChange?: boolean;
destination: NavigationDestination;
signal: AbortSignal;
formData?: FormData | null;
downloadRequest?: string | null;
info?: unknown;
}
export interface NavigationInterceptOptions {
handler?: () => Promise<void>;
focusReset?: 'after-transition' | 'manual';
scroll?: 'after-transition' | 'manual';
}
export declare class NavigationDestination {
readonly url: string;
readonly key: string | null;
readonly id: string | null;
readonly index: number;
readonly sameDocument: boolean;
getState(): unknown;
}
| {
"end_byte": 5583,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/src/navigation/navigation_types.ts"
} |
angular/packages/common/testing/src/navigation/provide_fake_platform_navigation.ts_0_1164 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {DOCUMENT, PlatformLocation} from '@angular/common';
import {inject, Provider} from '@angular/core';
// @ng_package: ignore-cross-repo-import
import {PlatformNavigation} from '../../../src/navigation/platform_navigation';
import {
FakeNavigationPlatformLocation,
MOCK_PLATFORM_LOCATION_CONFIG,
} from '../mock_platform_location';
import {FakeNavigation} from './fake_navigation';
/**
* Return a provider for the `FakeNavigation` in place of the real Navigation API.
*/
export function provideFakePlatformNavigation(): Provider[] {
return [
{
provide: PlatformNavigation,
useFactory: () => {
const config = inject(MOCK_PLATFORM_LOCATION_CONFIG, {optional: true});
return new FakeNavigation(
inject(DOCUMENT).defaultView!,
(config?.startUrl as `http${string}`) ?? 'http://_empty_/',
);
},
},
{provide: PlatformLocation, useClass: FakeNavigationPlatformLocation},
];
}
| {
"end_byte": 1164,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/testing/src/navigation/provide_fake_platform_navigation.ts"
} |
angular/packages/common/http/PACKAGE.md_0_331 | Implements an HTTP client API for Angular apps that relies on the `XMLHttpRequest` interface exposed by browsers.
Includes testability features, typed request and response objects, request and response interception,
observable APIs, and streamlined error handling.
For usage information, see the [HTTP Client](guide/http) guide. | {
"end_byte": 331,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/PACKAGE.md"
} |
angular/packages/common/http/BUILD.bazel_0_1054 | load("//tools:defaults.bzl", "api_golden_test", "generate_api_docs", "ng_module")
package(default_visibility = ["//visibility:public"])
exports_files(["package.json"])
ng_module(
name = "http",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
),
deps = [
"//packages/common",
"//packages/core",
"@npm//rxjs",
],
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
api_golden_test(
name = "http_errors",
data = [
"//goldens:public-api",
"//packages/common/http",
],
entry_point = "angular/packages/common/http/src/errors.d.ts",
golden = "angular/goldens/public-api/common/http/errors.api.md",
)
generate_api_docs(
name = "http_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
"//packages/common:files_for_docgen",
],
entry_point = ":index.ts",
module_name = "@angular/common/http",
)
| {
"end_byte": 1054,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/BUILD.bazel"
} |
angular/packages/common/http/index.ts_0_481 | /**
* @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 file is not used to build this module. It is only used during editing
// by the TypeScript language service and during build for verification. `ngc`
// replaces this file with production index.ts when it rewrites private symbol
// names.
export * from './public_api';
| {
"end_byte": 481,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/index.ts"
} |
angular/packages/common/http/public_api.ts_0_1808 | /**
* @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
*/
export {HttpBackend, HttpHandler} from './src/backend';
export {HttpClient} from './src/client';
export {HttpContext, HttpContextToken} from './src/context';
export {FetchBackend} from './src/fetch';
export {HttpHeaders} from './src/headers';
export {
HTTP_INTERCEPTORS,
HttpHandlerFn,
HttpInterceptor,
HttpInterceptorFn,
HttpInterceptorHandler as ɵHttpInterceptorHandler,
HttpInterceptorHandler as ɵHttpInterceptingHandler,
} from './src/interceptor';
export {JsonpClientBackend, JsonpInterceptor} from './src/jsonp';
export {HttpClientJsonpModule, HttpClientModule, HttpClientXsrfModule} from './src/module';
export {
HttpParameterCodec,
HttpParams,
HttpParamsOptions,
HttpUrlEncodingCodec,
} from './src/params';
export {
HttpFeature,
HttpFeatureKind,
provideHttpClient,
withFetch,
withInterceptors,
withInterceptorsFromDi,
withJsonpSupport,
withNoXsrfProtection,
withRequestsMadeViaParent,
withXsrfConfiguration,
} from './src/provider';
export {HttpRequest} from './src/request';
export {
HttpDownloadProgressEvent,
HttpErrorResponse,
HttpEvent,
HttpEventType,
HttpHeaderResponse,
HttpProgressEvent,
HttpResponse,
HttpResponseBase,
HttpSentEvent,
HttpStatusCode,
HttpUploadProgressEvent,
HttpUserEvent,
} from './src/response';
export {
HttpTransferCacheOptions,
withHttpTransferCache as ɵwithHttpTransferCache,
HTTP_TRANSFER_CACHE_ORIGIN_MAP,
} from './src/transfer_cache';
export {HttpXhrBackend} from './src/xhr';
export {HttpXsrfTokenExtractor} from './src/xsrf';
// Private exports
export * from './src/private_export';
| {
"end_byte": 1808,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/public_api.ts"
} |
angular/packages/common/http/test/fetch_spec.ts_0_1285 | /**
* @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 {HttpEvent, HttpEventType, HttpRequest, HttpResponse} from '@angular/common/http';
import {TestBed} from '@angular/core/testing';
import {Observable, of, Subject} from 'rxjs';
import {catchError, retry, scan, skip, take, toArray} from 'rxjs/operators';
import {
HttpClient,
HttpDownloadProgressEvent,
HttpErrorResponse,
HttpHeaderResponse,
HttpParams,
HttpStatusCode,
provideHttpClient,
withFetch,
} from '../public_api';
import {FetchBackend, FetchFactory} from '../src/fetch';
function trackEvents(obs: Observable<any>): Promise<any[]> {
return obs
.pipe(
// We don't want the promise to fail on HttpErrorResponse
catchError((e) => of(e)),
scan((acc, event) => {
acc.push(event);
return acc;
}, [] as any[]),
)
.toPromise() as Promise<any[]>;
}
const TEST_POST = new HttpRequest('POST', '/test', 'some body', {
responseType: 'text',
});
const TEST_POST_WITH_JSON_BODY = new HttpRequest(
'POST',
'/test',
{'some': 'body'},
{
responseType: 'text',
},
);
const XSSI_PREFIX = ")]}'\n"; | {
"end_byte": 1285,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/fetch_spec.ts"
} |
angular/packages/common/http/test/fetch_spec.ts_1287_9570 | describe('FetchBackend', async () => {
let fetchMock: MockFetchFactory = null!;
let backend: FetchBackend = null!;
let fetchSpy: jasmine.Spy<typeof fetch>;
function callFetchAndFlush(req: HttpRequest<any>): void {
backend.handle(req).pipe(take(1)).subscribe();
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'some response');
}
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{provide: FetchFactory, useClass: MockFetchFactory}, FetchBackend],
});
fetchMock = TestBed.inject(FetchFactory) as MockFetchFactory;
fetchSpy = spyOn(fetchMock, 'fetch').and.callThrough();
backend = TestBed.inject(FetchBackend);
});
it('emits status immediately', () => {
let event!: HttpEvent<any>;
// subscribe is sync
backend
.handle(TEST_POST)
.pipe(take(1))
.subscribe((e) => (event = e));
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'some response');
expect(event.type).toBe(HttpEventType.Sent);
});
it('should not call fetch without a subscribe', () => {
const handle = backend.handle(TEST_POST);
expect(fetchSpy).not.toHaveBeenCalled();
handle.subscribe();
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'some response');
expect(fetchSpy).toHaveBeenCalled();
});
it('should be able to retry', (done) => {
const handle = backend.handle(TEST_POST);
// Skipping both HttpSentEvent (from the 1st subscription + retry)
handle.pipe(retry(1), skip(2)).subscribe((response) => {
expect(response.type).toBe(HttpEventType.Response);
expect((response as HttpResponse<any>).body).toBe('some response');
done();
});
fetchMock.mockErrorEvent('Error 1');
fetchMock.resetFetchPromise();
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'some response');
});
it('sets method, url, and responseType correctly', () => {
callFetchAndFlush(TEST_POST);
expect(fetchMock.request.method).toBe('POST');
expect(fetchMock.request.url).toBe('/test');
});
it('use query params from request', () => {
const requestWithQuery = new HttpRequest('GET', '/test', 'some body', {
params: new HttpParams({fromObject: {query: 'foobar'}}),
responseType: 'text',
});
callFetchAndFlush(requestWithQuery);
expect(fetchMock.request.method).toBe('GET');
expect(fetchMock.request.url).toBe('/test?query=foobar');
});
it('sets outgoing body correctly', () => {
callFetchAndFlush(TEST_POST);
expect(fetchMock.request.body).toBe('some body');
});
it('sets outgoing body correctly when request payload is json', () => {
callFetchAndFlush(TEST_POST_WITH_JSON_BODY);
expect(fetchMock.request.body).toBe('{"some":"body"}');
});
it('sets outgoing headers, including default headers', () => {
const post = TEST_POST.clone({
setHeaders: {
'Test': 'Test header',
},
});
callFetchAndFlush(post);
expect(fetchMock.request.headers).toEqual({
'Test': 'Test header',
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'text/plain',
});
});
it('sets outgoing headers, including overriding defaults', () => {
const setHeaders = {
'Test': 'Test header',
'Accept': 'text/html',
'Content-Type': 'text/css',
};
callFetchAndFlush(TEST_POST.clone({setHeaders}));
expect(fetchMock.request.headers).toEqual(setHeaders);
});
it('should be case insensitive for Content-Type & Accept', () => {
const setHeaders = {
'accept': 'text/html',
'content-type': 'text/css',
};
callFetchAndFlush(TEST_POST.clone({setHeaders}));
expect(fetchMock.request.headers).toEqual(setHeaders);
});
it('passes withCredentials through', () => {
callFetchAndFlush(TEST_POST.clone({withCredentials: true}));
expect(fetchMock.request.credentials).toBe('include');
});
it('handles a text response', async () => {
const promise = trackEvents(backend.handle(TEST_POST));
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'some response');
const events = await promise;
expect(events.length).toBe(2);
expect(events[1].type).toBe(HttpEventType.Response);
expect(events[1] instanceof HttpResponse).toBeTruthy();
const res = events[1] as HttpResponse<string>;
expect(res.body).toBe('some response');
expect(res.status).toBe(HttpStatusCode.Ok);
expect(res.statusText).toBe('OK');
});
it('handles a json response', async () => {
const promise = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'})));
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', JSON.stringify({data: 'some data'}));
const events = await promise;
expect(events.length).toBe(2);
const res = events[1] as HttpResponse<{data: string}>;
expect(res.body!.data).toBe('some data');
});
it('handles a blank json response', async () => {
const promise = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'})));
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', '');
const events = await promise;
expect(events.length).toBe(2);
const res = events[1] as HttpResponse<{data: string}>;
expect(res.body).toBeNull();
});
it('handles a json error response', async () => {
const promise = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'})));
fetchMock.mockFlush(
HttpStatusCode.InternalServerError,
'Error',
JSON.stringify({data: 'some data'}),
);
const events = await promise;
expect(events.length).toBe(2);
const res = events[1] as any as HttpErrorResponse;
expect(res.error.data).toBe('some data');
});
it('handles a json error response with XSSI prefix', async () => {
const promise = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'})));
fetchMock.mockFlush(
HttpStatusCode.InternalServerError,
'Error',
XSSI_PREFIX + JSON.stringify({data: 'some data'}),
);
const events = await promise;
expect(events.length).toBe(2);
const res = events[1] as any as HttpErrorResponse;
expect(res.error.data).toBe('some data');
});
it('handles a json string response', async () => {
const promise = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'})));
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', JSON.stringify('this is a string'));
const events = await promise;
expect(events.length).toBe(2);
const res = events[1] as HttpResponse<string>;
expect(res.body).toEqual('this is a string');
});
it('handles a json response with an XSSI prefix', async () => {
const promise = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'})));
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', XSSI_PREFIX + JSON.stringify({data: 'some data'}));
const events = await promise;
expect(events.length).toBe(2);
const res = events[1] as HttpResponse<{data: string}>;
expect(res.body!.data).toBe('some data');
});
it('handles a blob with a mime type', async () => {
const promise = trackEvents(backend.handle(TEST_POST.clone({responseType: 'blob'})));
const type = 'application/pdf';
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', new Blob(), {'Content-Type': type});
const events = await promise;
expect(events.length).toBe(2);
const res = events[1] as HttpResponse<Blob>;
expect(res.body?.type).toBe(type);
});
it('emits unsuccessful responses via the error path', (done) => {
backend.handle(TEST_POST).subscribe({
error: (err: HttpErrorResponse) => {
expect(err instanceof HttpErrorResponse).toBe(true);
expect(err.error).toBe('this is the error');
done();
},
});
fetchMock.mockFlush(HttpStatusCode.BadRequest, 'Bad Request', 'this is the error');
});
it('emits real errors via the error path', (done) => {
// Skipping the HttpEventType.Sent that is sent first
backend
.handle(TEST_POST)
.pipe(skip(1))
.subscribe({
error: (err: HttpErrorResponse) => {
expect(err instanceof HttpErrorResponse).toBe(true);
expect(err.error instanceof Error).toBeTrue();
expect(err.url).toBe('/test');
done();
},
});
fetchMock.mockErrorEvent(new Error('blah'));
}); | {
"end_byte": 9570,
"start_byte": 1287,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/fetch_spec.ts"
} |
angular/packages/common/http/test/fetch_spec.ts_9574_16054 | it('emits an error when browser cancels a request', (done) => {
backend.handle(TEST_POST).subscribe({
error: (err: HttpErrorResponse) => {
expect(err instanceof HttpErrorResponse).toBe(true);
expect(err.error instanceof DOMException).toBeTruthy();
done();
},
});
fetchMock.mockAbortEvent();
});
describe('progress events', () => {
it('are emitted for download progress', (done) => {
backend
.handle(TEST_POST.clone({reportProgress: true}))
.pipe(toArray())
.subscribe((events) => {
expect(events.map((event) => event.type)).toEqual([
HttpEventType.Sent,
HttpEventType.ResponseHeader,
HttpEventType.DownloadProgress,
HttpEventType.DownloadProgress,
HttpEventType.DownloadProgress,
HttpEventType.Response,
]);
const [progress1, progress2, response] = [
events[2] as HttpDownloadProgressEvent,
events[3] as HttpDownloadProgressEvent,
events[5] as HttpResponse<string>,
];
expect(progress1.partialText).toBe('down');
expect(progress1.loaded).toBe(4);
expect(progress1.total).toBe(10);
expect(progress2.partialText).toBe('download');
expect(progress2.loaded).toBe(8);
expect(progress2.total).toBe(10);
expect(response.body).toBe('downloaded');
done();
});
fetchMock.mockProgressEvent(4);
fetchMock.mockProgressEvent(8);
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'downloaded');
});
it('include ResponseHeader with headers and status', (done) => {
backend
.handle(TEST_POST.clone({reportProgress: true}))
.pipe(toArray())
.subscribe((events) => {
expect(events.map((event) => event.type)).toEqual([
HttpEventType.Sent,
HttpEventType.ResponseHeader,
HttpEventType.DownloadProgress,
HttpEventType.DownloadProgress,
HttpEventType.Response,
]);
const partial = events[1] as HttpHeaderResponse;
expect(partial.type).toEqual(HttpEventType.ResponseHeader);
expect(partial.headers.get('Content-Type')).toEqual('text/plain');
expect(partial.headers.get('Test')).toEqual('Test header');
done();
});
fetchMock.response.headers = {'Test': 'Test header', 'Content-Type': 'text/plain'};
fetchMock.mockProgressEvent(200);
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'Done');
});
});
describe('gets response URL', async () => {
it('from the response URL', (done) => {
backend
.handle(TEST_POST)
.pipe(toArray())
.subscribe((events) => {
expect(events.length).toBe(2);
expect(events[1].type).toBe(HttpEventType.Response);
const response = events[1] as HttpResponse<string>;
expect(response.url).toBe('/response/url');
done();
});
fetchMock.response.url = '/response/url';
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'Test');
});
it('from X-Request-URL header if the response URL is not present', (done) => {
backend
.handle(TEST_POST)
.pipe(toArray())
.subscribe((events) => {
expect(events.length).toBe(2);
expect(events[1].type).toBe(HttpEventType.Response);
const response = events[1] as HttpResponse<string>;
expect(response.url).toBe('/response/url');
done();
});
fetchMock.response.headers = {'X-Request-URL': '/response/url'};
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'Test');
});
it('falls back on Request.url if neither are available', (done) => {
backend
.handle(TEST_POST)
.pipe(toArray())
.subscribe((events) => {
expect(events.length).toBe(2);
expect(events[1].type).toBe(HttpEventType.Response);
const response = events[1] as HttpResponse<string>;
expect(response.url).toBe('/test');
done();
});
fetchMock.mockFlush(HttpStatusCode.Ok, 'OK', 'Test');
});
});
describe('corrects for quirks', async () => {
it('by normalizing 0 status to 200 if a body is present', (done) => {
backend
.handle(TEST_POST)
.pipe(toArray())
.subscribe((events) => {
expect(events.length).toBe(2);
expect(events[1].type).toBe(HttpEventType.Response);
const response = events[1] as HttpResponse<string>;
expect(response.status).toBe(HttpStatusCode.Ok);
done();
});
fetchMock.mockFlush(0, 'CORS 0 status', 'Test');
});
it('by leaving 0 status as 0 if a body is not present', (done) => {
backend
.handle(TEST_POST)
.pipe(toArray())
.subscribe({
error: (error: HttpErrorResponse) => {
expect(error.status).toBe(0);
done();
},
});
fetchMock.mockFlush(0, 'CORS 0 status');
});
});
describe('dynamic global fetch', () => {
beforeEach(() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [provideHttpClient(withFetch())],
});
});
it('should use the current implementation of the global fetch', async () => {
const originalFetch = globalThis.fetch;
try {
const fakeFetch = jasmine
.createSpy('', () => Promise.resolve(new Response(JSON.stringify({foo: 'bar'}))))
.and.callThrough();
globalThis.fetch = fakeFetch;
const client = TestBed.inject(HttpClient);
expect(fakeFetch).not.toHaveBeenCalled();
let response = await client.get<unknown>('').toPromise();
expect(fakeFetch).toHaveBeenCalled();
expect(response).toEqual({foo: 'bar'});
// We dynamicaly change the implementation of fetch
const fakeFetch2 = jasmine
.createSpy('', () => Promise.resolve(new Response(JSON.stringify({foo: 'baz'}))))
.and.callThrough();
globalThis.fetch = fakeFetch2;
response = await client.get<unknown>('').toPromise();
expect(response).toEqual({foo: 'baz'});
} finally {
// We need to restore the original fetch implementation, else the tests might become flaky
globalThis.fetch = originalFetch;
}
});
});
}); | {
"end_byte": 16054,
"start_byte": 9574,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/fetch_spec.ts"
} |
angular/packages/common/http/test/fetch_spec.ts_16056_19954 | export class MockFetchFactory extends FetchFactory {
public readonly response = new MockFetchResponse();
public readonly request = new MockFetchRequest();
private resolve!: Function;
private reject!: Function;
private clearWarningTimeout?: VoidFunction;
private promise = new Promise<Response>((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
override fetch = (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
this.request.method = init?.method;
this.request.url = input;
this.request.body = init?.body;
this.request.headers = init?.headers;
this.request.credentials = init?.credentials;
if (init?.signal) {
init?.signal.addEventListener('abort', () => {
this.reject();
this.clearWarningTimeout?.();
});
}
// Fetch uses a Macrotask to keep the NgZone unstable during the fetch
// If the promise is not resolved/rejected the unit will succeed but the test suite will
// fail with a timeout
const timeoutId = setTimeout(() => {
console.error('********* You forgot to resolve/reject the promise ********* ');
this.reject();
}, 5000);
this.clearWarningTimeout = () => clearTimeout(timeoutId);
return this.promise;
// tslint:disable:semicolon
};
mockFlush(
status: number,
statusText: string,
body?: string | Blob,
headers?: Record<string, string>,
): void {
this.clearWarningTimeout?.();
if (typeof body === 'string') {
this.response.setupBodyStream(body);
} else {
this.response.setBody(body);
}
const response = new Response(this.response.stream, {
statusText,
headers: {...this.response.headers, ...(headers ?? {})},
});
// Have to be set outside the constructor because it might throw
// RangeError: init["status"] must be in the range of 200 to 599, inclusive
Object.defineProperty(response, 'status', {value: status});
if (this.response.url) {
// url is readonly
Object.defineProperty(response, 'url', {value: this.response.url});
}
this.resolve(response);
}
mockProgressEvent(loaded: number): void {
this.response.progress.push(loaded);
}
mockErrorEvent(error: any) {
this.reject(error);
}
mockAbortEvent() {
// When `abort()` is called, the fetch() promise rejects with an Error of type DOMException,
// with name AbortError. see
// https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort
this.reject(new DOMException('', 'AbortError'));
}
resetFetchPromise() {
this.promise = new Promise<Response>((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
}
class MockFetchRequest {
public url!: RequestInfo | URL;
public method?: string;
public body: any;
public credentials?: RequestCredentials;
public headers?: HeadersInit;
}
class MockFetchResponse {
public url?: string;
public headers: Record<string, string> = {};
public progress: number[] = [];
private sub$ = new Subject<any>();
public stream = new ReadableStream({
start: (controller) => {
this.sub$.subscribe({
next: (val) => {
controller.enqueue(new TextEncoder().encode(val));
},
complete: () => {
controller.close();
},
});
},
});
public setBody(body: any) {
this.sub$.next(body);
this.sub$.complete();
}
public setupBodyStream(body?: string) {
if (body && this.progress.length) {
this.headers['content-length'] = `${body.length}`;
let shift = 0;
this.progress.forEach((loaded) => {
this.sub$.next(body.substring(shift, loaded));
shift = loaded;
});
this.sub$.next(body.substring(shift, body.length));
} else {
this.sub$.next(body);
}
this.sub$.complete();
}
} | {
"end_byte": 19954,
"start_byte": 16056,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/fetch_spec.ts"
} |
angular/packages/common/http/test/client_spec.ts_0_511 | /**
* @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 {HttpClient} from '@angular/common/http/src/client';
import {
HttpErrorResponse,
HttpEventType,
HttpResponse,
HttpStatusCode,
} from '@angular/common/http/src/response';
import {HttpClientTestingBackend} from '@angular/common/http/testing/src/backend';
import {toArray} from 'rxjs/operators'; | {
"end_byte": 511,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/client_spec.ts"
} |
angular/packages/common/http/test/client_spec.ts_513_8686 | describe('HttpClient', () => {
let client: HttpClient = null!;
let backend: HttpClientTestingBackend = null!;
beforeEach(() => {
backend = new HttpClientTestingBackend();
client = new HttpClient(backend);
});
afterEach(() => {
backend.verify();
});
describe('makes a basic request', () => {
it('for JSON data', (done) => {
client.get('/test').subscribe((res) => {
expect((res as any)['data']).toEqual('hello world');
done();
});
backend.expectOne('/test').flush({'data': 'hello world'});
});
it('should allow flushing requests with a boolean value', (done: DoneFn) => {
client.get('/test').subscribe((res) => {
expect(res as any).toEqual(true);
done();
});
backend.expectOne('/test').flush(true);
});
it('for text data', (done) => {
client.get('/test', {responseType: 'text'}).subscribe((res) => {
expect(res).toEqual('hello world');
done();
});
backend.expectOne('/test').flush('hello world');
});
it('with headers', (done) => {
client.get('/test', {headers: {'X-Option': 'true'}}).subscribe(() => done());
const req = backend.expectOne('/test');
expect(req.request.headers.get('X-Option')).toEqual('true');
req.flush({});
});
it('with string params', (done) => {
client.get('/test', {params: {'test': 'true'}}).subscribe(() => done());
backend.expectOne('/test?test=true').flush({});
});
it('with an array of string params', (done) => {
client.get('/test', {params: {'test': ['a', 'b']}}).subscribe(() => done());
backend.expectOne('/test?test=a&test=b').flush({});
});
it('with number params', (done) => {
client.get('/test', {params: {'test': 2}}).subscribe(() => done());
backend.expectOne('/test?test=2').flush({});
});
it('with an array of number params', (done) => {
client.get('/test', {params: {'test': [2, 3]}}).subscribe(() => done());
backend.expectOne('/test?test=2&test=3').flush({});
});
it('with boolean params', (done) => {
client.get('/test', {params: {'test': true}}).subscribe(() => done());
backend.expectOne('/test?test=true').flush({});
});
it('with an array of boolean params', (done) => {
client.get('/test', {params: {'test': [true, false]}}).subscribe(() => done());
backend.expectOne('/test?test=true&test=false').flush({});
});
it('with an array of params of different types', (done) => {
client.get('/test', {params: {'test': [true, 'a', 2] as const}}).subscribe(() => done());
backend.expectOne('/test?test=true&test=a&test=2').flush({});
});
it('for an arraybuffer', (done) => {
const body = new ArrayBuffer(4);
client.get('/test', {responseType: 'arraybuffer'}).subscribe((res) => {
expect(res).toBe(body);
done();
});
backend.expectOne('/test').flush(body);
});
if (typeof Blob !== 'undefined') {
it('for a blob', (done) => {
const body = new Blob([new ArrayBuffer(4)]);
client.get('/test', {responseType: 'blob'}).subscribe((res) => {
expect(res).toBe(body);
done();
});
backend.expectOne('/test').flush(body);
});
}
it('that returns a response', (done) => {
const body = {'data': 'hello world'};
client.get('/test', {observe: 'response'}).subscribe((res) => {
expect(res instanceof HttpResponse).toBe(true);
expect(res.body).toBe(body);
done();
});
backend.expectOne('/test').flush(body);
});
it('that returns a stream of events', (done) => {
client
.get('/test', {observe: 'events'})
.pipe(toArray())
.toPromise()
.then((events) => {
expect(events!.length).toBe(2);
let x = HttpResponse;
expect(events![0].type).toBe(HttpEventType.Sent);
expect(events![1].type).toBe(HttpEventType.Response);
expect(events![1] instanceof HttpResponse).toBeTruthy();
done();
});
backend.expectOne('/test').flush({'data': 'hello world'});
});
it('with progress events enabled', (done) => {
client.get('/test', {reportProgress: true}).subscribe(() => done());
const req = backend.expectOne('/test');
expect(req.request.reportProgress).toEqual(true);
req.flush({});
});
});
describe('makes a POST request', () => {
it('with text data', (done) => {
client
.post('/test', 'text body', {observe: 'response', responseType: 'text'})
.subscribe((res) => {
expect(res.ok).toBeTruthy();
expect(res.status).toBe(HttpStatusCode.Ok);
done();
});
backend.expectOne('/test').flush('hello world');
});
it('with json data', (done) => {
const body = {data: 'json body'};
client.post('/test', body, {observe: 'response', responseType: 'text'}).subscribe((res) => {
expect(res.ok).toBeTruthy();
expect(res.status).toBe(HttpStatusCode.Ok);
done();
});
const testReq = backend.expectOne('/test');
expect(testReq.request.body).toBe(body);
testReq.flush('hello world');
});
it('with a json body of false', (done) => {
client.post('/test', false, {observe: 'response', responseType: 'text'}).subscribe((res) => {
expect(res.ok).toBeTruthy();
expect(res.status).toBe(HttpStatusCode.Ok);
done();
});
const testReq = backend.expectOne('/test');
expect(testReq.request.body).toBe(false);
testReq.flush('hello world');
});
it('with a json body of 0', (done) => {
client.post('/test', 0, {observe: 'response', responseType: 'text'}).subscribe((res) => {
expect(res.ok).toBeTruthy();
expect(res.status).toBe(HttpStatusCode.Ok);
done();
});
const testReq = backend.expectOne('/test');
expect(testReq.request.body).toBe(0);
testReq.flush('hello world');
});
it('with an arraybuffer', (done) => {
const body = new ArrayBuffer(4);
client.post('/test', body, {observe: 'response', responseType: 'text'}).subscribe((res) => {
expect(res.ok).toBeTruthy();
expect(res.status).toBe(HttpStatusCode.Ok);
done();
});
const testReq = backend.expectOne('/test');
expect(testReq.request.body).toBe(body);
testReq.flush('hello world');
});
});
describe('makes a DELETE request', () => {
it('with body', (done) => {
const body = {data: 'json body'};
client
.delete('/test', {observe: 'response', responseType: 'text', body: body})
.subscribe((res) => {
expect(res.ok).toBeTruthy();
expect(res.status).toBe(200);
done();
});
const testReq = backend.expectOne('/test');
expect(testReq.request.body).toBe(body);
testReq.flush('hello world');
});
it('without body', (done) => {
client.delete('/test', {observe: 'response', responseType: 'text'}).subscribe((res) => {
expect(res.ok).toBeTruthy();
expect(res.status).toBe(200);
done();
});
const testReq = backend.expectOne('/test');
expect(testReq.request.body).toBe(null);
testReq.flush('hello world');
});
});
describe('makes a JSONP request', () => {
it('with properly set method and callback', (done) => {
client.jsonp('/test', 'myCallback').subscribe(() => done());
backend
.expectOne({method: 'JSONP', url: '/test?myCallback=JSONP_CALLBACK'})
.flush('hello world');
});
});
describe('makes a request for an error response', () => {
it('with a JSON body', (done) => {
client.get('/test').subscribe(
() => {},
(res: HttpErrorResponse) => {
expect(res.error.data).toEqual('hello world');
done();
},
);
backend
.expectOne('/test')
.flush(
{'data': 'hello world'},
{status: HttpStatusCode.InternalServerError, statusText: 'Server error'},
);
});
}); | {
"end_byte": 8686,
"start_byte": 513,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/client_spec.ts"
} |
angular/packages/common/http/test/client_spec.ts_8689_9115 | describe('throws an error', () => {
it('for a request with nullish header', () => {
client.request('GET', '/test', {headers: {foo: null!}}).subscribe();
expect(() => backend.expectOne('/test').request.headers.has('random-header')).toThrowError(
'Unexpected value of the `foo` header provided. ' +
'Expecting either a string, a number or an array, but got: `null`.',
);
});
});
}); | {
"end_byte": 9115,
"start_byte": 8689,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/client_spec.ts"
} |
angular/packages/common/http/test/xhr_mock.ts_0_3771 | /**
* @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 {XhrFactory} from '@angular/common';
import {HttpHeaders} from '@angular/common/http/src/headers';
export class MockXhrFactory implements XhrFactory {
// TODO(issue/24571): remove '!'.
mock!: MockXMLHttpRequest;
build(): XMLHttpRequest {
return (this.mock = new MockXMLHttpRequest()) as any;
}
}
export class MockXMLHttpRequestUpload {
constructor(private mock: MockXMLHttpRequest) {}
addEventListener(event: 'progress', handler: Function) {
this.mock.addEventListener('uploadProgress', handler);
}
removeEventListener(event: 'progress', handler: Function) {
this.mock.removeEventListener('uploadProgress');
}
}
export class MockXMLHttpRequest {
// Set by method calls.
body: any;
// TODO(issue/24571): remove '!'.
method!: string;
// TODO(issue/24571): remove '!'.
url!: string;
mockHeaders: {[key: string]: string} = {};
mockAborted: boolean = false;
// Directly settable interface.
withCredentials: boolean = false;
responseType: string = 'text';
// Mocked response interface.
response: any | undefined = undefined;
responseText: string | undefined = undefined;
responseURL: string | null = null;
status: number = 0;
statusText: string = '';
mockResponseHeaders: string = '';
listeners: {
error?: (event: ProgressEvent) => void;
timeout?: (event: ProgressEvent) => void;
abort?: () => void;
load?: () => void;
progress?: (event: ProgressEvent) => void;
uploadProgress?: (event: ProgressEvent) => void;
} = {};
upload = new MockXMLHttpRequestUpload(this);
open(method: string, url: string): void {
this.method = method;
this.url = url;
}
send(body: any): void {
this.body = body;
}
addEventListener(
event: 'error' | 'timeout' | 'load' | 'progress' | 'uploadProgress' | 'abort',
handler: Function,
): void {
this.listeners[event] = handler as any;
}
removeEventListener(
event: 'error' | 'timeout' | 'load' | 'progress' | 'uploadProgress' | 'abort',
): void {
delete this.listeners[event];
}
setRequestHeader(name: string, value: string): void {
this.mockHeaders[name] = value;
}
getAllResponseHeaders(): string {
return this.mockResponseHeaders;
}
getResponseHeader(header: string): string | null {
return new HttpHeaders(this.mockResponseHeaders).get(header);
}
mockFlush(status: number, statusText: string, body?: string) {
if (typeof body === 'string') {
this.responseText = body;
} else {
this.response = body;
}
this.status = status;
this.statusText = statusText;
this.mockLoadEvent();
}
mockDownloadProgressEvent(loaded: number, total?: number): void {
if (this.listeners.progress) {
this.listeners.progress({lengthComputable: total !== undefined, loaded, total} as any);
}
}
mockUploadProgressEvent(loaded: number, total?: number) {
if (this.listeners.uploadProgress) {
this.listeners.uploadProgress({
lengthComputable: total !== undefined,
loaded,
total,
} as any);
}
}
mockLoadEvent(): void {
if (this.listeners.load) {
this.listeners.load();
}
}
mockErrorEvent(error: any): void {
if (this.listeners.error) {
this.listeners.error(error);
}
}
mockTimeoutEvent(error: any): void {
if (this.listeners.timeout) {
this.listeners.timeout(error);
}
}
mockAbortEvent(): void {
if (this.listeners.abort) {
this.listeners.abort();
}
}
abort() {
this.mockAborted = true;
}
}
| {
"end_byte": 3771,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/xhr_mock.ts"
} |
angular/packages/common/http/test/module_spec.ts_0_5236 | /**
* @license
* Copyright Google LLC All Rights Reserved.sonpCallbackContext
*
* 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 {HttpHandler} from '@angular/common/http/src/backend';
import {HttpClient} from '@angular/common/http/src/client';
import {HttpContext, HttpContextToken} from '@angular/common/http/src/context';
import {HTTP_INTERCEPTORS, HttpInterceptor} from '@angular/common/http/src/interceptor';
import {HttpRequest} from '@angular/common/http/src/request';
import {HttpEvent, HttpResponse} from '@angular/common/http/src/response';
import {HttpTestingController} from '@angular/common/http/testing/src/api';
import {HttpClientTestingModule} from '@angular/common/http/testing/src/module';
import {TestRequest} from '@angular/common/http/testing/src/request';
import {Injectable, Injector} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
const IS_INTERCEPTOR_C_ENABLED = new HttpContextToken<boolean | undefined>(() => undefined);
class TestInterceptor implements HttpInterceptor {
constructor(private value: string) {}
intercept(req: HttpRequest<any>, delegate: HttpHandler): Observable<HttpEvent<any>> {
const existing = req.headers.get('Intercepted');
const next = !!existing ? existing + ',' + this.value : this.value;
req = req.clone({setHeaders: {'Intercepted': next}});
return delegate.handle(req).pipe(
map((event) => {
if (event instanceof HttpResponse) {
const existing = event.headers.get('Intercepted');
const next = !!existing ? existing + ',' + this.value : this.value;
return event.clone({headers: event.headers.set('Intercepted', next)});
}
return event;
}),
);
}
}
class InterceptorA extends TestInterceptor {
constructor() {
super('A');
}
}
class InterceptorB extends TestInterceptor {
constructor() {
super('B');
}
}
class InterceptorC extends TestInterceptor {
constructor() {
super('C');
}
override intercept(req: HttpRequest<any>, delegate: HttpHandler): Observable<HttpEvent<any>> {
if (req.context.get(IS_INTERCEPTOR_C_ENABLED) === true) {
return super.intercept(req, delegate);
}
return delegate.handle(req);
}
}
@Injectable()
class ReentrantInterceptor implements HttpInterceptor {
constructor(private client: HttpClient) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req);
}
}
describe('HttpClientModule', () => {
let injector: Injector;
beforeEach(() => {
injector = TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
{provide: HTTP_INTERCEPTORS, useClass: InterceptorA, multi: true},
{provide: HTTP_INTERCEPTORS, useClass: InterceptorB, multi: true},
{provide: HTTP_INTERCEPTORS, useClass: InterceptorC, multi: true},
],
});
});
it('initializes HttpClient properly', (done) => {
injector
.get(HttpClient)
.get('/test', {responseType: 'text'})
.subscribe((value: string) => {
expect(value).toBe('ok!');
done();
});
injector.get(HttpTestingController).expectOne('/test').flush('ok!');
});
it('intercepts outbound responses in the order in which interceptors were bound', (done) => {
injector
.get(HttpClient)
.get('/test', {observe: 'response', responseType: 'text'})
.subscribe(() => done());
const req = injector.get(HttpTestingController).expectOne('/test') as TestRequest;
expect(req.request.headers.get('Intercepted')).toEqual('A,B');
req.flush('ok!');
});
it('intercepts outbound responses in the order in which interceptors were bound and include specifically enabled interceptor', (done) => {
injector
.get(HttpClient)
.get('/test', {
observe: 'response',
responseType: 'text',
context: new HttpContext().set(IS_INTERCEPTOR_C_ENABLED, true),
})
.subscribe((value) => done());
const req = injector.get(HttpTestingController).expectOne('/test') as TestRequest;
expect(req.request.headers.get('Intercepted')).toEqual('A,B,C');
req.flush('ok!');
});
it('intercepts inbound responses in the right (reverse binding) order', (done) => {
injector
.get(HttpClient)
.get('/test', {observe: 'response', responseType: 'text'})
.subscribe((value: HttpResponse<string>) => {
expect(value.headers.get('Intercepted')).toEqual('B,A');
done();
});
injector.get(HttpTestingController).expectOne('/test').flush('ok!');
});
it('allows interceptors to inject HttpClient', (done) => {
TestBed.resetTestingModule();
injector = TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [{provide: HTTP_INTERCEPTORS, useClass: ReentrantInterceptor, multi: true}],
});
injector
.get(HttpClient)
.get('/test')
.subscribe(() => {
done();
});
injector.get(HttpTestingController).expectOne('/test').flush('ok!');
});
});
| {
"end_byte": 5236,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/module_spec.ts"
} |
angular/packages/common/http/test/xsrf_spec.ts_0_4547 | /**
* @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 {HttpHeaders} from '@angular/common/http/src/headers';
import {HttpRequest} from '@angular/common/http/src/request';
import {
HttpXsrfCookieExtractor,
HttpXsrfInterceptor,
HttpXsrfTokenExtractor,
XSRF_ENABLED,
XSRF_HEADER_NAME,
} from '@angular/common/http/src/xsrf';
import {HttpClientTestingBackend} from '@angular/common/http/testing/src/backend';
import {TestBed} from '@angular/core/testing';
class SampleTokenExtractor extends HttpXsrfTokenExtractor {
constructor(private token: string | null) {
super();
}
override getToken(): string | null {
return this.token;
}
}
describe('HttpXsrfInterceptor', () => {
let backend: HttpClientTestingBackend;
let interceptor: HttpXsrfInterceptor;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{
provide: HttpXsrfTokenExtractor,
useValue: new SampleTokenExtractor('test'),
},
{
provide: XSRF_HEADER_NAME,
useValue: 'X-XSRF-TOKEN',
},
{
provide: XSRF_ENABLED,
useValue: true,
},
HttpXsrfInterceptor,
],
});
interceptor = TestBed.inject(HttpXsrfInterceptor);
backend = new HttpClientTestingBackend();
});
it('applies XSRF protection to outgoing requests', () => {
interceptor.intercept(new HttpRequest('POST', '/test', {}), backend).subscribe();
const req = backend.expectOne('/test');
expect(req.request.headers.get('X-XSRF-TOKEN')).toEqual('test');
req.flush({});
});
it('does not apply XSRF protection when request is a GET', () => {
interceptor.intercept(new HttpRequest('GET', '/test'), backend).subscribe();
const req = backend.expectOne('/test');
expect(req.request.headers.has('X-XSRF-TOKEN')).toEqual(false);
req.flush({});
});
it('does not apply XSRF protection when request is a HEAD', () => {
interceptor.intercept(new HttpRequest('HEAD', '/test'), backend).subscribe();
const req = backend.expectOne('/test');
expect(req.request.headers.has('X-XSRF-TOKEN')).toEqual(false);
req.flush({});
});
it('does not overwrite existing header', () => {
interceptor
.intercept(
new HttpRequest(
'POST',
'/test',
{},
{headers: new HttpHeaders().set('X-XSRF-TOKEN', 'blah')},
),
backend,
)
.subscribe();
const req = backend.expectOne('/test');
expect(req.request.headers.get('X-XSRF-TOKEN')).toEqual('blah');
req.flush({});
});
it('does not set the header for a null token', () => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
{
provide: HttpXsrfTokenExtractor,
useValue: new SampleTokenExtractor(null),
},
{
provide: XSRF_HEADER_NAME,
useValue: 'X-XSRF-TOKEN',
},
{
provide: XSRF_ENABLED,
useValue: true,
},
HttpXsrfInterceptor,
],
});
interceptor = TestBed.inject(HttpXsrfInterceptor);
interceptor.intercept(new HttpRequest('POST', '/test', {}), backend).subscribe();
const req = backend.expectOne('/test');
expect(req.request.headers.has('X-XSRF-TOKEN')).toEqual(false);
req.flush({});
});
afterEach(() => {
backend.verify();
});
});
describe('HttpXsrfCookieExtractor', () => {
let document: {[key: string]: string};
let extractor: HttpXsrfCookieExtractor;
beforeEach(() => {
document = {
cookie: 'XSRF-TOKEN=test',
};
extractor = new HttpXsrfCookieExtractor(document, 'browser', 'XSRF-TOKEN');
});
it('parses the cookie from document.cookie', () => {
expect(extractor.getToken()).toEqual('test');
});
it('does not re-parse if document.cookie has not changed', () => {
expect(extractor.getToken()).toEqual('test');
expect(extractor.getToken()).toEqual('test');
expect(getParseCount(extractor)).toEqual(1);
});
it('re-parses if document.cookie changes', () => {
expect(extractor.getToken()).toEqual('test');
document['cookie'] = 'XSRF-TOKEN=blah';
expect(extractor.getToken()).toEqual('blah');
expect(getParseCount(extractor)).toEqual(2);
});
});
function getParseCount(extractor: HttpXsrfCookieExtractor): number {
return (extractor as any).parseCount;
}
| {
"end_byte": 4547,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/xsrf_spec.ts"
} |
angular/packages/common/http/test/context_spec.ts_0_2061 | /**
* @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 {HttpContext, HttpContextToken} from '../src/context';
const IS_ENABLED = new HttpContextToken<boolean>(() => false);
const UNUSED = new HttpContextToken<boolean>(() => true);
const CACHE_OPTION = new HttpContextToken<{cache: boolean; expiresIn?: number}>(() => ({
cache: false,
}));
describe('HttpContext', () => {
let context: HttpContext;
beforeEach(() => {
context = new HttpContext();
});
describe('with basic value', () => {
it('should test public api', () => {
expect(context.has(UNUSED)).toBe(false);
expect(context.get(IS_ENABLED)).toBe(false);
expect([...context.keys()]).toEqual([IS_ENABLED]); // value from factory function is stored in the map upon access
expect(context.has(IS_ENABLED)).toBe(true);
context.set(IS_ENABLED, true);
expect(context.has(IS_ENABLED)).toBe(true);
expect(context.get(IS_ENABLED)).toBe(true);
expect([...context.keys()]).toEqual([IS_ENABLED]);
context.delete(IS_ENABLED);
expect([...context.keys()]).toEqual([]);
});
});
describe('with complex value', () => {
it('should test public api', () => {
expect(context.get(CACHE_OPTION)).toEqual({cache: false});
expect([...context.keys()]).toEqual([CACHE_OPTION]);
const value = {cache: true, expiresIn: 30};
context.set(CACHE_OPTION, value);
expect(context.get(CACHE_OPTION)).toBe(value);
expect([...context.keys()]).toEqual([CACHE_OPTION]);
context.delete(CACHE_OPTION);
expect([...context.keys()]).toEqual([]);
});
it('should ensure that same reference is returned for default value between multiple accesses', () => {
const value = context.get(CACHE_OPTION); // will get default value
expect(value).toEqual({cache: false});
expect(context.get(CACHE_OPTION)).toBe(value);
});
});
});
| {
"end_byte": 2061,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/context_spec.ts"
} |
angular/packages/common/http/test/params_spec.ts_0_263 | /**
* @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 {HttpParams} from '@angular/common/http/src/params'; | {
"end_byte": 263,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/params_spec.ts"
} |
angular/packages/common/http/test/params_spec.ts_265_7369 | describe('HttpUrlEncodedParams', () => {
describe('initialization', () => {
it('should be empty at construction', () => {
const body = new HttpParams();
expect(body.toString()).toEqual('');
});
it('should parse an existing url', () => {
const body = new HttpParams({fromString: 'a=b&c=d&c=e'});
expect(body.getAll('a')).toEqual(['b']);
expect(body.getAll('c')).toEqual(['d', 'e']);
});
it('should ignore question mark in a url', () => {
const body = new HttpParams({fromString: '?a=b&c=d&c=e'});
expect(body.getAll('a')).toEqual(['b']);
expect(body.getAll('c')).toEqual(['d', 'e']);
});
it('should only remove question mark at the beginning of the params', () => {
const body = new HttpParams({fromString: '?a=b&c=d&?e=f'});
expect(body.getAll('a')).toEqual(['b']);
expect(body.getAll('c')).toEqual(['d']);
expect(body.getAll('?e')).toEqual(['f']);
});
});
describe('lazy mutation', () => {
it('should allow setting string parameters', () => {
const body = new HttpParams({fromString: 'a=b'});
const mutated = body.set('a', 'c');
expect(mutated.toString()).toEqual('a=c');
});
it('should allow setting number parameters', () => {
const body = new HttpParams({fromString: 'a=b'});
const mutated = body.set('a', 1);
expect(mutated.toString()).toEqual('a=1');
});
it('should allow setting boolean parameters', () => {
const body = new HttpParams({fromString: 'a=b'});
const mutated = body.set('a', true);
expect(mutated.toString()).toEqual('a=true');
});
it('should allow appending string parameters', () => {
const body = new HttpParams({fromString: 'a=b'});
const mutated = body.append('a', 'c');
expect(mutated.toString()).toEqual('a=b&a=c');
});
it('should allow appending number parameters', () => {
const body = new HttpParams({fromString: 'a=b'});
const mutated = body.append('a', 1);
expect(mutated.toString()).toEqual('a=b&a=1');
});
it('should allow appending boolean parameters', () => {
const body = new HttpParams({fromString: 'a=b'});
const mutated = body.append('a', true);
expect(mutated.toString()).toEqual('a=b&a=true');
});
it('should allow appending all string parameters', () => {
const body = new HttpParams({fromString: 'a=a1&b=b1'});
const mutated = body.appendAll({a: ['a2', 'a3'], b: 'b2'});
expect(mutated.toString()).toEqual('a=a1&a=a2&a=a3&b=b1&b=b2');
});
it('should allow appending all number parameters', () => {
const body = new HttpParams({fromString: 'a=1&b=b1'});
const mutated = body.appendAll({a: [2, 3], b: 'b2'});
expect(mutated.toString()).toEqual('a=1&a=2&a=3&b=b1&b=b2');
});
it('should allow appending all boolean parameters', () => {
const body = new HttpParams({fromString: 'a=true&b=b1'});
const mutated = body.appendAll({a: [true, false], b: 'b2'});
expect(mutated.toString()).toEqual('a=true&a=true&a=false&b=b1&b=b2');
});
it('should allow appending all parameters of different types', () => {
const body = new HttpParams({fromString: 'a=true&b=b1'});
const mutated = body.appendAll({a: [true, 0, 'a1'] as const, b: 'b2'});
expect(mutated.toString()).toEqual('a=true&a=true&a=0&a=a1&b=b1&b=b2');
});
it('should allow deletion of parameters', () => {
const body = new HttpParams({fromString: 'a=b&c=d&e=f'});
const mutated = body.delete('c');
expect(mutated.toString()).toEqual('a=b&e=f');
});
it('should allow deletion of parameters with specific string value', () => {
const body = new HttpParams({fromString: 'a=b&c=d&e=f'});
const notMutated = body.delete('c', 'z');
expect(notMutated.toString()).toEqual('a=b&c=d&e=f');
const mutated = body.delete('c', 'd');
expect(mutated.toString()).toEqual('a=b&e=f');
});
it('should allow deletion of parameters with specific number value', () => {
const body = new HttpParams({fromString: 'a=b&c=1&e=f'});
const notMutated = body.delete('c', 2);
expect(notMutated.toString()).toEqual('a=b&c=1&e=f');
const mutated = body.delete('c', 1);
expect(mutated.toString()).toEqual('a=b&e=f');
});
it('should allow deletion of parameters with specific boolean value', () => {
const body = new HttpParams({fromString: 'a=b&c=true&e=f'});
const notMutated = body.delete('c', false);
expect(notMutated.toString()).toEqual('a=b&c=true&e=f');
const mutated = body.delete('c', true);
expect(mutated.toString()).toEqual('a=b&e=f');
});
it('should allow chaining of mutations', () => {
const body = new HttpParams({fromString: 'a=b&c=d&e=f'});
const mutated = body.append('e', 'y').delete('c').set('a', 'x').append('e', 'z');
expect(mutated.toString()).toEqual('a=x&e=f&e=y&e=z');
});
it('should allow deletion of one value of a string parameter', () => {
const body = new HttpParams({fromString: 'a=1&a=2&a=3&a=4&a=5'});
const mutated = body.delete('a', '2').delete('a', '4');
expect(mutated.getAll('a')).toEqual(['1', '3', '5']);
});
it('should allow deletion of one value of a number parameter', () => {
const body = new HttpParams({fromString: 'a=0&a=1&a=2&a=3&a=4&a=5'});
const mutated = body.delete('a', 0).delete('a', 4);
expect(mutated.getAll('a')).toEqual(['1', '2', '3', '5']);
});
it('should allow deletion of one value of a boolean parameter', () => {
const body = new HttpParams({fromString: 'a=false&a=true&a=false'});
const mutated = body.delete('a', false);
expect(mutated.getAll('a')).toEqual(['true', 'false']);
});
it('should not repeat mutations that have already been materialized', () => {
const body = new HttpParams({fromString: 'a=b'});
const mutated = body.append('a', 'c');
expect(mutated.toString()).toEqual('a=b&a=c');
const mutated2 = mutated.append('c', 'd');
expect(mutated.toString()).toEqual('a=b&a=c');
expect(mutated2.toString()).toEqual('a=b&a=c&c=d');
});
});
describe('read operations', () => {
it('should give null if parameter is not set', () => {
const body = new HttpParams({fromString: 'a=b&c=d'});
expect(body.get('e')).toBeNull();
expect(body.getAll('e')).toBeNull();
});
it('should give an accurate list of keys', () => {
const body = new HttpParams({fromString: 'a=1&b=2&c=3&d=4'});
expect(body.keys()).toEqual(['a', 'b', 'c', 'd']);
});
});
describe('encoding', () => {
it('should encode parameters', () => {
const body = new HttpParams({fromString: 'a=standard_chars'});
expect(body.toString()).toEqual('a=standard_chars');
const body2 = new HttpParams({fromString: 'a=1 2 3&b=mail@test&c=3_^[]$&d=eq=1&e=1+1'});
expect(body2.toString()).toEqual('a=1%202%203&b=mail@test&c=3_%5E%5B%5D$&d=eq=1&e=1%2B1');
});
}); | {
"end_byte": 7369,
"start_byte": 265,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/params_spec.ts"
} |
angular/packages/common/http/test/params_spec.ts_7373_9349 | describe('toString', () => {
it('should stringify string params', () => {
const body = new HttpParams({fromObject: {a: '', b: '2', c: '3'}});
expect(body.toString()).toBe('a=&b=2&c=3');
});
it('should stringify string array params', () => {
const body = new HttpParams({fromObject: {a: '', b: ['21', '22'], c: '3'}});
expect(body.toString()).toBe('a=&b=21&b=22&c=3');
});
it('should stringify number params', () => {
const body = new HttpParams({fromObject: {a: '', b: 2, c: 3}});
expect(body.toString()).toBe('a=&b=2&c=3');
// make sure the param value is now a string
expect(body.get('b')).toBe('2');
});
it('should stringify number array params', () => {
const body = new HttpParams({fromObject: {a: '', b: [21, 22], c: 3}});
expect(body.toString()).toBe('a=&b=21&b=22&c=3');
// make sure the param values are now strings
expect(body.getAll('b')).toEqual(['21', '22']);
});
it('should stringify boolean params', () => {
const body = new HttpParams({fromObject: {a: '', b: true, c: 3}});
expect(body.toString()).toBe('a=&b=true&c=3');
// make sure the param value is now a boolean
expect(body.get('b')).toBe('true');
});
it('should stringify boolean array params', () => {
const body = new HttpParams({fromObject: {a: '', b: [true, false], c: 3}});
expect(body.toString()).toBe('a=&b=true&b=false&c=3');
// make sure the param values are now booleans
expect(body.getAll('b')).toEqual(['true', 'false']);
});
it('should stringify array params of different types', () => {
const body = new HttpParams({fromObject: {a: ['', false, 3] as const}});
expect(body.toString()).toBe('a=&a=false&a=3');
});
it('should stringify empty array params', () => {
const body = new HttpParams({fromObject: {a: '', b: [], c: '3'}});
expect(body.toString()).toBe('a=&c=3');
});
});
}); | {
"end_byte": 9349,
"start_byte": 7373,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/params_spec.ts"
} |
angular/packages/common/http/test/jsonp_spec.ts_0_3937 | /**
* @license
* Copyright Google LLC All Rights Reserved.sonpCallbackContext
*
* 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 {HttpHeaders} from '@angular/common/http/src/headers';
import {
JSONP_ERR_HEADERS_NOT_SUPPORTED,
JSONP_ERR_NO_CALLBACK,
JSONP_ERR_WRONG_METHOD,
JSONP_ERR_WRONG_RESPONSE_TYPE,
JsonpClientBackend,
} from '@angular/common/http/src/jsonp';
import {HttpRequest} from '@angular/common/http/src/request';
import {HttpErrorResponse, HttpEventType} from '@angular/common/http/src/response';
import {toArray} from 'rxjs/operators';
import {MockDocument} from './jsonp_mock';
describe('JsonpClientBackend', () => {
const SAMPLE_REQ = new HttpRequest<never>('JSONP', '/test');
let home: any;
let document: MockDocument;
let backend: JsonpClientBackend;
function runOnlyCallback(home: any, data: Object) {
const keys = Object.keys(home);
expect(keys.length).toBe(1);
const callback = home[keys[0]];
callback(data);
}
beforeEach(() => {
home = {};
document = new MockDocument();
backend = new JsonpClientBackend(home, document);
});
it('handles a basic request', (done) => {
backend
.handle(SAMPLE_REQ)
.pipe(toArray())
.subscribe((events) => {
expect(events.map((event) => event.type)).toEqual([
HttpEventType.Sent,
HttpEventType.Response,
]);
done();
});
runOnlyCallback(home, {data: 'This is a test'});
document.mockLoad();
});
// Issue #39496
it('handles a request with callback call wrapped in promise', (done) => {
backend.handle(SAMPLE_REQ).subscribe({complete: done});
queueMicrotask(() => {
runOnlyCallback(home, {data: 'This is a test'});
});
document.mockLoad();
});
it('handles an error response properly', (done) => {
const error = new Error('This is a test error');
backend
.handle(SAMPLE_REQ)
.pipe(toArray())
.subscribe(undefined, (err: HttpErrorResponse) => {
expect(err.status).toBe(0);
expect(err.error).toBe(error);
done();
});
document.mockError(error);
});
it('prevents the script from executing when the request is cancelled', () => {
const sub = backend.handle(SAMPLE_REQ).subscribe();
expect(Object.keys(home).length).toBe(1);
const keys = Object.keys(home);
const spy = jasmine.createSpy('spy', home[keys[0]]);
sub.unsubscribe();
document.mockLoad();
expect(Object.keys(home).length).toBe(0);
expect(spy).not.toHaveBeenCalled();
// The script element should have been transferred to a different document to prevent it from
// executing.
expect(document.mock!.ownerDocument).not.toEqual(document);
});
describe('throws an error', () => {
it('when request method is not JSONP', () =>
expect(() => backend.handle(SAMPLE_REQ.clone<never>({method: 'GET'}))).toThrowError(
JSONP_ERR_WRONG_METHOD,
));
it('when response type is not json', () =>
expect(() =>
backend.handle(
SAMPLE_REQ.clone<never>({
responseType: 'text',
}),
),
).toThrowError(JSONP_ERR_WRONG_RESPONSE_TYPE));
it('when headers are set in request', () =>
expect(() =>
backend.handle(
SAMPLE_REQ.clone<never>({
headers: new HttpHeaders({'Content-Type': 'application/json'}),
}),
),
).toThrowError(JSONP_ERR_HEADERS_NOT_SUPPORTED));
it('when callback is never called', (done) => {
backend.handle(SAMPLE_REQ).subscribe(undefined, (err: HttpErrorResponse) => {
expect(err.status).toBe(0);
expect(err.error instanceof Error).toEqual(true);
expect(err.error.message).toEqual(JSONP_ERR_NO_CALLBACK);
done();
});
document.mockLoad();
});
});
});
| {
"end_byte": 3937,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/jsonp_spec.ts"
} |
angular/packages/common/http/test/transfer_cache_spec.ts_0_1465 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {DOCUMENT} from '@angular/common';
import {ApplicationRef, Component, Injectable, PLATFORM_ID} from '@angular/core';
import {makeStateKey, TransferState} from '@angular/core/src/transfer_state';
import {fakeAsync, flush, TestBed} from '@angular/core/testing';
import {withBody} from '@angular/private/testing';
import {BehaviorSubject} from 'rxjs';
import {HttpClient, HttpResponse, provideHttpClient} from '../public_api';
import {
BODY,
HEADERS,
HTTP_TRANSFER_CACHE_ORIGIN_MAP,
RESPONSE_TYPE,
STATUS,
STATUS_TEXT,
REQ_URL,
withHttpTransferCache,
} from '../src/transfer_cache';
import {HttpTestingController, provideHttpClientTesting} from '../testing';
import {PLATFORM_BROWSER_ID, PLATFORM_SERVER_ID} from '../../src/platform_id';
interface RequestParams {
method?: string;
observe?: 'body' | 'response';
transferCache?: {includeHeaders: string[]} | boolean;
headers?: {[key: string]: string};
body?: RequestBody;
}
type RequestBody =
| ArrayBuffer
| Blob
| boolean
| string
| number
| Object
| (boolean | string | number | Object | null)[]
| null;
describe('TransferCache', () => {
@Component({
selector: 'test-app-http',
template: 'hello',
standalone: false,
})
class SomeComponent {} | {
"end_byte": 1465,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/transfer_cache_spec.ts"
} |
angular/packages/common/http/test/transfer_cache_spec.ts_1469_9643 | describe('withHttpTransferCache', () => {
let isStable: BehaviorSubject<boolean>;
function makeRequestAndExpectOne(
url: string,
body: RequestBody,
params?: RequestParams,
): string;
function makeRequestAndExpectOne(
url: string,
body: RequestBody,
params?: RequestParams & {observe: 'response'},
): HttpResponse<string>;
function makeRequestAndExpectOne(url: string, body: RequestBody, params?: RequestParams): any {
let response!: any;
TestBed.inject(HttpClient)
.request(params?.method ?? 'GET', url, params)
.subscribe((r) => (response = r));
TestBed.inject(HttpTestingController).expectOne(url).flush(body, {headers: params?.headers});
return response;
}
function makeRequestAndExpectNone(
url: string,
method: string = 'GET',
params?: RequestParams,
): HttpResponse<string> {
let response!: HttpResponse<string>;
TestBed.inject(HttpClient)
.request(method, url, {observe: 'response', ...params})
.subscribe((r) => (response = r));
TestBed.inject(HttpTestingController).expectNone(url);
return response;
}
beforeEach(
withBody('<test-app-http></test-app-http>', () => {
TestBed.resetTestingModule();
isStable = new BehaviorSubject<boolean>(false);
@Injectable()
class ApplicationRefPatched extends ApplicationRef {
override isStable = new BehaviorSubject<boolean>(false);
}
TestBed.configureTestingModule({
declarations: [SomeComponent],
providers: [
{provide: PLATFORM_ID, useValue: PLATFORM_SERVER_ID},
{provide: DOCUMENT, useFactory: () => document},
{provide: ApplicationRef, useClass: ApplicationRefPatched},
withHttpTransferCache({}),
provideHttpClient(),
provideHttpClientTesting(),
],
});
const appRef = TestBed.inject(ApplicationRef);
appRef.bootstrap(SomeComponent);
isStable = appRef.isStable as BehaviorSubject<boolean>;
}),
);
it('should store HTTP calls in cache when application is not stable', () => {
makeRequestAndExpectOne('/test', 'foo');
const transferState = TestBed.inject(TransferState);
const key = makeStateKey(Object.keys((transferState as any).store)[0]);
expect(transferState.get(key, null)).toEqual(jasmine.objectContaining({[BODY]: 'foo'}));
});
it('should stop storing HTTP calls in `TransferState` after application becomes stable', fakeAsync(() => {
makeRequestAndExpectOne('/test-1', 'foo');
makeRequestAndExpectOne('/test-2', 'buzz');
isStable.next(true);
flush();
makeRequestAndExpectOne('/test-3', 'bar');
const transferState = TestBed.inject(TransferState);
expect(JSON.parse(transferState.toJson()) as Record<string, unknown>).toEqual({
'2400571479': {
[BODY]: 'foo',
[HEADERS]: {},
[STATUS]: 200,
[STATUS_TEXT]: 'OK',
[REQ_URL]: '/test-1',
[RESPONSE_TYPE]: 'json',
},
'2400572440': {
[BODY]: 'buzz',
[HEADERS]: {},
[STATUS]: 200,
[STATUS_TEXT]: 'OK',
[REQ_URL]: '/test-2',
[RESPONSE_TYPE]: 'json',
},
});
}));
it(`should use calls from cache when present and application is not stable`, () => {
makeRequestAndExpectOne('/test-1', 'foo');
// Do the same call, this time it should served from cache.
makeRequestAndExpectNone('/test-1');
});
it(`should not use calls from cache when present and application is stable`, fakeAsync(() => {
makeRequestAndExpectOne('/test-1', 'foo');
isStable.next(true);
flush();
// Do the same call, this time it should go through as application is stable.
makeRequestAndExpectOne('/test-1', 'foo');
}));
it(`should differentiate calls with different parameters`, async () => {
// make calls with different parameters. All of which should be saved in the state.
makeRequestAndExpectOne('/test-1?foo=1', 'foo');
makeRequestAndExpectOne('/test-1', 'foo');
makeRequestAndExpectOne('/test-1?foo=2', 'buzz');
makeRequestAndExpectNone('/test-1?foo=1');
await expectAsync(TestBed.inject(HttpClient).get('/test-1?foo=1').toPromise()).toBeResolvedTo(
'foo',
);
});
it('should skip cache when specified', () => {
makeRequestAndExpectOne('/test-1?foo=1', 'foo', {transferCache: false});
// The previous request wasn't cached so this one can't use the cache
makeRequestAndExpectOne('/test-1?foo=1', 'foo');
// But this one will
makeRequestAndExpectNone('/test-1?foo=1');
});
it('should not cache a POST even with filter true specified', () => {
makeRequestAndExpectOne('/test-1?foo=1', 'post-body', {method: 'POST'});
// Previous POST request wasn't cached
makeRequestAndExpectOne('/test-1?foo=1', 'body2', {method: 'POST'});
// filter => true won't cache neither
makeRequestAndExpectOne('/test-1?foo=1', 'post-body', {method: 'POST', transferCache: true});
const response = makeRequestAndExpectOne('/test-1?foo=1', 'body2', {method: 'POST'});
expect(response).toBe('body2');
});
it('should not cache headers', async () => {
// HttpTransferCacheOptions: true = fallback to default = headers won't be cached
makeRequestAndExpectOne('/test-1?foo=1', 'foo', {
headers: {foo: 'foo', bar: 'bar'},
transferCache: true,
});
// request returns the cache without any header.
const response2 = makeRequestAndExpectNone('/test-1?foo=1');
expect(response2.headers.keys().length).toBe(0);
});
it('should cache with headers', async () => {
// headers are case not sensitive
makeRequestAndExpectOne('/test-1?foo=1', 'foo', {
headers: {foo: 'foo', bar: 'bar', 'BAZ': 'baz'},
transferCache: {includeHeaders: ['foo', 'baz']},
});
const consoleWarnSpy = spyOn(console, 'warn');
// request returns the cache with only 2 header entries.
const response = makeRequestAndExpectNone('/test-1?foo=1', 'GET', {
transferCache: {includeHeaders: ['foo', 'baz']},
});
expect(response.headers.keys().length).toBe(2);
// foo has been kept
const foo = response.headers.get('foo');
expect(foo).toBe('foo');
// foo wasn't removed, we won't log anything
expect(consoleWarnSpy.calls.count()).toBe(0);
// bar has been removed
response.headers.get('bar');
response.headers.get('some-other-header');
expect(consoleWarnSpy.calls.count()).toBe(2);
response.headers.get('some-other-header');
// We ensure the warning is only logged once per header method + entry
expect(consoleWarnSpy.calls.count()).toBe(2);
response.headers.has('some-other-header');
// Here the method is different, we get one more call.
expect(consoleWarnSpy.calls.count()).toBe(3);
});
it('should not cache POST by default', () => {
makeRequestAndExpectOne('/test-1?foo=1', 'foo', {method: 'POST'});
makeRequestAndExpectOne('/test-1?foo=1', 'foo', {method: 'POST'});
});
// TODO: Investigate why this test is flaky
it('should cache POST with the transferCache option', () => {
makeRequestAndExpectOne('/test-1?foo=1', 'foo', {method: 'POST', transferCache: true});
makeRequestAndExpectNone('/test-1?foo=1', 'POST', {transferCache: true});
makeRequestAndExpectOne('/test-2?foo=1', 'foo', {
method: 'POST',
transferCache: {includeHeaders: []},
});
makeRequestAndExpectNone('/test-2?foo=1', 'POST', {transferCache: true});
});
it('should not cache request that requires authorization by default', async () => {
makeRequestAndExpectOne('/test-auth', 'foo', {
headers: {Authorization: 'Basic YWxhZGRpbjpvcGVuc2VzYW1l'},
});
makeRequestAndExpectOne('/test-auth', 'foo');
}); | {
"end_byte": 9643,
"start_byte": 1469,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/transfer_cache_spec.ts"
} |
angular/packages/common/http/test/transfer_cache_spec.ts_9649_16352 | it('should not cache request that requires proxy authorization by default', async () => {
makeRequestAndExpectOne('/test-auth', 'foo', {
headers: {'Proxy-Authorization': 'Basic YWxhZGRpbjpvcGVuc2VzYW1l'},
});
makeRequestAndExpectOne('/test-auth', 'foo');
});
it('should cache POST with the differing body in string form', () => {
makeRequestAndExpectOne('/test-1', null, {method: 'POST', transferCache: true, body: 'foo'});
makeRequestAndExpectNone('/test-1', 'POST', {transferCache: true, body: 'foo'});
makeRequestAndExpectOne('/test-1', null, {method: 'POST', transferCache: true, body: 'bar'});
});
it('should cache POST with the differing body in object form', () => {
makeRequestAndExpectOne('/test-1', null, {
method: 'POST',
transferCache: true,
body: {foo: true},
});
makeRequestAndExpectNone('/test-1', 'POST', {transferCache: true, body: {foo: true}});
makeRequestAndExpectOne('/test-1', null, {
method: 'POST',
transferCache: true,
body: {foo: false},
});
});
it('should cache POST with the differing body in URLSearchParams form', () => {
makeRequestAndExpectOne('/test-1', null, {
method: 'POST',
transferCache: true,
body: new URLSearchParams('foo=1'),
});
makeRequestAndExpectNone('/test-1', 'POST', {
transferCache: true,
body: new URLSearchParams('foo=1'),
});
makeRequestAndExpectOne('/test-1', null, {
method: 'POST',
transferCache: true,
body: new URLSearchParams('foo=2'),
});
});
describe('caching in browser context', () => {
beforeEach(
withBody('<test-app-http></test-app-http>', () => {
TestBed.resetTestingModule();
isStable = new BehaviorSubject<boolean>(false);
@Injectable()
class ApplicationRefPatched extends ApplicationRef {
override isStable = new BehaviorSubject<boolean>(false);
}
TestBed.configureTestingModule({
declarations: [SomeComponent],
providers: [
{provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID},
{provide: DOCUMENT, useFactory: () => document},
{provide: ApplicationRef, useClass: ApplicationRefPatched},
withHttpTransferCache({}),
provideHttpClient(),
provideHttpClientTesting(),
],
});
const appRef = TestBed.inject(ApplicationRef);
appRef.bootstrap(SomeComponent);
isStable = appRef.isStable as BehaviorSubject<boolean>;
}),
);
it('should skip storing in transfer cache when platform is browser', () => {
makeRequestAndExpectOne('/test-1?foo=1', 'foo');
makeRequestAndExpectOne('/test-1?foo=1', 'foo');
});
});
describe('caching with global setting', () => {
beforeEach(
withBody('<test-app-http></test-app-http>', () => {
TestBed.resetTestingModule();
isStable = new BehaviorSubject<boolean>(false);
@Injectable()
class ApplicationRefPatched extends ApplicationRef {
override isStable = new BehaviorSubject<boolean>(false);
}
TestBed.configureTestingModule({
declarations: [SomeComponent],
providers: [
{provide: PLATFORM_ID, useValue: PLATFORM_SERVER_ID},
{provide: DOCUMENT, useFactory: () => document},
{provide: ApplicationRef, useClass: ApplicationRefPatched},
withHttpTransferCache({
filter: (req) => {
if (req.url.includes('include')) {
return true;
} else if (req.url.includes('exclude')) {
return false;
} else {
return true;
}
},
includeHeaders: ['foo', 'bar'],
includePostRequests: true,
includeRequestsWithAuthHeaders: true,
}),
provideHttpClient(),
provideHttpClientTesting(),
],
});
const appRef = TestBed.inject(ApplicationRef);
appRef.bootstrap(SomeComponent);
isStable = appRef.isStable as BehaviorSubject<boolean>;
}),
);
it('should cache because of global filter', () => {
makeRequestAndExpectOne('/include?foo=1', 'foo');
makeRequestAndExpectNone('/include?foo=1');
});
it('should not cache because of global filter', () => {
makeRequestAndExpectOne('/exclude?foo=1', 'foo');
makeRequestAndExpectOne('/exclude?foo=1', 'foo');
});
it(`should cache request that requires authorization when 'includeRequestsWithAuthHeaders' is 'true'`, async () => {
makeRequestAndExpectOne('/test-auth', 'foo', {
headers: {Authorization: 'Basic YWxhZGRpbjpvcGVuc2VzYW1l'},
});
makeRequestAndExpectNone('/test-auth');
});
it(`should cache request that requires proxy authorization when 'includeRequestsWithAuthHeaders' is 'true'`, async () => {
makeRequestAndExpectOne('/test-auth', 'foo', {
headers: {'Proxy-Authorization': 'Basic YWxhZGRpbjpvcGVuc2VzYW1l'},
});
makeRequestAndExpectNone('/test-auth');
});
it('should cache a POST request', () => {
makeRequestAndExpectOne('/include?foo=1', 'post-body', {method: 'POST'});
// Previous POST request wasn't cached
const response = makeRequestAndExpectNone('/include?foo=1', 'POST');
expect(response.body).toBe('post-body');
});
it('should cache with headers', () => {
// nothing specified, should use global options = callback => include + headers
makeRequestAndExpectOne('/include?foo=1', 'foo', {headers: {foo: 'foo', bar: 'bar'}});
// This one was cached with headers
const response = makeRequestAndExpectNone('/include?foo=1');
expect(response.headers.keys().length).toBe(2);
});
it('should cache without headers because overridden', () => {
// nothing specified, should use global options = callback => include + headers
makeRequestAndExpectOne('/include?foo=1', 'foo', {
headers: {foo: 'foo', bar: 'bar'},
transferCache: {includeHeaders: []},
});
// This one was cached with headers
const response = makeRequestAndExpectNone('/include?foo=1');
expect(response.headers.keys().length).toBe(0);
});
}); | {
"end_byte": 16352,
"start_byte": 9649,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/transfer_cache_spec.ts"
} |
angular/packages/common/http/test/transfer_cache_spec.ts_16358_23415 | describe('caching with public origins', () => {
beforeEach(
withBody('<test-app-http></test-app-http>', () => {
TestBed.resetTestingModule();
isStable = new BehaviorSubject<boolean>(false);
@Injectable()
class ApplicationRefPatched extends ApplicationRef {
override isStable = new BehaviorSubject<boolean>(false);
}
TestBed.configureTestingModule({
declarations: [SomeComponent],
providers: [
{provide: PLATFORM_ID, useValue: PLATFORM_SERVER_ID},
{provide: DOCUMENT, useFactory: () => document},
{provide: ApplicationRef, useClass: ApplicationRefPatched},
withHttpTransferCache({}),
provideHttpClient(),
provideHttpClientTesting(),
{
provide: HTTP_TRANSFER_CACHE_ORIGIN_MAP,
useValue: {
'http://internal-domain.com:1234': 'https://external-domain.net:443',
},
},
],
});
const appRef = TestBed.inject(ApplicationRef);
appRef.bootstrap(SomeComponent);
isStable = appRef.isStable as BehaviorSubject<boolean>;
}),
);
it('should cache with public origin', () => {
makeRequestAndExpectOne('http://internal-domain.com:1234/test-1?foo=1', 'foo');
const cachedRequest = makeRequestAndExpectNone(
'https://external-domain.net:443/test-1?foo=1',
);
expect(cachedRequest.url).toBe('https://external-domain.net:443/test-1?foo=1');
});
it('should cache normally when there is no mapping defined for the origin', () => {
makeRequestAndExpectOne('https://other.internal-domain.com:1234/test-1?foo=1', 'foo');
makeRequestAndExpectNone('https://other.internal-domain.com:1234/test-1?foo=1');
});
describe('when the origin map is configured with extra paths', () => {
beforeEach(
withBody('<test-app-http></test-app-http>', () => {
TestBed.resetTestingModule();
isStable = new BehaviorSubject<boolean>(false);
@Injectable()
class ApplicationRefPatched extends ApplicationRef {
override isStable = new BehaviorSubject<boolean>(false);
}
TestBed.configureTestingModule({
declarations: [SomeComponent],
providers: [
{provide: PLATFORM_ID, useValue: PLATFORM_SERVER_ID},
{provide: DOCUMENT, useFactory: () => document},
{provide: ApplicationRef, useClass: ApplicationRefPatched},
withHttpTransferCache({}),
provideHttpClient(),
provideHttpClientTesting(),
{
provide: HTTP_TRANSFER_CACHE_ORIGIN_MAP,
useValue: {
'http://internal-domain.com:1234': 'https://external-domain.net:443/path',
},
},
],
});
const appRef = TestBed.inject(ApplicationRef);
appRef.bootstrap(SomeComponent);
isStable = appRef.isStable as BehaviorSubject<boolean>;
}),
);
it('should throw an error when the origin map is configured with extra paths', () => {
TestBed.inject(HttpClient)
.request('GET', 'http://internal-domain.com:1234/path/test-1')
.subscribe({
error: (error: Error) => {
expect(error.message).toBe(
'NG02804: Angular detected a URL with a path segment in the value provided for the ' +
'`HTTP_TRANSFER_CACHE_ORIGIN_MAP` token: https://external-domain.net:443/path. ' +
'The map should only contain origins without any other segments.',
);
},
});
});
});
describe('on the client', () => {
beforeEach(
withBody('<test-app-http></test-app-http>', () => {
TestBed.resetTestingModule();
isStable = new BehaviorSubject<boolean>(false);
@Injectable()
class ApplicationRefPatched extends ApplicationRef {
override isStable = new BehaviorSubject<boolean>(false);
}
TestBed.configureTestingModule({
declarations: [SomeComponent],
providers: [
{provide: DOCUMENT, useFactory: () => document},
{provide: ApplicationRef, useClass: ApplicationRefPatched},
withHttpTransferCache({}),
provideHttpClient(),
provideHttpClientTesting(),
{
provide: HTTP_TRANSFER_CACHE_ORIGIN_MAP,
useValue: {
'http://internal-domain.com:1234': 'https://external-domain.net:443',
},
},
{provide: PLATFORM_ID, useValue: PLATFORM_SERVER_ID},
],
});
// Make a request on the server to fill the transfer state then reuse it in the browser
makeRequestAndExpectOne('http://internal-domain.com:1234/test-1?foo=1', 'foo');
const transferState = TestBed.inject(TransferState);
TestBed.resetTestingModule();
TestBed.configureTestingModule({
declarations: [SomeComponent],
providers: [
{provide: DOCUMENT, useFactory: () => document},
{provide: ApplicationRef, useClass: ApplicationRefPatched},
withHttpTransferCache({}),
provideHttpClient(),
provideHttpClientTesting(),
{
provide: HTTP_TRANSFER_CACHE_ORIGIN_MAP,
useValue: {
'http://internal-domain.com:1234': 'https://external-domain.net:443',
},
},
{provide: TransferState, useValue: transferState},
{provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID},
],
});
const appRef = TestBed.inject(ApplicationRef);
appRef.bootstrap(SomeComponent);
isStable = appRef.isStable as BehaviorSubject<boolean>;
}),
);
it('should throw an error when origin mapping is defined', () => {
TestBed.inject(HttpClient)
.request('GET', 'https://external-domain.net:443/test-1?foo=1')
.subscribe({
error: (error: Error) => {
expect(error.message).toBe(
'NG02803: Angular detected that the `HTTP_TRANSFER_CACHE_ORIGIN_MAP` token is configured and ' +
'present in the client side code. Please ensure that this token is only provided in the ' +
'server code of the application.',
);
},
});
});
});
});
});
}); | {
"end_byte": 23415,
"start_byte": 16358,
"url": "https://github.com/angular/angular/blob/main/packages/common/http/test/transfer_cache_spec.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.