_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/forms/src/model/form_control.ts_0_5585 | /**
* @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 {ɵWritable as Writable} from '@angular/core';
import {AsyncValidatorFn, ValidatorFn} from '../directives/validators';
import {removeListItem} from '../util';
import {
AbstractControl,
AbstractControlOptions,
isOptionsObj,
pickAsyncValidators,
pickValidators,
} from './abstract_model';
/**
* FormControlState is a boxed form value. It is an object with a `value` key and a `disabled` key.
*
* @publicApi
*/
export interface FormControlState<T> {
value: T;
disabled: boolean;
}
/**
* Interface for options provided to a `FormControl`.
*
* This interface extends all options from {@link AbstractControlOptions}, plus some options
* unique to `FormControl`.
*
* @publicApi
*/
export interface FormControlOptions extends AbstractControlOptions {
/**
* @description
* Whether to use the initial value used to construct the `FormControl` as its default value
* as well. If this option is false or not provided, the default value of a FormControl is `null`.
* When a FormControl is reset without an explicit value, its value reverts to
* its default value.
*/
nonNullable?: boolean;
/**
* @deprecated Use `nonNullable` instead.
*/
initialValueIsDefault?: boolean;
}
/**
* Tracks the value and validation status of an individual form control.
*
* This is one of the four fundamental building blocks of Angular forms, along with
* `FormGroup`, `FormArray` and `FormRecord`. It extends the `AbstractControl` class that
* implements most of the base functionality for accessing the value, validation status,
* user interactions and events.
*
* `FormControl` takes a single generic argument, which describes the type of its value. This
* argument always implicitly includes `null` because the control can be reset. To change this
* behavior, set `nonNullable` or see the usage notes below.
*
* See [usage examples below](#usage-notes).
*
* @see {@link AbstractControl}
* @see [Reactive Forms Guide](guide/forms/reactive-forms)
* @see [Usage Notes](#usage-notes)
*
* @publicApi
*
* @overriddenImplementation ɵFormControlCtor
*
* @usageNotes
*
* ### Initializing Form Controls
*
* Instantiate a `FormControl`, with an initial value.
*
* ```ts
* const control = new FormControl('some value');
* console.log(control.value); // 'some value'
* ```
*
* The following example initializes the control with a form state object. The `value`
* and `disabled` keys are required in this case.
*
* ```ts
* const control = new FormControl({ value: 'n/a', disabled: true });
* console.log(control.value); // 'n/a'
* console.log(control.status); // 'DISABLED'
* ```
*
* The following example initializes the control with a synchronous validator.
*
* ```ts
* const control = new FormControl('', Validators.required);
* console.log(control.value); // ''
* console.log(control.status); // 'INVALID'
* ```
*
* The following example initializes the control using an options object.
*
* ```ts
* const control = new FormControl('', {
* validators: Validators.required,
* asyncValidators: myAsyncValidator
* });
* ```
*
* ### The single type argument
*
* `FormControl` accepts a generic argument, which describes the type of its value.
* In most cases, this argument will be inferred.
*
* If you are initializing the control to `null`, or you otherwise wish to provide a
* wider type, you may specify the argument explicitly:
*
* ```
* let fc = new FormControl<string|null>(null);
* fc.setValue('foo');
* ```
*
* You might notice that `null` is always added to the type of the control.
* This is because the control will become `null` if you call `reset`. You can change
* this behavior by setting `{nonNullable: true}`.
*
* ### Configure the control to update on a blur event
*
* Set the `updateOn` option to `'blur'` to update on the blur `event`.
*
* ```ts
* const control = new FormControl('', { updateOn: 'blur' });
* ```
*
* ### Configure the control to update on a submit event
*
* Set the `updateOn` option to `'submit'` to update on a submit `event`.
*
* ```ts
* const control = new FormControl('', { updateOn: 'submit' });
* ```
*
* ### Reset the control back to a specific value
*
* You reset to a specific form state by passing through a standalone
* value or a form state object that contains both a value and a disabled state
* (these are the only two properties that cannot be calculated).
*
* ```ts
* const control = new FormControl('Nancy');
*
* console.log(control.value); // 'Nancy'
*
* control.reset('Drew');
*
* console.log(control.value); // 'Drew'
* ```
*
* ### Reset the control to its initial value
*
* If you wish to always reset the control to its initial value (instead of null),
* you can pass the `nonNullable` option:
*
* ```
* const control = new FormControl('Nancy', {nonNullable: true});
*
* console.log(control.value); // 'Nancy'
*
* control.reset();
*
* console.log(control.value); // 'Nancy'
* ```
*
* ### Reset the control back to an initial value and disabled
*
* ```
* const control = new FormControl('Nancy');
*
* console.log(control.value); // 'Nancy'
* console.log(control.status); // 'VALID'
*
* control.reset({ value: 'Drew', disabled: true });
*
* console.log(control.value); // 'Drew'
* console.log(control.status); // 'DISABLED'
* ```
*/
e | {
"end_byte": 5585,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/form_control.ts"
} |
angular/packages/forms/src/model/form_control.ts_5586_13109 | port interface FormControl<TValue = any> extends AbstractControl<TValue> {
/**
* The default value of this FormControl, used whenever the control is reset without an explicit
* value. See {@link FormControlOptions#nonNullable} for more information on configuring
* a default value.
*/
readonly defaultValue: TValue;
/** @internal */
_onChange: Function[];
/**
* This field holds a pending value that has not yet been applied to the form's value.
* @internal
*/
_pendingValue: TValue;
/** @internal */
_pendingChange: boolean;
/**
* Sets a new value for the form control.
*
* @param value The new value for the control.
* @param options Configuration options that determine how the control propagates changes
* and emits events when the value changes.
* The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
* updateValueAndValidity} method.
*
* * `onlySelf`: When true, each change only affects this control, and not its parent. Default is
* false.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control value is updated.
* When false, no events are emitted.
* * `emitModelToViewChange`: When true or not supplied (the default), each change triggers an
* `onChange` event to
* update the view.
* * `emitViewToModelChange`: When true or not supplied (the default), each change triggers an
* `ngModelChange`
* event to update the model.
*
*/
setValue(
value: TValue,
options?: {
onlySelf?: boolean;
emitEvent?: boolean;
emitModelToViewChange?: boolean;
emitViewToModelChange?: boolean;
},
): void;
/**
* Patches the value of a control.
*
* This function is functionally the same as {@link FormControl#setValue setValue} at this level.
* It exists for symmetry with {@link FormGroup#patchValue patchValue} on `FormGroups` and
* `FormArrays`, where it does behave differently.
*
* @see {@link FormControl#setValue} for options
*/
patchValue(
value: TValue,
options?: {
onlySelf?: boolean;
emitEvent?: boolean;
emitModelToViewChange?: boolean;
emitViewToModelChange?: boolean;
},
): void;
/**
* Resets the form control, marking it `pristine` and `untouched`, and resetting
* the value. The new value will be the provided value (if passed), `null`, or the initial value
* if `nonNullable` was set in the constructor via {@link FormControlOptions}.
*
* ```ts
* // By default, the control will reset to null.
* const dog = new FormControl('spot');
* dog.reset(); // dog.value is null
*
* // If this flag is set, the control will instead reset to the initial value.
* const cat = new FormControl('tabby', {nonNullable: true});
* cat.reset(); // cat.value is "tabby"
*
* // A value passed to reset always takes precedence.
* const fish = new FormControl('finn', {nonNullable: true});
* fish.reset('bubble'); // fish.value is "bubble"
* ```
*
* @param formState Resets the control with an initial value,
* or an object that defines the initial value and disabled state.
*
* @param options Configuration options that determine how the control propagates changes
* and emits events after the value changes.
*
* * `onlySelf`: When true, each change only affects this control, and not its parent. Default is
* false.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control is reset.
* When false, no events are emitted.
*
*/
reset(
formState?: TValue | FormControlState<TValue>,
options?: {
onlySelf?: boolean;
emitEvent?: boolean;
},
): void;
/**
* For a simple FormControl, the raw value is equivalent to the value.
*/
getRawValue(): TValue;
/**
* @internal
*/
_updateValue(): void;
/**
* @internal
*/
_anyControls(condition: (c: AbstractControl) => boolean): boolean;
/**
* @internal
*/
_allControlsDisabled(): boolean;
/**
* Register a listener for change events.
*
* @param fn The method that is called when the value changes
*/
registerOnChange(fn: Function): void;
/**
* Internal function to unregister a change events listener.
* @internal
*/
_unregisterOnChange(fn: (value?: any, emitModelEvent?: boolean) => void): void;
/**
* Register a listener for disabled events.
*
* @param fn The method that is called when the disabled status changes.
*/
registerOnDisabledChange(fn: (isDisabled: boolean) => void): void;
/**
* Internal function to unregister a disabled event listener.
* @internal
*/
_unregisterOnDisabledChange(fn: (isDisabled: boolean) => void): void;
/**
* @internal
*/
_forEachChild(cb: (c: AbstractControl) => void): void;
/** @internal */
_syncPendingControls(): boolean;
}
// This internal interface is present to avoid a naming clash, resulting in the wrong `FormControl`
// symbol being used.
type FormControlInterface<TValue = any> = FormControl<TValue>;
/**
* Various available constructors for `FormControl`.
* Do not use this interface directly. Instead, use `FormControl`:
* ```
* const fc = new FormControl('foo');
* ```
* This symbol is prefixed with ɵ to make plain that it is an internal symbol.
*/
export interface ɵFormControlCtor {
/**
* Construct a FormControl with no initial value or validators.
*/
new (): FormControl<any>;
/**
* Creates a new `FormControl` instance.
*
* @param formState Initializes the control with an initial value,
* or an object that defines the initial value and disabled state.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or a `FormControlOptions` object that contains validation functions
* and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator functions
*/
new <T = any>(
value: FormControlState<T> | T,
opts: FormControlOptions & {nonNullable: true},
): FormControl<T>;
/**
* @deprecated Use `nonNullable` instead.
*/
new <T = any>(
value: FormControlState<T> | T,
opts: FormControlOptions & {
initialValueIsDefault: true;
},
): FormControl<T>;
/**
* @deprecated When passing an `options` argument, the `asyncValidator` argument has no effect.
*/
new <T = any>(
value: FormControlState<T> | T,
opts: FormControlOptions,
asyncValidator: AsyncValidatorFn | AsyncValidatorFn[],
): FormControl<T | null>;
new <T = any>(
value: FormControlState<T> | T,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | FormControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
): FormControl<T | null>;
/**
* The presence of an explicit `prototype` property provides backwards-compatibility for apps that
* manually inspect the prototype chain.
*/
prototype: FormControl<any>;
}
function isFormControlState(formState: unknown): formState is FormControlState<unknown> {
return (
typeof formState === 'object' &&
formState !== null &&
Object.keys(formState).length === 2 &&
'value' in formState &&
'disabled' in formState
);
}
ex | {
"end_byte": 13109,
"start_byte": 5586,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/form_control.ts"
} |
angular/packages/forms/src/model/form_control.ts_13111_18394 | rt const FormControl: ɵFormControlCtor = class FormControl<TValue = any>
extends AbstractControl<TValue>
implements FormControlInterface<TValue>
{
/** @publicApi */
public readonly defaultValue: TValue = null as unknown as TValue;
/** @internal */
_onChange: Array<Function> = [];
/** @internal */
_pendingValue!: TValue;
/** @internal */
_pendingChange: boolean = false;
constructor(
// formState and defaultValue will only be null if T is nullable
formState: FormControlState<TValue> | TValue = null as unknown as TValue,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | FormControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
) {
super(pickValidators(validatorOrOpts), pickAsyncValidators(asyncValidator, validatorOrOpts));
this._applyFormState(formState);
this._setUpdateStrategy(validatorOrOpts);
this._initObservables();
this.updateValueAndValidity({
onlySelf: true,
// If `asyncValidator` is present, it will trigger control status change from `PENDING` to
// `VALID` or `INVALID`.
// The status should be broadcasted via the `statusChanges` observable, so we set
// `emitEvent` to `true` to allow that during the control creation process.
emitEvent: !!this.asyncValidator,
});
if (
isOptionsObj(validatorOrOpts) &&
(validatorOrOpts.nonNullable || validatorOrOpts.initialValueIsDefault)
) {
if (isFormControlState(formState)) {
this.defaultValue = formState.value;
} else {
this.defaultValue = formState;
}
}
}
override setValue(
value: TValue,
options: {
onlySelf?: boolean;
emitEvent?: boolean;
emitModelToViewChange?: boolean;
emitViewToModelChange?: boolean;
} = {},
): void {
(this as Writable<this>).value = this._pendingValue = value;
if (this._onChange.length && options.emitModelToViewChange !== false) {
this._onChange.forEach((changeFn) =>
changeFn(this.value, options.emitViewToModelChange !== false),
);
}
this.updateValueAndValidity(options);
}
override patchValue(
value: TValue,
options: {
onlySelf?: boolean;
emitEvent?: boolean;
emitModelToViewChange?: boolean;
emitViewToModelChange?: boolean;
} = {},
): void {
this.setValue(value, options);
}
override reset(
formState: TValue | FormControlState<TValue> = this.defaultValue,
options: {onlySelf?: boolean; emitEvent?: boolean} = {},
): void {
this._applyFormState(formState);
this.markAsPristine(options);
this.markAsUntouched(options);
this.setValue(this.value, options);
this._pendingChange = false;
}
/** @internal */
override _updateValue(): void {}
/** @internal */
override _anyControls(condition: (c: AbstractControl) => boolean): boolean {
return false;
}
/** @internal */
override _allControlsDisabled(): boolean {
return this.disabled;
}
registerOnChange(fn: Function): void {
this._onChange.push(fn);
}
/** @internal */
_unregisterOnChange(fn: (value?: any, emitModelEvent?: boolean) => void): void {
removeListItem(this._onChange, fn);
}
registerOnDisabledChange(fn: (isDisabled: boolean) => void): void {
this._onDisabledChange.push(fn);
}
/** @internal */
_unregisterOnDisabledChange(fn: (isDisabled: boolean) => void): void {
removeListItem(this._onDisabledChange, fn);
}
/** @internal */
override _forEachChild(cb: (c: AbstractControl) => void): void {}
/** @internal */
override _syncPendingControls(): boolean {
if (this.updateOn === 'submit') {
if (this._pendingDirty) this.markAsDirty();
if (this._pendingTouched) this.markAsTouched();
if (this._pendingChange) {
this.setValue(this._pendingValue, {onlySelf: true, emitModelToViewChange: false});
return true;
}
}
return false;
}
private _applyFormState(formState: FormControlState<TValue> | TValue) {
if (isFormControlState(formState)) {
(this as Writable<this>).value = this._pendingValue = formState.value;
formState.disabled
? this.disable({onlySelf: true, emitEvent: false})
: this.enable({onlySelf: true, emitEvent: false});
} else {
(this as Writable<this>).value = this._pendingValue = formState;
}
}
};
interface UntypedFormControlCtor {
new (): UntypedFormControl;
new (
formState?: any,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | FormControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
): UntypedFormControl;
/**
* The presence of an explicit `prototype` property provides backwards-compatibility for apps that
* manually inspect the prototype chain.
*/
prototype: FormControl<any>;
}
/**
* UntypedFormControl is a non-strongly-typed version of `FormControl`.
*/
export type UntypedFormControl = FormControl<any>;
export const UntypedFormControl: UntypedFormControlCtor = FormControl;
/**
* @description
* Asserts that the given control is an instance of `FormControl`
*
* @publicApi
*/
export const isFormControl = (control: unknown): control is FormControl =>
control instanceof FormControl;
| {
"end_byte": 18394,
"start_byte": 13111,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/form_control.ts"
} |
angular/packages/forms/src/model/form_group.ts_0_5740 | /**
* @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 {ɵWritable as Writable} from '@angular/core';
import {AsyncValidatorFn, ValidatorFn} from '../directives/validators';
import {
AbstractControl,
AbstractControlOptions,
assertAllValuesPresent,
assertControlPresent,
pickAsyncValidators,
pickValidators,
ɵRawValue,
ɵTypedOrUntyped,
ɵValue,
} from './abstract_model';
/**
* FormGroupValue extracts the type of `.value` from a FormGroup's inner object type. The untyped
* case falls back to {[key: string]: any}.
*
* Angular uses this type internally to support Typed Forms; do not use it directly.
*
* For internal use only.
*/
export type ɵFormGroupValue<T extends {[K in keyof T]?: AbstractControl<any>}> = ɵTypedOrUntyped<
T,
Partial<{[K in keyof T]: ɵValue<T[K]>}>,
{[key: string]: any}
>;
/**
* FormGroupRawValue extracts the type of `.getRawValue()` from a FormGroup's inner object type. The
* untyped case falls back to {[key: string]: any}.
*
* Angular uses this type internally to support Typed Forms; do not use it directly.
*
* For internal use only.
*/
export type ɵFormGroupRawValue<T extends {[K in keyof T]?: AbstractControl<any>}> = ɵTypedOrUntyped<
T,
{[K in keyof T]: ɵRawValue<T[K]>},
{[key: string]: any}
>;
/**
* OptionalKeys returns the union of all optional keys in the object.
*
* Angular uses this type internally to support Typed Forms; do not use it directly.
*/
export type ɵOptionalKeys<T> = {
[K in keyof T]-?: undefined extends T[K] ? K : never;
}[keyof T];
/**
* Tracks the value and validity state of a group of `FormControl` instances.
*
* A `FormGroup` aggregates the values of each child `FormControl` into one object,
* with each control name as the key. It calculates its status by reducing the status values
* of its children. For example, if one of the controls in a group is invalid, the entire
* group becomes invalid.
*
* `FormGroup` is one of the four fundamental building blocks used to define forms in Angular,
* along with `FormControl`, `FormArray`, and `FormRecord`.
*
* When instantiating a `FormGroup`, pass in a collection of child controls as the first
* argument. The key for each child registers the name for the control.
*
* `FormGroup` is intended for use cases where the keys are known ahead of time.
* If you need to dynamically add and remove controls, use {@link FormRecord} instead.
*
* `FormGroup` accepts an optional type parameter `TControl`, which is an object type with inner
* control types as values.
*
* @usageNotes
*
* ### Create a form group with 2 controls
*
* ```
* const form = new FormGroup({
* first: new FormControl('Nancy', Validators.minLength(2)),
* last: new FormControl('Drew'),
* });
*
* console.log(form.value); // {first: 'Nancy', last; 'Drew'}
* console.log(form.status); // 'VALID'
* ```
*
* ### The type argument, and optional controls
*
* `FormGroup` accepts one generic argument, which is an object containing its inner controls.
* This type will usually be inferred automatically, but you can always specify it explicitly if you
* wish.
*
* If you have controls that are optional (i.e. they can be removed, you can use the `?` in the
* type):
*
* ```
* const form = new FormGroup<{
* first: FormControl<string|null>,
* middle?: FormControl<string|null>, // Middle name is optional.
* last: FormControl<string|null>,
* }>({
* first: new FormControl('Nancy'),
* last: new FormControl('Drew'),
* });
* ```
*
* ### Create a form group with a group-level validator
*
* You include group-level validators as the second arg, or group-level async
* validators as the third arg. These come in handy when you want to perform validation
* that considers the value of more than one child control.
*
* ```
* const form = new FormGroup({
* password: new FormControl('', Validators.minLength(2)),
* passwordConfirm: new FormControl('', Validators.minLength(2)),
* }, passwordMatchValidator);
*
*
* function passwordMatchValidator(g: FormGroup) {
* return g.get('password').value === g.get('passwordConfirm').value
* ? null : {'mismatch': true};
* }
* ```
*
* Like `FormControl` instances, you choose to pass in
* validators and async validators as part of an options object.
*
* ```
* const form = new FormGroup({
* password: new FormControl('')
* passwordConfirm: new FormControl('')
* }, { validators: passwordMatchValidator, asyncValidators: otherValidator });
* ```
*
* ### Set the updateOn property for all controls in a form group
*
* The options object is used to set a default value for each child
* control's `updateOn` property. If you set `updateOn` to `'blur'` at the
* group level, all child controls default to 'blur', unless the child
* has explicitly specified a different `updateOn` value.
*
* ```ts
* const c = new FormGroup({
* one: new FormControl()
* }, { updateOn: 'blur' });
* ```
*
* ### Using a FormGroup with optional controls
*
* It is possible to have optional controls in a FormGroup. An optional control can be removed later
* using `removeControl`, and can be omitted when calling `reset`. Optional controls must be
* declared optional in the group's type.
*
* ```ts
* const c = new FormGroup<{one?: FormControl<string>}>({
* one: new FormControl('')
* });
* ```
*
* Notice that `c.value.one` has type `string|null|undefined`. This is because calling `c.reset({})`
* without providing the optional key `one` will cause it to become `null`.
*
* @publicApi
*/
export cla | {
"end_byte": 5740,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/form_group.ts"
} |
angular/packages/forms/src/model/form_group.ts_5741_13534 | s FormGroup<
TControl extends {[K in keyof TControl]: AbstractControl<any>} = any,
> extends AbstractControl<
ɵTypedOrUntyped<TControl, ɵFormGroupValue<TControl>, any>,
ɵTypedOrUntyped<TControl, ɵFormGroupRawValue<TControl>, any>
> {
/**
* Creates a new `FormGroup` instance.
*
* @param controls A collection of child controls. The key for each child is the name
* under which it is registered.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or an `AbstractControlOptions` object that contains validation functions
* and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator functions
*
*/
constructor(
controls: TControl,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
) {
super(pickValidators(validatorOrOpts), pickAsyncValidators(asyncValidator, validatorOrOpts));
(typeof ngDevMode === 'undefined' || ngDevMode) && validateFormGroupControls(controls);
this.controls = controls;
this._initObservables();
this._setUpdateStrategy(validatorOrOpts);
this._setUpControls();
this.updateValueAndValidity({
onlySelf: true,
// If `asyncValidator` is present, it will trigger control status change from `PENDING` to
// `VALID` or `INVALID`. The status should be broadcasted via the `statusChanges` observable,
// so we set `emitEvent` to `true` to allow that during the control creation process.
emitEvent: !!this.asyncValidator,
});
}
public controls: ɵTypedOrUntyped<TControl, TControl, {[key: string]: AbstractControl<any>}>;
/**
* Registers a control with the group's list of controls. In a strongly-typed group, the control
* must be in the group's type (possibly as an optional key).
*
* This method does not update the value or validity of the control.
* Use {@link FormGroup#addControl addControl} instead.
*
* @param name The control name to register in the collection
* @param control Provides the control for the given name
*/
registerControl<K extends string & keyof TControl>(name: K, control: TControl[K]): TControl[K];
registerControl(
this: FormGroup<{[key: string]: AbstractControl<any>}>,
name: string,
control: AbstractControl<any>,
): AbstractControl<any>;
registerControl<K extends string & keyof TControl>(name: K, control: TControl[K]): TControl[K] {
if (this.controls[name]) return (this.controls as any)[name];
this.controls[name] = control;
control.setParent(this as FormGroup);
control._registerOnCollectionChange(this._onCollectionChange);
return control;
}
/**
* Add a control to this group. In a strongly-typed group, the control must be in the group's type
* (possibly as an optional key).
*
* If a control with a given name already exists, it would *not* be replaced with a new one.
* If you want to replace an existing control, use the {@link FormGroup#setControl setControl}
* method instead. This method also updates the value and validity of the control.
*
* @param name The control name to add to the collection
* @param control Provides the control for the given name
* @param options Specifies whether this FormGroup instance should emit events after a new
* control is added.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges` observables emit events with the latest status and value when the control is
* added. When false, no events are emitted.
*/
addControl(
this: FormGroup<{[key: string]: AbstractControl<any>}>,
name: string,
control: AbstractControl,
options?: {emitEvent?: boolean},
): void;
addControl<K extends string & keyof TControl>(
name: K,
control: Required<TControl>[K],
options?: {
emitEvent?: boolean;
},
): void;
addControl<K extends string & keyof TControl>(
name: K,
control: Required<TControl>[K],
options: {
emitEvent?: boolean;
} = {},
): void {
this.registerControl(name, control);
this.updateValueAndValidity({emitEvent: options.emitEvent});
this._onCollectionChange();
}
removeControl(
this: FormGroup<{[key: string]: AbstractControl<any>}>,
name: string,
options?: {
emitEvent?: boolean;
},
): void;
removeControl<S extends string>(
name: ɵOptionalKeys<TControl> & S,
options?: {
emitEvent?: boolean;
},
): void;
/**
* Remove a control from this group. In a strongly-typed group, required controls cannot be
* removed.
*
* This method also updates the value and validity of the control.
*
* @param name The control name to remove from the collection
* @param options Specifies whether this FormGroup instance should emit events after a
* control is removed.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges` observables emit events with the latest status and value when the control is
* removed. When false, no events are emitted.
*/
removeControl(name: string, options: {emitEvent?: boolean} = {}): void {
if ((this.controls as any)[name])
(this.controls as any)[name]._registerOnCollectionChange(() => {});
delete (this.controls as any)[name];
this.updateValueAndValidity({emitEvent: options.emitEvent});
this._onCollectionChange();
}
/**
* Replace an existing control. In a strongly-typed group, the control must be in the group's type
* (possibly as an optional key).
*
* If a control with a given name does not exist in this `FormGroup`, it will be added.
*
* @param name The control name to replace in the collection
* @param control Provides the control for the given name
* @param options Specifies whether this FormGroup instance should emit events after an
* existing control is replaced.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges` observables emit events with the latest status and value when the control is
* replaced with a new one. When false, no events are emitted.
*/
setControl<K extends string & keyof TControl>(
name: K,
control: TControl[K],
options?: {
emitEvent?: boolean;
},
): void;
setControl(
this: FormGroup<{[key: string]: AbstractControl<any>}>,
name: string,
control: AbstractControl,
options?: {emitEvent?: boolean},
): void;
setControl<K extends string & keyof TControl>(
name: K,
control: TControl[K],
options: {
emitEvent?: boolean;
} = {},
): void {
if (this.controls[name]) this.controls[name]._registerOnCollectionChange(() => {});
delete this.controls[name];
if (control) this.registerControl(name, control);
this.updateValueAndValidity({emitEvent: options.emitEvent});
this._onCollectionChange();
}
/**
* Check whether there is an enabled control with the given name in the group.
*
* Reports false for disabled controls. If you'd like to check for existence in the group
* only, use {@link AbstractControl#get get} instead.
*
* @param controlName The control name to check for existence in the collection
*
* @returns false for disabled controls, true otherwise.
*/
contains<K extends string>(controlName: K): boolean;
contains(this: FormGroup<{[key: string]: AbstractControl<any>}>, controlName: string): boolean;
contains<K extends string & keyof TControl>(controlName: K): boolean {
return this.controls.hasOwnProperty(controlName) && this.controls[controlName].enabled;
}
/**
* Sets | {
"end_byte": 13534,
"start_byte": 5741,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/form_group.ts"
} |
angular/packages/forms/src/model/form_group.ts_13538_21315 | value of the `FormGroup`. It accepts an object that matches
* the structure of the group, with control names as keys.
*
* @usageNotes
* ### Set the complete value for the form group
*
* ```
* const form = new FormGroup({
* first: new FormControl(),
* last: new FormControl()
* });
*
* console.log(form.value); // {first: null, last: null}
*
* form.setValue({first: 'Nancy', last: 'Drew'});
* console.log(form.value); // {first: 'Nancy', last: 'Drew'}
* ```
*
* @throws When strict checks fail, such as setting the value of a control
* that doesn't exist or if you exclude a value of a control that does exist.
*
* @param value The new value for the control that matches the structure of the group.
* @param options Configuration options that determine how the control propagates changes
* and emits events after the value changes.
* The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
* updateValueAndValidity} method.
*
* * `onlySelf`: When true, each change only affects this control, and not its parent. Default is
* false.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control value is updated.
* When false, no events are emitted.
*/
override setValue(
value: ɵFormGroupRawValue<TControl>,
options: {
onlySelf?: boolean;
emitEvent?: boolean;
} = {},
): void {
assertAllValuesPresent(this, true, value);
(Object.keys(value) as Array<keyof TControl>).forEach((name) => {
assertControlPresent(this, true, name as any);
(this.controls as any)[name].setValue((value as any)[name], {
onlySelf: true,
emitEvent: options.emitEvent,
});
});
this.updateValueAndValidity(options);
}
/**
* Patches the value of the `FormGroup`. It accepts an object with control
* names as keys, and does its best to match the values to the correct controls
* in the group.
*
* It accepts both super-sets and sub-sets of the group without throwing an error.
*
* @usageNotes
* ### Patch the value for a form group
*
* ```
* const form = new FormGroup({
* first: new FormControl(),
* last: new FormControl()
* });
* console.log(form.value); // {first: null, last: null}
*
* form.patchValue({first: 'Nancy'});
* console.log(form.value); // {first: 'Nancy', last: null}
* ```
*
* @param value The object that matches the structure of the group.
* @param options Configuration options that determine how the control propagates changes and
* emits events after the value is patched.
* * `onlySelf`: When true, each change only affects this control and not its parent. Default is
* true.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges` observables emit events with the latest status and value when the control value
* is updated. When false, no events are emitted. The configuration options are passed to
* the {@link AbstractControl#updateValueAndValidity updateValueAndValidity} method.
*/
override patchValue(
value: ɵFormGroupValue<TControl>,
options: {
onlySelf?: boolean;
emitEvent?: boolean;
} = {},
): void {
// Even though the `value` argument type doesn't allow `null` and `undefined` values, the
// `patchValue` can be called recursively and inner data structures might have these values, so
// we just ignore such cases when a field containing FormGroup instance receives `null` or
// `undefined` as a value.
if (value == null /* both `null` and `undefined` */) return;
(Object.keys(value) as Array<keyof TControl>).forEach((name) => {
// The compiler cannot see through the uninstantiated conditional type of `this.controls`, so
// `as any` is required.
const control = (this.controls as any)[name];
if (control) {
control.patchValue(
/* Guaranteed to be present, due to the outer forEach. */ value[
name as keyof ɵFormGroupValue<TControl>
]!,
{onlySelf: true, emitEvent: options.emitEvent},
);
}
});
this.updateValueAndValidity(options);
}
/**
* Resets the `FormGroup`, marks all descendants `pristine` and `untouched` and sets
* the value of all descendants to their default values, or null if no defaults were provided.
*
* You reset to a specific form state by passing in a map of states
* that matches the structure of your form, with control names as keys. The state
* is a standalone value or a form state object with both a value and a disabled
* status.
*
* @param value Resets the control with an initial value,
* or an object that defines the initial value and disabled state.
*
* @param options Configuration options that determine how the control propagates changes
* and emits events when the group is reset.
* * `onlySelf`: When true, each change only affects this control, and not its parent. Default is
* false.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control is reset.
* When false, no events are emitted.
* The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
* updateValueAndValidity} method.
*
* @usageNotes
*
* ### Reset the form group values
*
* ```ts
* const form = new FormGroup({
* first: new FormControl('first name'),
* last: new FormControl('last name')
* });
*
* console.log(form.value); // {first: 'first name', last: 'last name'}
*
* form.reset({ first: 'name', last: 'last name' });
*
* console.log(form.value); // {first: 'name', last: 'last name'}
* ```
*
* ### Reset the form group values and disabled status
*
* ```
* const form = new FormGroup({
* first: new FormControl('first name'),
* last: new FormControl('last name')
* });
*
* form.reset({
* first: {value: 'name', disabled: true},
* last: 'last'
* });
*
* console.log(form.value); // {last: 'last'}
* console.log(form.get('first').status); // 'DISABLED'
* ```
*/
override reset(
value: ɵTypedOrUntyped<
TControl,
ɵFormGroupValue<TControl>,
any
> = {} as unknown as ɵFormGroupValue<TControl>,
options: {onlySelf?: boolean; emitEvent?: boolean} = {},
): void {
this._forEachChild((control: AbstractControl, name) => {
control.reset(value ? (value as any)[name] : null, {
onlySelf: true,
emitEvent: options.emitEvent,
});
});
this._updatePristine(options, this);
this._updateTouched(options, this);
this.updateValueAndValidity(options);
}
/**
* The aggregate value of the `FormGroup`, including any disabled controls.
*
* Retrieves all values regardless of disabled status.
*/
override getRawValue(): ɵTypedOrUntyped<TControl, ɵFormGroupRawValue<TControl>, any> {
return this._reduceChildren({}, (acc, control, name) => {
(acc as any)[name] = (control as any).getRawValue();
return acc;
}) as any;
}
/** @internal */
override _syncPendingControls(): boolean {
let subtreeUpdated = this._reduceChildren(false, (updated: boolean, child) => {
return child._syncPendingControls() ? true : updated;
});
if (subtreeUpdated) this.updateValueAndValidity({onlySelf: true});
return subtreeUpdated;
}
/** @internal */
override _forEachChild | {
"end_byte": 21315,
"start_byte": 13538,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/form_group.ts"
} |
angular/packages/forms/src/model/form_group.ts_21318_28173 | : (v: any, k: any) => void): void {
Object.keys(this.controls).forEach((key) => {
// The list of controls can change (for ex. controls might be removed) while the loop
// is running (as a result of invoking Forms API in `valueChanges` subscription), so we
// have to null check before invoking the callback.
const control = (this.controls as any)[key];
control && cb(control, key);
});
}
/** @internal */
_setUpControls(): void {
this._forEachChild((control) => {
control.setParent(this);
control._registerOnCollectionChange(this._onCollectionChange);
});
}
/** @internal */
override _updateValue(): void {
(this as Writable<this>).value = this._reduceValue() as any;
}
/** @internal */
override _anyControls(condition: (c: AbstractControl) => boolean): boolean {
for (const [controlName, control] of Object.entries(this.controls)) {
if (this.contains(controlName as any) && condition(control as any)) {
return true;
}
}
return false;
}
/** @internal */
_reduceValue(): Partial<TControl> {
let acc: Partial<TControl> = {};
return this._reduceChildren(acc, (acc, control, name) => {
if (control.enabled || this.disabled) {
acc[name] = control.value;
}
return acc;
});
}
/** @internal */
_reduceChildren<T, K extends keyof TControl>(
initValue: T,
fn: (acc: T, control: TControl[K], name: K) => T,
): T {
let res = initValue;
this._forEachChild((control: TControl[K], name: K) => {
res = fn(res, control, name);
});
return res;
}
/** @internal */
override _allControlsDisabled(): boolean {
for (const controlName of Object.keys(this.controls) as Array<keyof TControl>) {
if ((this.controls as any)[controlName].enabled) {
return false;
}
}
return Object.keys(this.controls).length > 0 || this.disabled;
}
/** @internal */
override _find(name: string | number): AbstractControl | null {
return this.controls.hasOwnProperty(name as string)
? (this.controls as any)[name as keyof TControl]
: null;
}
}
/**
* Will validate that none of the controls has a key with a dot
* Throws other wise
*/
function validateFormGroupControls<TControl>(controls: {
[K in keyof TControl]: AbstractControl<any, any>;
}) {
const invalidKeys = Object.keys(controls).filter((key) => key.includes('.'));
if (invalidKeys.length > 0) {
// TODO: make this an error once there are no more uses in G3
console.warn(
`FormGroup keys cannot include \`.\`, please replace the keys for: ${invalidKeys.join(',')}.`,
);
}
}
interface UntypedFormGroupCtor {
new (
controls: {[key: string]: AbstractControl},
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
): UntypedFormGroup;
/**
* The presence of an explicit `prototype` property provides backwards-compatibility for apps that
* manually inspect the prototype chain.
*/
prototype: FormGroup<any>;
}
/**
* UntypedFormGroup is a non-strongly-typed version of `FormGroup`.
*/
export type UntypedFormGroup = FormGroup<any>;
export const UntypedFormGroup: UntypedFormGroupCtor = FormGroup;
/**
* @description
* Asserts that the given control is an instance of `FormGroup`
*
* @publicApi
*/
export const isFormGroup = (control: unknown): control is FormGroup => control instanceof FormGroup;
/**
* Tracks the value and validity state of a collection of `FormControl` instances, each of which has
* the same value type.
*
* `FormRecord` is very similar to {@link FormGroup}, except it can be used with a dynamic keys,
* with controls added and removed as needed.
*
* `FormRecord` accepts one generic argument, which describes the type of the controls it contains.
*
* @usageNotes
*
* ```
* let numbers = new FormRecord({bill: new FormControl('415-123-456')});
* numbers.addControl('bob', new FormControl('415-234-567'));
* numbers.removeControl('bill');
* ```
*
* @publicApi
*/
export class FormRecord<TControl extends AbstractControl = AbstractControl> extends FormGroup<{
[key: string]: TControl;
}> {}
export interface FormRecord<TControl> {
/**
* Registers a control with the records's list of controls.
*
* See `FormGroup#registerControl` for additional information.
*/
registerControl(name: string, control: TControl): TControl;
/**
* Add a control to this group.
*
* See `FormGroup#addControl` for additional information.
*/
addControl(name: string, control: TControl, options?: {emitEvent?: boolean}): void;
/**
* Remove a control from this group.
*
* See `FormGroup#removeControl` for additional information.
*/
removeControl(name: string, options?: {emitEvent?: boolean}): void;
/**
* Replace an existing control.
*
* See `FormGroup#setControl` for additional information.
*/
setControl(name: string, control: TControl, options?: {emitEvent?: boolean}): void;
/**
* Check whether there is an enabled control with the given name in the group.
*
* See `FormGroup#contains` for additional information.
*/
contains(controlName: string): boolean;
/**
* Sets the value of the `FormRecord`. It accepts an object that matches
* the structure of the group, with control names as keys.
*
* See `FormGroup#setValue` for additional information.
*/
setValue(
value: {[key: string]: ɵValue<TControl>},
options?: {
onlySelf?: boolean;
emitEvent?: boolean;
},
): void;
/**
* Patches the value of the `FormRecord`. It accepts an object with control
* names as keys, and does its best to match the values to the correct controls
* in the group.
*
* See `FormGroup#patchValue` for additional information.
*/
patchValue(
value: {[key: string]: ɵValue<TControl>},
options?: {
onlySelf?: boolean;
emitEvent?: boolean;
},
): void;
/**
* Resets the `FormRecord`, marks all descendants `pristine` and `untouched` and sets
* the value of all descendants to null.
*
* See `FormGroup#reset` for additional information.
*/
reset(
value?: {[key: string]: ɵValue<TControl>},
options?: {
onlySelf?: boolean;
emitEvent?: boolean;
},
): void;
/**
* The aggregate value of the `FormRecord`, including any disabled controls.
*
* See `FormGroup#getRawValue` for additional information.
*/
getRawValue(): {[key: string]: ɵRawValue<TControl>};
}
/**
* @description
* Asserts that the given control is an instance of `FormRecord`
*
* @publicApi
*/
export const isFormRecord = (control: unknown): control is FormRecord =>
control instanceof FormRecord;
| {
"end_byte": 28173,
"start_byte": 21318,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/form_group.ts"
} |
angular/packages/forms/src/model/abstract_model.ts_0_8149 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
EventEmitter,
signal,
ɵRuntimeError as RuntimeError,
ɵWritable as Writable,
untracked,
computed,
} from '@angular/core';
import {Observable, Subject} from 'rxjs';
import {
asyncValidatorsDroppedWithOptsWarning,
missingControlError,
missingControlValueError,
noControlsError,
} from '../directives/reactive_errors';
import type {AsyncValidatorFn, ValidationErrors, ValidatorFn} from '../directives/validators';
import {RuntimeErrorCode} from '../errors';
import {
addValidators,
composeAsyncValidators,
composeValidators,
hasValidator,
removeValidators,
toObservable,
} from '../validators';
import type {FormArray} from './form_array';
import type {FormGroup} from './form_group';
/**
* Reports that a control is valid, meaning that no errors exist in the input value.
*
* @see {@link status}
*/
export const VALID = 'VALID';
/**
* Reports that a control is invalid, meaning that an error exists in the input value.
*
* @see {@link status}
*/
export const INVALID = 'INVALID';
/**
* Reports that a control is pending, meaning that async validation is occurring and
* errors are not yet available for the input value.
*
* @see {@link markAsPending}
* @see {@link status}
*/
export const PENDING = 'PENDING';
/**
* Reports that a control is disabled, meaning that the control is exempt from ancestor
* calculations of validity or value.
*
* @see {@link markAsDisabled}
* @see {@link status}
*/
export const DISABLED = 'DISABLED';
/**
* A form can have several different statuses. Each
* possible status is returned as a string literal.
*
* * **VALID**: Reports that a control is valid, meaning that no errors exist in the input
* value.
* * **INVALID**: Reports that a control is invalid, meaning that an error exists in the input
* value.
* * **PENDING**: Reports that a control is pending, meaning that async validation is
* occurring and errors are not yet available for the input value.
* * **DISABLED**: Reports that a control is
* disabled, meaning that the control is exempt from ancestor calculations of validity or value.
*
* @publicApi
*/
export type FormControlStatus = 'VALID' | 'INVALID' | 'PENDING' | 'DISABLED';
/**
* Base class for every event sent by `AbstractControl.events()`
*
* @publicApi
*/
export abstract class ControlEvent<T = any> {
/**
* Form control from which this event is originated.
*
* Note: the type of the control can't be infered from T as the event can be emitted by any of child controls
*/
public abstract readonly source: AbstractControl<unknown>;
}
/**
* Event fired when the value of a control changes.
*
* @publicApi
*/
export class ValueChangeEvent<T> extends ControlEvent<T> {
constructor(
public readonly value: T,
public readonly source: AbstractControl,
) {
super();
}
}
/**
* Event fired when the control's pristine state changes (pristine <=> dirty).
*
* @publicApi */
export class PristineChangeEvent extends ControlEvent {
constructor(
public readonly pristine: boolean,
public readonly source: AbstractControl,
) {
super();
}
}
/**
* Event fired when the control's touched status changes (touched <=> untouched).
*
* @publicApi
*/
export class TouchedChangeEvent extends ControlEvent {
constructor(
public readonly touched: boolean,
public readonly source: AbstractControl,
) {
super();
}
}
/**
* Event fired when the control's status changes.
*
* @publicApi
*/
export class StatusChangeEvent extends ControlEvent {
constructor(
public readonly status: FormControlStatus,
public readonly source: AbstractControl,
) {
super();
}
}
/**
* Event fired when a form is submitted
*
* @publicApi
*/
export class FormSubmittedEvent extends ControlEvent {
constructor(public readonly source: AbstractControl) {
super();
}
}
/**
* Event fired when a form is reset.
*
* @publicApi
*/
export class FormResetEvent extends ControlEvent {
constructor(public readonly source: AbstractControl) {
super();
}
}
/**
* Gets validators from either an options object or given validators.
*/
export function pickValidators(
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
): ValidatorFn | ValidatorFn[] | null {
return (isOptionsObj(validatorOrOpts) ? validatorOrOpts.validators : validatorOrOpts) || null;
}
/**
* Creates validator function by combining provided validators.
*/
function coerceToValidator(validator: ValidatorFn | ValidatorFn[] | null): ValidatorFn | null {
return Array.isArray(validator) ? composeValidators(validator) : validator || null;
}
/**
* Gets async validators from either an options object or given validators.
*/
export function pickAsyncValidators(
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
): AsyncValidatorFn | AsyncValidatorFn[] | null {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (isOptionsObj(validatorOrOpts) && asyncValidator) {
console.warn(asyncValidatorsDroppedWithOptsWarning);
}
}
return (isOptionsObj(validatorOrOpts) ? validatorOrOpts.asyncValidators : asyncValidator) || null;
}
/**
* Creates async validator function by combining provided async validators.
*/
function coerceToAsyncValidator(
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
): AsyncValidatorFn | null {
return Array.isArray(asyncValidator)
? composeAsyncValidators(asyncValidator)
: asyncValidator || null;
}
export type FormHooks = 'change' | 'blur' | 'submit';
/**
* Interface for options provided to an `AbstractControl`.
*
* @publicApi
*/
export interface AbstractControlOptions {
/**
* @description
* The list of validators applied to a control.
*/
validators?: ValidatorFn | ValidatorFn[] | null;
/**
* @description
* The list of async validators applied to control.
*/
asyncValidators?: AsyncValidatorFn | AsyncValidatorFn[] | null;
/**
* @description
* The event name for control to update upon.
*/
updateOn?: 'change' | 'blur' | 'submit';
}
export function isOptionsObj(
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
): validatorOrOpts is AbstractControlOptions {
return (
validatorOrOpts != null &&
!Array.isArray(validatorOrOpts) &&
typeof validatorOrOpts === 'object'
);
}
export function assertControlPresent(parent: any, isGroup: boolean, key: string | number): void {
const controls = parent.controls as {[key: string | number]: unknown};
const collection = isGroup ? Object.keys(controls) : controls;
if (!collection.length) {
throw new RuntimeError(
RuntimeErrorCode.NO_CONTROLS,
typeof ngDevMode === 'undefined' || ngDevMode ? noControlsError(isGroup) : '',
);
}
if (!controls[key]) {
throw new RuntimeError(
RuntimeErrorCode.MISSING_CONTROL,
typeof ngDevMode === 'undefined' || ngDevMode ? missingControlError(isGroup, key) : '',
);
}
}
export function assertAllValuesPresent(control: any, isGroup: boolean, value: any): void {
control._forEachChild((_: unknown, key: string | number) => {
if (value[key] === undefined) {
throw new RuntimeError(
RuntimeErrorCode.MISSING_CONTROL_VALUE,
typeof ngDevMode === 'undefined' || ngDevMode ? missingControlValueError(isGroup, key) : '',
);
}
});
}
// IsAny checks if T is `any`, by checking a condition that couldn't possibly be true otherwise.
export type ɵIsAny<T, Y, N> = 0 extends 1 & T ? Y : N;
/**
* `TypedOrUntyped` allows one of two different types to be selected, depending on whether the Forms
* class it's applied to is typed or not.
*
* This is for internal Angular usage to support typed forms; do not directly use it.
*/
export type ɵTypedOrUntyped<T, Typed, Untyped> = ɵIsAny<T, Untyped, Typed>;
/** | {
"end_byte": 8149,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/abstract_model.ts"
} |
angular/packages/forms/src/model/abstract_model.ts_8151_14025 | * Value gives the value type corresponding to a control type.
*
* Note that the resulting type will follow the same rules as `.value` on your control, group, or
* array, including `undefined` for each group element which might be disabled.
*
* If you are trying to extract a value type for a data model, you probably want {@link RawValue},
* which will not have `undefined` in group keys.
*
* @usageNotes
*
* ### `FormControl` value type
*
* You can extract the value type of a single control:
*
* ```ts
* type NameControl = FormControl<string>;
* type NameValue = Value<NameControl>;
* ```
*
* The resulting type is `string`.
*
* ### `FormGroup` value type
*
* Imagine you have an interface defining the controls in your group. You can extract the shape of
* the values as follows:
*
* ```ts
* interface PartyFormControls {
* address: FormControl<string>;
* }
*
* // Value operates on controls; the object must be wrapped in a FormGroup.
* type PartyFormValues = Value<FormGroup<PartyFormControls>>;
* ```
*
* The resulting type is `{address: string|undefined}`.
*
* ### `FormArray` value type
*
* You can extract values from FormArrays as well:
*
* ```ts
* type GuestNamesControls = FormArray<FormControl<string>>;
*
* type NamesValues = Value<GuestNamesControls>;
* ```
*
* The resulting type is `string[]`.
*
* **Internal: not for public use.**
*/
export type ɵValue<T extends AbstractControl | undefined> =
T extends AbstractControl<any, any> ? T['value'] : never;
/**
* RawValue gives the raw value type corresponding to a control type.
*
* Note that the resulting type will follow the same rules as `.getRawValue()` on your control,
* group, or array. This means that all controls inside a group will be required, not optional,
* regardless of their disabled state.
*
* You may also wish to use {@link ɵValue}, which will have `undefined` in group keys (which can be
* disabled).
*
* @usageNotes
*
* ### `FormGroup` raw value type
*
* Imagine you have an interface defining the controls in your group. You can extract the shape of
* the raw values as follows:
*
* ```ts
* interface PartyFormControls {
* address: FormControl<string>;
* }
*
* // RawValue operates on controls; the object must be wrapped in a FormGroup.
* type PartyFormValues = RawValue<FormGroup<PartyFormControls>>;
* ```
*
* The resulting type is `{address: string}`. (Note the absence of `undefined`.)
*
* **Internal: not for public use.**
*/
export type ɵRawValue<T extends AbstractControl | undefined> =
T extends AbstractControl<any, any>
? T['setValue'] extends (v: infer R) => void
? R
: never
: never;
/**
* Tokenize splits a string literal S by a delimiter D.
*/
export type ɵTokenize<S extends string, D extends string> = string extends S
? string[] /* S must be a literal */
: S extends `${infer T}${D}${infer U}`
? [T, ...ɵTokenize<U, D>]
: [S] /* Base case */;
/**
* CoerceStrArrToNumArr accepts an array of strings, and converts any numeric string to a number.
*/
export type ɵCoerceStrArrToNumArr<S> =
// Extract the head of the array.
S extends [infer Head, ...infer Tail]
? // Using a template literal type, coerce the head to `number` if possible.
// Then, recurse on the tail.
Head extends `${number}`
? [number, ...ɵCoerceStrArrToNumArr<Tail>]
: [Head, ...ɵCoerceStrArrToNumArr<Tail>]
: [];
/**
* Navigate takes a type T and an array K, and returns the type of T[K[0]][K[1]][K[2]]...
*/
export type ɵNavigate<
T,
K extends Array<string | number>,
> = T extends object /* T must be indexable (object or array) */
? K extends [infer Head, ...infer Tail] /* Split K into head and tail */
? Head extends keyof T /* head(K) must index T */
? Tail extends (string | number)[] /* tail(K) must be an array */
? [] extends Tail
? T[Head] /* base case: K can be split, but Tail is empty */
: ɵNavigate<T[Head], Tail> /* explore T[head(K)] by tail(K) */
: any /* tail(K) was not an array, give up */
: never /* head(K) does not index T, give up */
: any /* K cannot be split, give up */
: any /* T is not indexable, give up */;
/**
* ɵWriteable removes readonly from all keys.
*/
export type ɵWriteable<T> = {
-readonly [P in keyof T]: T[P];
};
/**
* GetProperty takes a type T and some property names or indices K.
* If K is a dot-separated string, it is tokenized into an array before proceeding.
* Then, the type of the nested property at K is computed: T[K[0]][K[1]][K[2]]...
* This works with both objects, which are indexed by property name, and arrays, which are indexed
* numerically.
*
* For internal use only.
*/
export type ɵGetProperty<T, K> =
// K is a string
K extends string
? ɵGetProperty<T, ɵCoerceStrArrToNumArr<ɵTokenize<K, '.'>>>
: // Is it an array
ɵWriteable<K> extends Array<string | number>
? ɵNavigate<T, ɵWriteable<K>>
: // Fall through permissively if we can't calculate the type of K.
any;
/**
* This is the base class for `FormControl`, `FormGroup`, and `FormArray`.
*
* It provides some of the shared behavior that all controls and groups of controls have, like
* running validators, calculating status, and resetting state. It also defines the properties
* that are shared between all sub-classes, like `value`, `valid`, and `dirty`. It shouldn't be
* instantiated directly.
*
* The first type parameter TValue represents the value type of the control (`control.value`).
* The optional type parameter TRawValue represents the raw value type (`control.getRawValue()`).
*
* @see [Forms Guide](guide/forms)
* @see [Reactive Forms Guide](guide/forms/reactive-forms)
* @see [Dynamic Forms Guide](guide/forms/dynamic-forms)
*
* @publicApi
*/
export abstract class A | {
"end_byte": 14025,
"start_byte": 8151,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/abstract_model.ts"
} |
angular/packages/forms/src/model/abstract_model.ts_14026_22055 | stractControl<TValue = any, TRawValue extends TValue = TValue> {
/** @internal */
_pendingDirty = false;
/**
* Indicates that a control has its own pending asynchronous validation in progress.
* It also stores if the control should emit events when the validation status changes.
*
* @internal
*/
_hasOwnPendingAsyncValidator: null | {emitEvent: boolean} = null;
/** @internal */
_pendingTouched = false;
/** @internal */
_onCollectionChange = () => {};
/** @internal */
_updateOn?: FormHooks;
private _parent: FormGroup | FormArray | null = null;
private _asyncValidationSubscription: any;
/**
* Contains the result of merging synchronous validators into a single validator function
* (combined using `Validators.compose`).
*
* @internal
*/
private _composedValidatorFn!: ValidatorFn | null;
/**
* Contains the result of merging asynchronous validators into a single validator function
* (combined using `Validators.composeAsync`).
*
* @internal
*/
private _composedAsyncValidatorFn!: AsyncValidatorFn | null;
/**
* Synchronous validators as they were provided:
* - in `AbstractControl` constructor
* - as an argument while calling `setValidators` function
* - while calling the setter on the `validator` field (e.g. `control.validator = validatorFn`)
*
* @internal
*/
private _rawValidators!: ValidatorFn | ValidatorFn[] | null;
/**
* Asynchronous validators as they were provided:
* - in `AbstractControl` constructor
* - as an argument while calling `setAsyncValidators` function
* - while calling the setter on the `asyncValidator` field (e.g. `control.asyncValidator =
* asyncValidatorFn`)
*
* @internal
*/
private _rawAsyncValidators!: AsyncValidatorFn | AsyncValidatorFn[] | null;
/**
* The current value of the control.
*
* * For a `FormControl`, the current value.
* * For an enabled `FormGroup`, the values of enabled controls as an object
* with a key-value pair for each member of the group.
* * For a disabled `FormGroup`, the values of all controls as an object
* with a key-value pair for each member of the group.
* * For a `FormArray`, the values of enabled controls as an array.
*
*/
public readonly value!: TValue;
/**
* Initialize the AbstractControl instance.
*
* @param validators The function or array of functions that is used to determine the validity of
* this control synchronously.
* @param asyncValidators The function or array of functions that is used to determine validity of
* this control asynchronously.
*/
constructor(
validators: ValidatorFn | ValidatorFn[] | null,
asyncValidators: AsyncValidatorFn | AsyncValidatorFn[] | null,
) {
this._assignValidators(validators);
this._assignAsyncValidators(asyncValidators);
}
/**
* Returns the function that is used to determine the validity of this control synchronously.
* If multiple validators have been added, this will be a single composed function.
* See `Validators.compose()` for additional information.
*/
get validator(): ValidatorFn | null {
return this._composedValidatorFn;
}
set validator(validatorFn: ValidatorFn | null) {
this._rawValidators = this._composedValidatorFn = validatorFn;
}
/**
* Returns the function that is used to determine the validity of this control asynchronously.
* If multiple validators have been added, this will be a single composed function.
* See `Validators.compose()` for additional information.
*/
get asyncValidator(): AsyncValidatorFn | null {
return this._composedAsyncValidatorFn;
}
set asyncValidator(asyncValidatorFn: AsyncValidatorFn | null) {
this._rawAsyncValidators = this._composedAsyncValidatorFn = asyncValidatorFn;
}
/**
* The parent control.
*/
get parent(): FormGroup | FormArray | null {
return this._parent;
}
/**
* The validation status of the control.
*
* @see {@link FormControlStatus}
*
* These status values are mutually exclusive, so a control cannot be
* both valid AND invalid or invalid AND disabled.
*/
get status(): FormControlStatus {
return untracked(this.statusReactive)!;
}
private set status(v: FormControlStatus) {
untracked(() => this.statusReactive.set(v));
}
/** @internal */
readonly _status = computed(() => this.statusReactive());
private readonly statusReactive = signal<FormControlStatus | undefined>(undefined);
/**
* A control is `valid` when its `status` is `VALID`.
*
* @see {@link AbstractControl.status}
*
* @returns True if the control has passed all of its validation tests,
* false otherwise.
*/
get valid(): boolean {
return this.status === VALID;
}
/**
* A control is `invalid` when its `status` is `INVALID`.
*
* @see {@link AbstractControl.status}
*
* @returns True if this control has failed one or more of its validation checks,
* false otherwise.
*/
get invalid(): boolean {
return this.status === INVALID;
}
/**
* A control is `pending` when its `status` is `PENDING`.
*
* @see {@link AbstractControl.status}
*
* @returns True if this control is in the process of conducting a validation check,
* false otherwise.
*/
get pending(): boolean {
return this.status == PENDING;
}
/**
* A control is `disabled` when its `status` is `DISABLED`.
*
* Disabled controls are exempt from validation checks and
* are not included in the aggregate value of their ancestor
* controls.
*
* @see {@link AbstractControl.status}
*
* @returns True if the control is disabled, false otherwise.
*/
get disabled(): boolean {
return this.status === DISABLED;
}
/**
* A control is `enabled` as long as its `status` is not `DISABLED`.
*
* @returns True if the control has any status other than 'DISABLED',
* false if the status is 'DISABLED'.
*
* @see {@link AbstractControl.status}
*
*/
get enabled(): boolean {
return this.status !== DISABLED;
}
/**
* An object containing any errors generated by failing validation,
* or null if there are no errors.
*/
public readonly errors!: ValidationErrors | null;
/**
* A control is `pristine` if the user has not yet changed
* the value in the UI.
*
* @returns True if the user has not yet changed the value in the UI; compare `dirty`.
* Programmatic changes to a control's value do not mark it dirty.
*/
get pristine(): boolean {
return untracked(this.pristineReactive);
}
private set pristine(v: boolean) {
untracked(() => this.pristineReactive.set(v));
}
/** @internal */
readonly _pristine = computed(() => this.pristineReactive());
private readonly pristineReactive = signal(true);
/**
* A control is `dirty` if the user has changed the value
* in the UI.
*
* @returns True if the user has changed the value of this control in the UI; compare `pristine`.
* Programmatic changes to a control's value do not mark it dirty.
*/
get dirty(): boolean {
return !this.pristine;
}
/**
* True if the control is marked as `touched`.
*
* A control is marked `touched` once the user has triggered
* a `blur` event on it.
*/
get touched(): boolean {
return untracked(this.touchedReactive);
}
private set touched(v: boolean) {
untracked(() => this.touchedReactive.set(v));
}
/** @internal */
readonly _touched = computed(() => this.touchedReactive());
private readonly touchedReactive = signal(false);
/**
* True if the control has not been marked as touched
*
* A control is `untouched` if the user has not yet triggered
* a `blur` event on it.
*/
get untouched(): boolean {
return !this.touched;
}
/**
* Exposed as observable, see below.
*
* @internal
*/
readonly _events = new Subject<ControlEvent<TValue>>();
/**
* A multicast | {
"end_byte": 22055,
"start_byte": 14026,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/abstract_model.ts"
} |
angular/packages/forms/src/model/abstract_model.ts_22059_30882 | observable that emits an event every time the state of the control changes.
* It emits for value, status, pristine or touched changes.
*
* **Note**: On value change, the emit happens right after a value of this control is updated. The
* value of a parent control (for example if this FormControl is a part of a FormGroup) is updated
* later, so accessing a value of a parent control (using the `value` property) from the callback
* of this event might result in getting a value that has not been updated yet. Subscribe to the
* `events` of the parent control instead.
* For other event types, the events are emitted after the parent control has been updated.
*
*/
public readonly events = this._events.asObservable();
/**
* A multicasting observable that emits an event every time the value of the control changes, in
* the UI or programmatically. It also emits an event each time you call enable() or disable()
* without passing along {emitEvent: false} as a function argument.
*
* **Note**: the emit happens right after a value of this control is updated. The value of a
* parent control (for example if this FormControl is a part of a FormGroup) is updated later, so
* accessing a value of a parent control (using the `value` property) from the callback of this
* event might result in getting a value that has not been updated yet. Subscribe to the
* `valueChanges` event of the parent control instead.
*
* TODO: this should be piped from events() but is breaking in G3
*/
public readonly valueChanges!: Observable<TValue>;
/**
* A multicasting observable that emits an event every time the validation `status` of the control
* recalculates.
*
* @see {@link FormControlStatus}
* @see {@link AbstractControl.status}
*
* TODO: this should be piped from events() but is breaking in G3
*/
public readonly statusChanges!: Observable<FormControlStatus>;
/**
* Reports the update strategy of the `AbstractControl` (meaning
* the event on which the control updates itself).
* Possible values: `'change'` | `'blur'` | `'submit'`
* Default value: `'change'`
*/
get updateOn(): FormHooks {
return this._updateOn ? this._updateOn : this.parent ? this.parent.updateOn : 'change';
}
/**
* Sets the synchronous validators that are active on this control. Calling
* this overwrites any existing synchronous validators.
*
* When you add or remove a validator at run time, you must call
* `updateValueAndValidity()` for the new validation to take effect.
*
* If you want to add a new validator without affecting existing ones, consider
* using `addValidators()` method instead.
*/
setValidators(validators: ValidatorFn | ValidatorFn[] | null): void {
this._assignValidators(validators);
}
/**
* Sets the asynchronous validators that are active on this control. Calling this
* overwrites any existing asynchronous validators.
*
* When you add or remove a validator at run time, you must call
* `updateValueAndValidity()` for the new validation to take effect.
*
* If you want to add a new validator without affecting existing ones, consider
* using `addAsyncValidators()` method instead.
*/
setAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[] | null): void {
this._assignAsyncValidators(validators);
}
/**
* Add a synchronous validator or validators to this control, without affecting other validators.
*
* When you add or remove a validator at run time, you must call
* `updateValueAndValidity()` for the new validation to take effect.
*
* Adding a validator that already exists will have no effect. If duplicate validator functions
* are present in the `validators` array, only the first instance would be added to a form
* control.
*
* @param validators The new validator function or functions to add to this control.
*/
addValidators(validators: ValidatorFn | ValidatorFn[]): void {
this.setValidators(addValidators(validators, this._rawValidators));
}
/**
* Add an asynchronous validator or validators to this control, without affecting other
* validators.
*
* When you add or remove a validator at run time, you must call
* `updateValueAndValidity()` for the new validation to take effect.
*
* Adding a validator that already exists will have no effect.
*
* @param validators The new asynchronous validator function or functions to add to this control.
*/
addAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void {
this.setAsyncValidators(addValidators(validators, this._rawAsyncValidators));
}
/**
* Remove a synchronous validator from this control, without affecting other validators.
* Validators are compared by function reference; you must pass a reference to the exact same
* validator function as the one that was originally set. If a provided validator is not found,
* it is ignored.
*
* @usageNotes
*
* ### Reference to a ValidatorFn
*
* ```
* // Reference to the RequiredValidator
* const ctrl = new FormControl<string | null>('', Validators.required);
* ctrl.removeValidators(Validators.required);
*
* // Reference to anonymous function inside MinValidator
* const minValidator = Validators.min(3);
* const ctrl = new FormControl<string | null>('', minValidator);
* expect(ctrl.hasValidator(minValidator)).toEqual(true)
* expect(ctrl.hasValidator(Validators.min(3))).toEqual(false)
*
* ctrl.removeValidators(minValidator);
* ```
*
* When you add or remove a validator at run time, you must call
* `updateValueAndValidity()` for the new validation to take effect.
*
* @param validators The validator or validators to remove.
*/
removeValidators(validators: ValidatorFn | ValidatorFn[]): void {
this.setValidators(removeValidators(validators, this._rawValidators));
}
/**
* Remove an asynchronous validator from this control, without affecting other validators.
* Validators are compared by function reference; you must pass a reference to the exact same
* validator function as the one that was originally set. If a provided validator is not found, it
* is ignored.
*
* When you add or remove a validator at run time, you must call
* `updateValueAndValidity()` for the new validation to take effect.
*
* @param validators The asynchronous validator or validators to remove.
*/
removeAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[]): void {
this.setAsyncValidators(removeValidators(validators, this._rawAsyncValidators));
}
/**
* Check whether a synchronous validator function is present on this control. The provided
* validator must be a reference to the exact same function that was provided.
*
* @usageNotes
*
* ### Reference to a ValidatorFn
*
* ```
* // Reference to the RequiredValidator
* const ctrl = new FormControl<number | null>(0, Validators.required);
* expect(ctrl.hasValidator(Validators.required)).toEqual(true)
*
* // Reference to anonymous function inside MinValidator
* const minValidator = Validators.min(3);
* const ctrl = new FormControl<number | null>(0, minValidator);
* expect(ctrl.hasValidator(minValidator)).toEqual(true)
* expect(ctrl.hasValidator(Validators.min(3))).toEqual(false)
* ```
*
* @param validator The validator to check for presence. Compared by function reference.
* @returns Whether the provided validator was found on this control.
*/
hasValidator(validator: ValidatorFn): boolean {
return hasValidator(this._rawValidators, validator);
}
/**
* Check whether an asynchronous validator function is present on this control. The provided
* validator must be a reference to the exact same function that was provided.
*
* @param validator The asynchronous validator to check for presence. Compared by function
* reference.
* @returns Whether the provided asynchronous validator was found on this control.
*/
hasAsyncValidator(validator: AsyncValidatorFn): boolean {
return hasValidator(this._rawAsyncValidators, validator);
}
/**
* Empties out the synchronous validator list.
*
* When you add or remove a validator at run time, you must call
* `updateValueAndValidity()` for the new validation to take effect.
*
*/
clearValidators(): void {
this.validator = null;
}
/**
* Empties out the async validator list.
*
* When you add or remove a validator at run time, you must call
* `updateValueAndValidity()` for the new validation to take effect.
*
*/
clearAsyncValidators(): void {
this.asyncValidator = null;
}
/**
* Marks the c | {
"end_byte": 30882,
"start_byte": 22059,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/abstract_model.ts"
} |
angular/packages/forms/src/model/abstract_model.ts_30886_38850 | ol as `touched`. A control is touched by focus and
* blur events that do not change the value.
*
* @see {@link markAsUntouched()}
* @see {@link markAsDirty()}
* @see {@link markAsPristine()}
*
* @param opts Configuration options that determine how the control propagates changes
* and emits events after marking is applied.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false.
* * `emitEvent`: When true or not supplied (the default), the `events`
* observable emits a `TouchedChangeEvent` with the `touched` property being `true`.
* When false, no events are emitted.
*/
markAsTouched(opts?: {onlySelf?: boolean; emitEvent?: boolean}): void;
/**
* @internal Used to propagate the source control downwards
*/
markAsTouched(opts?: {
onlySelf?: boolean;
emitEvent?: boolean;
sourceControl?: AbstractControl;
}): void;
markAsTouched(
opts: {onlySelf?: boolean; emitEvent?: boolean; sourceControl?: AbstractControl} = {},
): void {
const changed = this.touched === false;
this.touched = true;
const sourceControl = opts.sourceControl ?? this;
if (this._parent && !opts.onlySelf) {
this._parent.markAsTouched({...opts, sourceControl});
}
if (changed && opts.emitEvent !== false) {
this._events.next(new TouchedChangeEvent(true, sourceControl));
}
}
/**
* Marks the control and all its descendant controls as `touched`.
* @see {@link markAsTouched()}
*
* @param opts Configuration options that determine how the control propagates changes
* and emits events after marking is applied.
* * `emitEvent`: When true or not supplied (the default), the `events`
* observable emits a `TouchedChangeEvent` with the `touched` property being `true`.
* When false, no events are emitted.
*/
markAllAsTouched(opts: {emitEvent?: boolean} = {}): void {
this.markAsTouched({onlySelf: true, emitEvent: opts.emitEvent, sourceControl: this});
this._forEachChild((control: AbstractControl) => control.markAllAsTouched(opts));
}
/**
* Marks the control as `untouched`.
*
* If the control has any children, also marks all children as `untouched`
* and recalculates the `touched` status of all parent controls.
*
* @see {@link markAsTouched()}
* @see {@link markAsDirty()}
* @see {@link markAsPristine()}
*
* @param opts Configuration options that determine how the control propagates changes
* and emits events after the marking is applied.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false.
* * `emitEvent`: When true or not supplied (the default), the `events`
* observable emits a `TouchedChangeEvent` with the `touched` property being `false`.
* When false, no events are emitted.
*/
markAsUntouched(opts?: {onlySelf?: boolean; emitEvent?: boolean}): void;
/**
*
* @internal Used to propagate the source control downwards
*/
markAsUntouched(opts: {
onlySelf?: boolean;
emitEvent?: boolean;
sourceControl?: AbstractControl;
}): void;
markAsUntouched(
opts: {onlySelf?: boolean; emitEvent?: boolean; sourceControl?: AbstractControl} = {},
): void {
const changed = this.touched === true;
this.touched = false;
this._pendingTouched = false;
const sourceControl = opts.sourceControl ?? this;
this._forEachChild((control: AbstractControl) => {
control.markAsUntouched({onlySelf: true, emitEvent: opts.emitEvent, sourceControl});
});
if (this._parent && !opts.onlySelf) {
this._parent._updateTouched(opts, sourceControl);
}
if (changed && opts.emitEvent !== false) {
this._events.next(new TouchedChangeEvent(false, sourceControl));
}
}
/**
* Marks the control as `dirty`. A control becomes dirty when
* the control's value is changed through the UI; compare `markAsTouched`.
*
* @see {@link markAsTouched()}
* @see {@link markAsUntouched()}
* @see {@link markAsPristine()}
*
* @param opts Configuration options that determine how the control propagates changes
* and emits events after marking is applied.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false.
* * `emitEvent`: When true or not supplied (the default), the `events`
* observable emits a `PristineChangeEvent` with the `pristine` property being `false`.
* When false, no events are emitted.
*/
markAsDirty(opts?: {onlySelf?: boolean; emitEvent?: boolean}): void;
/**
* @internal Used to propagate the source control downwards
*/
markAsDirty(opts: {
onlySelf?: boolean;
emitEvent?: boolean;
sourceControl?: AbstractControl;
}): void;
markAsDirty(
opts: {onlySelf?: boolean; emitEvent?: boolean; sourceControl?: AbstractControl} = {},
): void {
const changed = this.pristine === true;
this.pristine = false;
const sourceControl = opts.sourceControl ?? this;
if (this._parent && !opts.onlySelf) {
this._parent.markAsDirty({...opts, sourceControl});
}
if (changed && opts.emitEvent !== false) {
this._events.next(new PristineChangeEvent(false, sourceControl));
}
}
/**
* Marks the control as `pristine`.
*
* If the control has any children, marks all children as `pristine`,
* and recalculates the `pristine` status of all parent
* controls.
*
* @see {@link markAsTouched()}
* @see {@link markAsUntouched()}
* @see {@link markAsDirty()}
*
* @param opts Configuration options that determine how the control emits events after
* marking is applied.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false.
* * `emitEvent`: When true or not supplied (the default), the `events`
* observable emits a `PristineChangeEvent` with the `pristine` property being `true`.
* When false, no events are emitted.
*/
markAsPristine(opts?: {onlySelf?: boolean; emitEvent?: boolean}): void;
/**
* @internal Used to propagate the source control downwards
*/
markAsPristine(opts: {
onlySelf?: boolean;
emitEvent?: boolean;
sourceControl?: AbstractControl;
}): void;
markAsPristine(
opts: {onlySelf?: boolean; emitEvent?: boolean; sourceControl?: AbstractControl} = {},
): void {
const changed = this.pristine === false;
this.pristine = true;
this._pendingDirty = false;
const sourceControl = opts.sourceControl ?? this;
this._forEachChild((control: AbstractControl) => {
/** We don't propagate the source control downwards */
control.markAsPristine({onlySelf: true, emitEvent: opts.emitEvent});
});
if (this._parent && !opts.onlySelf) {
this._parent._updatePristine(opts, sourceControl);
}
if (changed && opts.emitEvent !== false) {
this._events.next(new PristineChangeEvent(true, sourceControl));
}
}
/**
* Marks the control as `pending`.
*
* A control is pending while the control performs async validation.
*
* @see {@link AbstractControl.status}
*
* @param opts Configuration options that determine how the control propagates changes and
* emits events after marking is applied.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false.
* * `emitEvent`: When true or not supplied (the default), the `statusChanges`
* observable emits an event with the latest status the control is marked pending
* and the `events` observable emits a `StatusChangeEvent` with the `status` property being
* `PENDING` When false, no events are emitted.
*
*/
markAsPending(opts?: {onlySelf?: boolean; emitEvent?: boolean}): void;
/**
* @internal U | {
"end_byte": 38850,
"start_byte": 30886,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/abstract_model.ts"
} |
angular/packages/forms/src/model/abstract_model.ts_38850_47120 | sed to propagate the source control downwards
*/
markAsPending(opts: {
onlySelf?: boolean;
emitEvent?: boolean;
sourceControl?: AbstractControl;
}): void;
markAsPending(
opts: {onlySelf?: boolean; emitEvent?: boolean; sourceControl?: AbstractControl} = {},
): void {
this.status = PENDING;
const sourceControl = opts.sourceControl ?? this;
if (opts.emitEvent !== false) {
this._events.next(new StatusChangeEvent(this.status, sourceControl));
(this.statusChanges as EventEmitter<FormControlStatus>).emit(this.status);
}
if (this._parent && !opts.onlySelf) {
this._parent.markAsPending({...opts, sourceControl});
}
}
/**
* Disables the control. This means the control is exempt from validation checks and
* excluded from the aggregate value of any parent. Its status is `DISABLED`.
*
* If the control has children, all children are also disabled.
*
* @see {@link AbstractControl.status}
*
* @param opts Configuration options that determine how the control propagates
* changes and emits events after the control is disabled.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false.
* * `emitEvent`: When true or not supplied (the default), the `statusChanges`,
* `valueChanges` and `events`
* observables emit events with the latest status and value when the control is disabled.
* When false, no events are emitted.
*/
disable(opts?: {onlySelf?: boolean; emitEvent?: boolean}): void;
/**
* @internal Used to propagate the source control downwards
*/
disable(opts: {onlySelf?: boolean; emitEvent?: boolean; sourceControl?: AbstractControl}): void;
disable(
opts: {onlySelf?: boolean; emitEvent?: boolean; sourceControl?: AbstractControl} = {},
): void {
// If parent has been marked artificially dirty we don't want to re-calculate the
// parent's dirtiness based on the children.
const skipPristineCheck = this._parentMarkedDirty(opts.onlySelf);
this.status = DISABLED;
(this as Writable<this>).errors = null;
this._forEachChild((control: AbstractControl) => {
/** We don't propagate the source control downwards */
control.disable({...opts, onlySelf: true});
});
this._updateValue();
const sourceControl = opts.sourceControl ?? this;
if (opts.emitEvent !== false) {
this._events.next(new ValueChangeEvent(this.value, sourceControl));
this._events.next(new StatusChangeEvent(this.status, sourceControl));
(this.valueChanges as EventEmitter<TValue>).emit(this.value);
(this.statusChanges as EventEmitter<FormControlStatus>).emit(this.status);
}
this._updateAncestors({...opts, skipPristineCheck}, this);
this._onDisabledChange.forEach((changeFn) => changeFn(true));
}
/**
* Enables the control. This means the control is included in validation checks and
* the aggregate value of its parent. Its status recalculates based on its value and
* its validators.
*
* By default, if the control has children, all children are enabled.
*
* @see {@link AbstractControl.status}
*
* @param opts Configure options that control how the control propagates changes and
* emits events when marked as untouched
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false.
* * `emitEvent`: When true or not supplied (the default), the `statusChanges`,
* `valueChanges` and `events`
* observables emit events with the latest status and value when the control is enabled.
* When false, no events are emitted.
*/
enable(opts: {onlySelf?: boolean; emitEvent?: boolean} = {}): void {
// If parent has been marked artificially dirty we don't want to re-calculate the
// parent's dirtiness based on the children.
const skipPristineCheck = this._parentMarkedDirty(opts.onlySelf);
this.status = VALID;
this._forEachChild((control: AbstractControl) => {
control.enable({...opts, onlySelf: true});
});
this.updateValueAndValidity({onlySelf: true, emitEvent: opts.emitEvent});
this._updateAncestors({...opts, skipPristineCheck}, this);
this._onDisabledChange.forEach((changeFn) => changeFn(false));
}
private _updateAncestors(
opts: {onlySelf?: boolean; emitEvent?: boolean; skipPristineCheck?: boolean},
sourceControl: AbstractControl,
): void {
if (this._parent && !opts.onlySelf) {
this._parent.updateValueAndValidity(opts);
if (!opts.skipPristineCheck) {
this._parent._updatePristine({}, sourceControl);
}
this._parent._updateTouched({}, sourceControl);
}
}
/**
* Sets the parent of the control
*
* @param parent The new parent.
*/
setParent(parent: FormGroup | FormArray | null): void {
this._parent = parent;
}
/**
* Sets the value of the control. Abstract method (implemented in sub-classes).
*/
abstract setValue(value: TRawValue, options?: Object): void;
/**
* Patches the value of the control. Abstract method (implemented in sub-classes).
*/
abstract patchValue(value: TValue, options?: Object): void;
/**
* Resets the control. Abstract method (implemented in sub-classes).
*/
abstract reset(value?: TValue, options?: Object): void;
/**
* The raw value of this control. For most control implementations, the raw value will include
* disabled children.
*/
getRawValue(): any {
return this.value;
}
/**
* Recalculates the value and validation status of the control.
*
* By default, it also updates the value and validity of its ancestors.
*
* @param opts Configuration options determine how the control propagates changes and emits events
* after updates and validity checks are applied.
* * `onlySelf`: When true, only update this control. When false or not supplied,
* update all direct ancestors. Default is false.
* * `emitEvent`: When true or not supplied (the default), the `statusChanges`,
* `valueChanges` and `events`
* observables emit events with the latest status and value when the control is updated.
* When false, no events are emitted.
*/
updateValueAndValidity(opts?: {onlySelf?: boolean; emitEvent?: boolean}): void;
/**
* @internal Used to propagate the source control downwards
*/
updateValueAndValidity(opts: {
onlySelf?: boolean;
emitEvent?: boolean;
sourceControl?: AbstractControl;
}): void;
updateValueAndValidity(
opts: {onlySelf?: boolean; emitEvent?: boolean; sourceControl?: AbstractControl} = {},
): void {
this._setInitialStatus();
this._updateValue();
if (this.enabled) {
const shouldHaveEmitted = this._cancelExistingSubscription();
(this as Writable<this>).errors = this._runValidator();
this.status = this._calculateStatus();
if (this.status === VALID || this.status === PENDING) {
// If the canceled subscription should have emitted
// we make sure the async validator emits the status change on completion
this._runAsyncValidator(shouldHaveEmitted, opts.emitEvent);
}
}
const sourceControl = opts.sourceControl ?? this;
if (opts.emitEvent !== false) {
this._events.next(new ValueChangeEvent<TValue>(this.value, sourceControl));
this._events.next(new StatusChangeEvent(this.status, sourceControl));
(this.valueChanges as EventEmitter<TValue>).emit(this.value);
(this.statusChanges as EventEmitter<FormControlStatus>).emit(this.status);
}
if (this._parent && !opts.onlySelf) {
this._parent.updateValueAndValidity({...opts, sourceControl});
}
}
/** @internal */
_updateTreeValidity(opts: {emitEvent?: boolean} = {emitEvent: true}): void {
this._forEachChild((ctrl: AbstractControl) => ctrl._updateTreeValidity(opts));
this.updateValueAndValidity({onlySelf: true, emitEvent: opts.emitEvent});
}
private _setInitialStatus() {
this.status = this._allControlsDisabled() ? DISABLED : VALID;
}
private _runValidator(): ValidationErrors | null {
return this.validator ? this.validator(this) : null;
}
private _runAsyncVal | {
"end_byte": 47120,
"start_byte": 38850,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/abstract_model.ts"
} |
angular/packages/forms/src/model/abstract_model.ts_47124_54556 | or(shouldHaveEmitted: boolean, emitEvent?: boolean): void {
if (this.asyncValidator) {
this.status = PENDING;
this._hasOwnPendingAsyncValidator = {emitEvent: emitEvent !== false};
const obs = toObservable(this.asyncValidator(this));
this._asyncValidationSubscription = obs.subscribe((errors: ValidationErrors | null) => {
this._hasOwnPendingAsyncValidator = null;
// This will trigger the recalculation of the validation status, which depends on
// the state of the asynchronous validation (whether it is in progress or not). So, it is
// necessary that we have updated the `_hasOwnPendingAsyncValidator` boolean flag first.
this.setErrors(errors, {emitEvent, shouldHaveEmitted});
});
}
}
private _cancelExistingSubscription(): boolean {
if (this._asyncValidationSubscription) {
this._asyncValidationSubscription.unsubscribe();
// we're cancelling the validator subscribtion, we keep if it should have emitted
// because we want to emit eventually if it was required at least once.
const shouldHaveEmitted = this._hasOwnPendingAsyncValidator?.emitEvent ?? false;
this._hasOwnPendingAsyncValidator = null;
return shouldHaveEmitted;
}
return false;
}
/**
* Sets errors on a form control when running validations manually, rather than automatically.
*
* Calling `setErrors` also updates the validity of the parent control.
*
* @param opts Configuration options that determine how the control propagates
* changes and emits events after the control errors are set.
* * `emitEvent`: When true or not supplied (the default), the `statusChanges`
* observable emits an event after the errors are set.
*
* @usageNotes
*
* ### Manually set the errors for a control
*
* ```
* const login = new FormControl('someLogin');
* login.setErrors({
* notUnique: true
* });
*
* expect(login.valid).toEqual(false);
* expect(login.errors).toEqual({ notUnique: true });
*
* login.setValue('someOtherLogin');
*
* expect(login.valid).toEqual(true);
* ```
*/
setErrors(errors: ValidationErrors | null, opts?: {emitEvent?: boolean}): void;
/** @internal */
setErrors(
errors: ValidationErrors | null,
opts?: {emitEvent?: boolean; shouldHaveEmitted?: boolean},
): void;
setErrors(
errors: ValidationErrors | null,
opts: {emitEvent?: boolean; shouldHaveEmitted?: boolean} = {},
): void {
(this as Writable<this>).errors = errors;
this._updateControlsErrors(opts.emitEvent !== false, this, opts.shouldHaveEmitted);
}
/**
* Retrieves a child control given the control's name or path.
*
* This signature for get supports strings and `const` arrays (`.get(['foo', 'bar'] as const)`).
*/
get<P extends string | readonly (string | number)[]>(
path: P,
): AbstractControl<ɵGetProperty<TRawValue, P>> | null;
/**
* Retrieves a child control given the control's name or path.
*
* This signature for `get` supports non-const (mutable) arrays. Inferred type
* information will not be as robust, so prefer to pass a `readonly` array if possible.
*/
get<P extends string | Array<string | number>>(
path: P,
): AbstractControl<ɵGetProperty<TRawValue, P>> | null;
/**
* Retrieves a child control given the control's name or path.
*
* @param path A dot-delimited string or array of string/number values that define the path to the
* control. If a string is provided, passing it as a string literal will result in improved type
* information. Likewise, if an array is provided, passing it `as const` will cause improved type
* information to be available.
*
* @usageNotes
* ### Retrieve a nested control
*
* For example, to get a `name` control nested within a `person` sub-group:
*
* * `this.form.get('person.name');`
*
* -OR-
*
* * `this.form.get(['person', 'name'] as const);` // `as const` gives improved typings
*
* ### Retrieve a control in a FormArray
*
* When accessing an element inside a FormArray, you can use an element index.
* For example, to get a `price` control from the first element in an `items` array you can use:
*
* * `this.form.get('items.0.price');`
*
* -OR-
*
* * `this.form.get(['items', 0, 'price']);`
*/
get<P extends string | (string | number)[]>(
path: P,
): AbstractControl<ɵGetProperty<TRawValue, P>> | null {
let currPath: Array<string | number> | string = path;
if (currPath == null) return null;
if (!Array.isArray(currPath)) currPath = currPath.split('.');
if (currPath.length === 0) return null;
return currPath.reduce(
(control: AbstractControl | null, name) => control && control._find(name),
this,
);
}
/**
* @description
* Reports error data for the control with the given path.
*
* @param errorCode The code of the error to check
* @param path A list of control names that designates how to move from the current control
* to the control that should be queried for errors.
*
* @usageNotes
* For example, for the following `FormGroup`:
*
* ```
* form = new FormGroup({
* address: new FormGroup({ street: new FormControl() })
* });
* ```
*
* The path to the 'street' control from the root form would be 'address' -> 'street'.
*
* It can be provided to this method in one of two formats:
*
* 1. An array of string control names, e.g. `['address', 'street']`
* 1. A period-delimited list of control names in one string, e.g. `'address.street'`
*
* @returns error data for that particular error. If the control or error is not present,
* null is returned.
*/
getError(errorCode: string, path?: Array<string | number> | string): any {
const control = path ? this.get(path) : this;
return control && control.errors ? control.errors[errorCode] : null;
}
/**
* @description
* Reports whether the control with the given path has the error specified.
*
* @param errorCode The code of the error to check
* @param path A list of control names that designates how to move from the current control
* to the control that should be queried for errors.
*
* @usageNotes
* For example, for the following `FormGroup`:
*
* ```
* form = new FormGroup({
* address: new FormGroup({ street: new FormControl() })
* });
* ```
*
* The path to the 'street' control from the root form would be 'address' -> 'street'.
*
* It can be provided to this method in one of two formats:
*
* 1. An array of string control names, e.g. `['address', 'street']`
* 1. A period-delimited list of control names in one string, e.g. `'address.street'`
*
* If no path is given, this method checks for the error on the current control.
*
* @returns whether the given error is present in the control at the given path.
*
* If the control is not present, false is returned.
*/
hasError(errorCode: string, path?: Array<string | number> | string): boolean {
return !!this.getError(errorCode, path);
}
/**
* Retrieves the top-level ancestor of this control.
*/
get root(): AbstractControl {
let x: AbstractControl = this;
while (x._parent) {
x = x._parent;
}
return x;
}
/** @internal */
_updateControlsErrors(
| {
"end_byte": 54556,
"start_byte": 47124,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/abstract_model.ts"
} |
angular/packages/forms/src/model/abstract_model.ts_54559_59230 | emitEvent: boolean,
changedControl: AbstractControl,
shouldHaveEmitted?: boolean,
): void {
this.status = this._calculateStatus();
if (emitEvent) {
(this.statusChanges as EventEmitter<FormControlStatus>).emit(this.status);
}
// The Events Observable expose a slight different bevahior than the statusChanges obs
// An async validator will still emit a StatusChangeEvent is a previously cancelled
// async validator has emitEvent set to true
if (emitEvent || shouldHaveEmitted) {
this._events.next(new StatusChangeEvent(this.status, changedControl));
}
if (this._parent) {
this._parent._updateControlsErrors(emitEvent, changedControl, shouldHaveEmitted);
}
}
/** @internal */
_initObservables() {
(this as Writable<this>).valueChanges = new EventEmitter();
(this as Writable<this>).statusChanges = new EventEmitter();
}
private _calculateStatus(): FormControlStatus {
if (this._allControlsDisabled()) return DISABLED;
if (this.errors) return INVALID;
if (this._hasOwnPendingAsyncValidator || this._anyControlsHaveStatus(PENDING)) return PENDING;
if (this._anyControlsHaveStatus(INVALID)) return INVALID;
return VALID;
}
/** @internal */
abstract _updateValue(): void;
/** @internal */
abstract _forEachChild(cb: (c: AbstractControl) => void): void;
/** @internal */
abstract _anyControls(condition: (c: AbstractControl) => boolean): boolean;
/** @internal */
abstract _allControlsDisabled(): boolean;
/** @internal */
abstract _syncPendingControls(): boolean;
/** @internal */
_anyControlsHaveStatus(status: FormControlStatus): boolean {
return this._anyControls((control: AbstractControl) => control.status === status);
}
/** @internal */
_anyControlsDirty(): boolean {
return this._anyControls((control: AbstractControl) => control.dirty);
}
/** @internal */
_anyControlsTouched(): boolean {
return this._anyControls((control: AbstractControl) => control.touched);
}
/** @internal */
_updatePristine(opts: {onlySelf?: boolean}, changedControl: AbstractControl): void {
const newPristine = !this._anyControlsDirty();
const changed = this.pristine !== newPristine;
this.pristine = newPristine;
if (this._parent && !opts.onlySelf) {
this._parent._updatePristine(opts, changedControl);
}
if (changed) {
this._events.next(new PristineChangeEvent(this.pristine, changedControl));
}
}
/** @internal */
_updateTouched(opts: {onlySelf?: boolean} = {}, changedControl: AbstractControl): void {
this.touched = this._anyControlsTouched();
this._events.next(new TouchedChangeEvent(this.touched, changedControl));
if (this._parent && !opts.onlySelf) {
this._parent._updateTouched(opts, changedControl);
}
}
/** @internal */
_onDisabledChange: Array<(isDisabled: boolean) => void> = [];
/** @internal */
_registerOnCollectionChange(fn: () => void): void {
this._onCollectionChange = fn;
}
/** @internal */
_setUpdateStrategy(opts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null): void {
if (isOptionsObj(opts) && opts.updateOn != null) {
this._updateOn = opts.updateOn!;
}
}
/**
* Check to see if parent has been marked artificially dirty.
*
* @internal
*/
private _parentMarkedDirty(onlySelf?: boolean): boolean {
const parentDirty = this._parent && this._parent.dirty;
return !onlySelf && !!parentDirty && !this._parent!._anyControlsDirty();
}
/** @internal */
_find(name: string | number): AbstractControl | null {
return null;
}
/**
* Internal implementation of the `setValidators` method. Needs to be separated out into a
* different method, because it is called in the constructor and it can break cases where
* a control is extended.
*/
private _assignValidators(validators: ValidatorFn | ValidatorFn[] | null): void {
this._rawValidators = Array.isArray(validators) ? validators.slice() : validators;
this._composedValidatorFn = coerceToValidator(this._rawValidators);
}
/**
* Internal implementation of the `setAsyncValidators` method. Needs to be separated out into a
* different method, because it is called in the constructor and it can break cases where
* a control is extended.
*/
private _assignAsyncValidators(validators: AsyncValidatorFn | AsyncValidatorFn[] | null): void {
this._rawAsyncValidators = Array.isArray(validators) ? validators.slice() : validators;
this._composedAsyncValidatorFn = coerceToAsyncValidator(this._rawAsyncValidators);
}
}
| {
"end_byte": 59230,
"start_byte": 54559,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/abstract_model.ts"
} |
angular/packages/forms/src/model/form_array.ts_0_3755 | /**
* @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 {ɵWritable as Writable} from '@angular/core';
import {AsyncValidatorFn, ValidatorFn} from '../directives/validators';
import {
AbstractControl,
AbstractControlOptions,
assertAllValuesPresent,
assertControlPresent,
pickAsyncValidators,
pickValidators,
ɵRawValue,
ɵTypedOrUntyped,
ɵValue,
} from './abstract_model';
/**
* FormArrayValue extracts the type of `.value` from a FormArray's element type, and wraps it in an
* array.
*
* Angular uses this type internally to support Typed Forms; do not use it directly. The untyped
* case falls back to any[].
*/
export type ɵFormArrayValue<T extends AbstractControl<any>> = ɵTypedOrUntyped<
T,
Array<ɵValue<T>>,
any[]
>;
/**
* FormArrayRawValue extracts the type of `.getRawValue()` from a FormArray's element type, and
* wraps it in an array. The untyped case falls back to any[].
*
* Angular uses this type internally to support Typed Forms; do not use it directly.
*/
export type ɵFormArrayRawValue<T extends AbstractControl<any>> = ɵTypedOrUntyped<
T,
Array<ɵRawValue<T>>,
any[]
>;
/**
* Tracks the value and validity state of an array of `FormControl`,
* `FormGroup` or `FormArray` instances.
*
* A `FormArray` aggregates the values of each child `FormControl` into an array.
* It calculates its status by reducing the status values of its children. For example, if one of
* the controls in a `FormArray` is invalid, the entire array becomes invalid.
*
* `FormArray` accepts one generic argument, which is the type of the controls inside.
* If you need a heterogenous array, use {@link UntypedFormArray}.
*
* `FormArray` is one of the four fundamental building blocks used to define forms in Angular,
* along with `FormControl`, `FormGroup`, and `FormRecord`.
*
* @usageNotes
*
* ### Create an array of form controls
*
* ```
* const arr = new FormArray([
* new FormControl('Nancy', Validators.minLength(2)),
* new FormControl('Drew'),
* ]);
*
* console.log(arr.value); // ['Nancy', 'Drew']
* console.log(arr.status); // 'VALID'
* ```
*
* ### Create a form array with array-level validators
*
* You include array-level validators and async validators. These come in handy
* when you want to perform validation that considers the value of more than one child
* control.
*
* The two types of validators are passed in separately as the second and third arg
* respectively, or together as part of an options object.
*
* ```
* const arr = new FormArray([
* new FormControl('Nancy'),
* new FormControl('Drew')
* ], {validators: myValidator, asyncValidators: myAsyncValidator});
* ```
*
* ### Set the updateOn property for all controls in a form array
*
* The options object is used to set a default value for each child
* control's `updateOn` property. If you set `updateOn` to `'blur'` at the
* array level, all child controls default to 'blur', unless the child
* has explicitly specified a different `updateOn` value.
*
* ```ts
* const arr = new FormArray([
* new FormControl()
* ], {updateOn: 'blur'});
* ```
*
* ### Adding or removing controls from a form array
*
* To change the controls in the array, use the `push`, `insert`, `removeAt` or `clear` methods
* in `FormArray` itself. These methods ensure the controls are properly tracked in the
* form's hierarchy. Do not modify the array of `AbstractControl`s used to instantiate
* the `FormArray` directly, as that result in strange and unexpected behavior such
* as broken change detection.
*
* @publicApi
*/
export cl | {
"end_byte": 3755,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/form_array.ts"
} |
angular/packages/forms/src/model/form_array.ts_3756_11692 | ss FormArray<TControl extends AbstractControl<any> = any> extends AbstractControl<
ɵTypedOrUntyped<TControl, ɵFormArrayValue<TControl>, any>,
ɵTypedOrUntyped<TControl, ɵFormArrayRawValue<TControl>, any>
> {
/**
* Creates a new `FormArray` instance.
*
* @param controls An array of child controls. Each child control is given an index
* where it is registered.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or an `AbstractControlOptions` object that contains validation functions
* and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator functions
*
*/
constructor(
controls: Array<TControl>,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
) {
super(pickValidators(validatorOrOpts), pickAsyncValidators(asyncValidator, validatorOrOpts));
this.controls = controls;
this._initObservables();
this._setUpdateStrategy(validatorOrOpts);
this._setUpControls();
this.updateValueAndValidity({
onlySelf: true,
// If `asyncValidator` is present, it will trigger control status change from `PENDING` to
// `VALID` or `INVALID`.
// The status should be broadcasted via the `statusChanges` observable, so we set `emitEvent`
// to `true` to allow that during the control creation process.
emitEvent: !!this.asyncValidator,
});
}
public controls: ɵTypedOrUntyped<TControl, Array<TControl>, Array<AbstractControl<any>>>;
/**
* Get the `AbstractControl` at the given `index` in the array.
*
* @param index Index in the array to retrieve the control. If `index` is negative, it will wrap
* around from the back, and if index is greatly negative (less than `-length`), the result is
* undefined. This behavior is the same as `Array.at(index)`.
*/
at(index: number): ɵTypedOrUntyped<TControl, TControl, AbstractControl<any>> {
return (this.controls as any)[this._adjustIndex(index)];
}
/**
* Insert a new `AbstractControl` at the end of the array.
*
* @param control Form control to be inserted
* @param options Specifies whether this FormArray instance should emit events after a new
* control is added.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges` observables emit events with the latest status and value when the control is
* inserted. When false, no events are emitted.
*/
push(control: TControl, options: {emitEvent?: boolean} = {}): void {
this.controls.push(control);
this._registerControl(control);
this.updateValueAndValidity({emitEvent: options.emitEvent});
this._onCollectionChange();
}
/**
* Insert a new `AbstractControl` at the given `index` in the array.
*
* @param index Index in the array to insert the control. If `index` is negative, wraps around
* from the back. If `index` is greatly negative (less than `-length`), prepends to the array.
* This behavior is the same as `Array.splice(index, 0, control)`.
* @param control Form control to be inserted
* @param options Specifies whether this FormArray instance should emit events after a new
* control is inserted.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges` observables emit events with the latest status and value when the control is
* inserted. When false, no events are emitted.
*/
insert(index: number, control: TControl, options: {emitEvent?: boolean} = {}): void {
this.controls.splice(index, 0, control);
this._registerControl(control);
this.updateValueAndValidity({emitEvent: options.emitEvent});
}
/**
* Remove the control at the given `index` in the array.
*
* @param index Index in the array to remove the control. If `index` is negative, wraps around
* from the back. If `index` is greatly negative (less than `-length`), removes the first
* element. This behavior is the same as `Array.splice(index, 1)`.
* @param options Specifies whether this FormArray instance should emit events after a
* control is removed.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges` observables emit events with the latest status and value when the control is
* removed. When false, no events are emitted.
*/
removeAt(index: number, options: {emitEvent?: boolean} = {}): void {
// Adjust the index, then clamp it at no less than 0 to prevent undesired underflows.
let adjustedIndex = this._adjustIndex(index);
if (adjustedIndex < 0) adjustedIndex = 0;
if (this.controls[adjustedIndex])
this.controls[adjustedIndex]._registerOnCollectionChange(() => {});
this.controls.splice(adjustedIndex, 1);
this.updateValueAndValidity({emitEvent: options.emitEvent});
}
/**
* Replace an existing control.
*
* @param index Index in the array to replace the control. If `index` is negative, wraps around
* from the back. If `index` is greatly negative (less than `-length`), replaces the first
* element. This behavior is the same as `Array.splice(index, 1, control)`.
* @param control The `AbstractControl` control to replace the existing control
* @param options Specifies whether this FormArray instance should emit events after an
* existing control is replaced with a new one.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges` observables emit events with the latest status and value when the control is
* replaced with a new one. When false, no events are emitted.
*/
setControl(index: number, control: TControl, options: {emitEvent?: boolean} = {}): void {
// Adjust the index, then clamp it at no less than 0 to prevent undesired underflows.
let adjustedIndex = this._adjustIndex(index);
if (adjustedIndex < 0) adjustedIndex = 0;
if (this.controls[adjustedIndex])
this.controls[adjustedIndex]._registerOnCollectionChange(() => {});
this.controls.splice(adjustedIndex, 1);
if (control) {
this.controls.splice(adjustedIndex, 0, control);
this._registerControl(control);
}
this.updateValueAndValidity({emitEvent: options.emitEvent});
this._onCollectionChange();
}
/**
* Length of the control array.
*/
get length(): number {
return this.controls.length;
}
/**
* Sets the value of the `FormArray`. It accepts an array that matches
* the structure of the control.
*
* This method performs strict checks, and throws an error if you try
* to set the value of a control that doesn't exist or if you exclude the
* value of a control.
*
* @usageNotes
* ### Set the values for the controls in the form array
*
* ```
* const arr = new FormArray([
* new FormControl(),
* new FormControl()
* ]);
* console.log(arr.value); // [null, null]
*
* arr.setValue(['Nancy', 'Drew']);
* console.log(arr.value); // ['Nancy', 'Drew']
* ```
*
* @param value Array of values for the controls
* @param options Configure options that determine how the control propagates changes and
* emits events after the value changes
*
* * `onlySelf`: When true, each change only affects this control, and not its parent. Default
* is false.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control value is updated.
* When false, no events are emitted.
* The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
* updateValueAndValidity} method.
*/
override setV | {
"end_byte": 11692,
"start_byte": 3756,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/form_array.ts"
} |
angular/packages/forms/src/model/form_array.ts_11695_19621 | e(
value: ɵFormArrayRawValue<TControl>,
options: {
onlySelf?: boolean;
emitEvent?: boolean;
} = {},
): void {
assertAllValuesPresent(this, false, value);
value.forEach((newValue: any, index: number) => {
assertControlPresent(this, false, index);
this.at(index).setValue(newValue, {onlySelf: true, emitEvent: options.emitEvent});
});
this.updateValueAndValidity(options);
}
/**
* Patches the value of the `FormArray`. It accepts an array that matches the
* structure of the control, and does its best to match the values to the correct
* controls in the group.
*
* It accepts both super-sets and sub-sets of the array without throwing an error.
*
* @usageNotes
* ### Patch the values for controls in a form array
*
* ```
* const arr = new FormArray([
* new FormControl(),
* new FormControl()
* ]);
* console.log(arr.value); // [null, null]
*
* arr.patchValue(['Nancy']);
* console.log(arr.value); // ['Nancy', null]
* ```
*
* @param value Array of latest values for the controls
* @param options Configure options that determine how the control propagates changes and
* emits events after the value changes
*
* * `onlySelf`: When true, each change only affects this control, and not its parent. Default
* is false.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges` observables emit events with the latest status and value when the control
* value is updated. When false, no events are emitted. The configuration options are passed to
* the {@link AbstractControl#updateValueAndValidity updateValueAndValidity} method.
*/
override patchValue(
value: ɵFormArrayValue<TControl>,
options: {
onlySelf?: boolean;
emitEvent?: boolean;
} = {},
): void {
// Even though the `value` argument type doesn't allow `null` and `undefined` values, the
// `patchValue` can be called recursively and inner data structures might have these values,
// so we just ignore such cases when a field containing FormArray instance receives `null` or
// `undefined` as a value.
if (value == null /* both `null` and `undefined` */) return;
value.forEach((newValue, index) => {
if (this.at(index)) {
this.at(index).patchValue(newValue, {onlySelf: true, emitEvent: options.emitEvent});
}
});
this.updateValueAndValidity(options);
}
/**
* Resets the `FormArray` and all descendants are marked `pristine` and `untouched`, and the
* value of all descendants to null or null maps.
*
* You reset to a specific form state by passing in an array of states
* that matches the structure of the control. The state is a standalone value
* or a form state object with both a value and a disabled status.
*
* @usageNotes
* ### Reset the values in a form array
*
* ```ts
* const arr = new FormArray([
* new FormControl(),
* new FormControl()
* ]);
* arr.reset(['name', 'last name']);
*
* console.log(arr.value); // ['name', 'last name']
* ```
*
* ### Reset the values in a form array and the disabled status for the first control
*
* ```
* arr.reset([
* {value: 'name', disabled: true},
* 'last'
* ]);
*
* console.log(arr.value); // ['last']
* console.log(arr.at(0).status); // 'DISABLED'
* ```
*
* @param value Array of values for the controls
* @param options Configure options that determine how the control propagates changes and
* emits events after the value changes
*
* * `onlySelf`: When true, each change only affects this control, and not its parent. Default
* is false.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control is reset.
* When false, no events are emitted.
* The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
* updateValueAndValidity} method.
*/
override reset(
value: ɵTypedOrUntyped<TControl, ɵFormArrayValue<TControl>, any> = [],
options: {
onlySelf?: boolean;
emitEvent?: boolean;
} = {},
): void {
this._forEachChild((control: AbstractControl, index: number) => {
control.reset(value[index], {onlySelf: true, emitEvent: options.emitEvent});
});
this._updatePristine(options, this);
this._updateTouched(options, this);
this.updateValueAndValidity(options);
}
/**
* The aggregate value of the array, including any disabled controls.
*
* Reports all values regardless of disabled status.
*/
override getRawValue(): ɵFormArrayRawValue<TControl> {
return this.controls.map((control: AbstractControl) => control.getRawValue());
}
/**
* Remove all controls in the `FormArray`.
*
* @param options Specifies whether this FormArray instance should emit events after all
* controls are removed.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges` observables emit events with the latest status and value when all controls
* in this FormArray instance are removed. When false, no events are emitted.
*
* @usageNotes
* ### Remove all elements from a FormArray
*
* ```ts
* const arr = new FormArray([
* new FormControl(),
* new FormControl()
* ]);
* console.log(arr.length); // 2
*
* arr.clear();
* console.log(arr.length); // 0
* ```
*
* It's a simpler and more efficient alternative to removing all elements one by one:
*
* ```ts
* const arr = new FormArray([
* new FormControl(),
* new FormControl()
* ]);
*
* while (arr.length) {
* arr.removeAt(0);
* }
* ```
*/
clear(options: {emitEvent?: boolean} = {}): void {
if (this.controls.length < 1) return;
this._forEachChild((control) => control._registerOnCollectionChange(() => {}));
this.controls.splice(0);
this.updateValueAndValidity({emitEvent: options.emitEvent});
}
/**
* Adjusts a negative index by summing it with the length of the array. For very negative
* indices, the result may remain negative.
* @internal
*/
private _adjustIndex(index: number): number {
return index < 0 ? index + this.length : index;
}
/** @internal */
override _syncPendingControls(): boolean {
let subtreeUpdated = (this.controls as any).reduce((updated: any, child: any) => {
return child._syncPendingControls() ? true : updated;
}, false);
if (subtreeUpdated) this.updateValueAndValidity({onlySelf: true});
return subtreeUpdated;
}
/** @internal */
override _forEachChild(cb: (c: AbstractControl, index: number) => void): void {
this.controls.forEach((control: AbstractControl, index: number) => {
cb(control, index);
});
}
/** @internal */
override _updateValue(): void {
(this as Writable<this>).value = this.controls
.filter((control) => control.enabled || this.disabled)
.map((control) => control.value);
}
/** @internal */
override _anyControls(condition: (c: AbstractControl) => boolean): boolean {
return this.controls.some((control) => control.enabled && condition(control));
}
/** @internal */
_setUpControls(): void {
this._forEachChild((control) => this._registerControl(control));
}
/** @internal */
override _allControlsDisabled(): boolean {
for (const control of this.controls) {
if (control.enabled) return false;
}
return this.controls.length > 0 || this.disabled;
}
private _registerControl(control: AbstractControl) {
control.setParent(this);
control._registerOnCollectionChange(this._onCollectionChange);
}
/** @internal */
override _find(nam | {
"end_byte": 19621,
"start_byte": 11695,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/form_array.ts"
} |
angular/packages/forms/src/model/form_array.ts_19624_20610 | string | number): AbstractControl | null {
return this.at(name as number) ?? null;
}
}
interface UntypedFormArrayCtor {
new (
controls: AbstractControl[],
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
): UntypedFormArray;
/**
* The presence of an explicit `prototype` property provides backwards-compatibility for apps that
* manually inspect the prototype chain.
*/
prototype: FormArray<any>;
}
/**
* UntypedFormArray is a non-strongly-typed version of `FormArray`, which
* permits heterogenous controls.
*/
export type UntypedFormArray = FormArray<any>;
export const UntypedFormArray: UntypedFormArrayCtor = FormArray;
/**
* @description
* Asserts that the given control is an instance of `FormArray`
*
* @publicApi
*/
export const isFormArray = (control: unknown): control is FormArray => control instanceof FormArray;
| {
"end_byte": 20610,
"start_byte": 19624,
"url": "https://github.com/angular/angular/blob/main/packages/forms/src/model/form_array.ts"
} |
angular/packages/core/PACKAGE.md_0_410 | Implements Angular's core functionality, low-level services, and utilities.
* Defines the class infrastructure for components, view hierarchies, change detection, rendering, and event handling.
* Defines the decorators that supply metadata and context for Angular constructs.
* Defines infrastructure for dependency injection (DI), internationalization (i18n), and various testing and debugging facilities. | {
"end_byte": 410,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/PACKAGE.md"
} |
angular/packages/core/BUILD.bazel_0_4761 | load("@build_bazel_rules_nodejs//:index.bzl", "generated_file_test")
load("//adev/shared-docs/pipeline/api-gen:generate_api_docs.bzl", "generate_api_docs")
load("//packages/common/locales:index.bzl", "generate_base_locale_file")
load("//tools:defaults.bzl", "api_golden_test", "api_golden_test_npm_package", "ng_module", "ng_package", "tsec_test")
package(default_visibility = ["//visibility:public"])
# This generates the `src/i18n/locale_en.ts` file through the `generate-locales` tool. Since
# the base locale file is checked-in for Google3, we add a `generated_file_test` to ensure
# the checked-in file is up-to-date. To disambiguate from the test, we use a more precise target
# name here.
generate_base_locale_file(
name = "base_locale_file_generated",
output_file = "base_locale_file_generated.ts",
)
generated_file_test(
name = "base_locale_file",
src = "src/i18n/locale_en.ts",
generated = ":base_locale_file_generated",
)
ng_module(
name = "core",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
),
deps = [
"//packages:types",
"//packages/core/primitives/event-dispatch",
"//packages/core/primitives/signals",
"//packages/core/src/compiler",
"//packages/core/src/di/interface",
"//packages/core/src/interface",
"//packages/core/src/reflection",
"//packages/core/src/util",
"//packages/zone.js/lib:zone_d_ts",
"@npm//rxjs",
],
)
tsec_test(
name = "tsec_test",
target = "core",
tsconfig = "//packages:tsec_config",
)
ng_package(
name = "npm_package",
package_name = "@angular/core",
srcs = [
"package.json",
":event_dispatch_contract_binary",
],
nested_packages = [
"//packages/core/schematics:npm_package",
],
tags = [
"release-with-framework",
],
# Do not add more to this list.
# Dependencies on the full npm_package cause long re-builds.
visibility = [
"//adev:__pkg__",
"//adev/shared-docs:__subpackages__",
"//integration:__subpackages__",
"//modules/ssr-benchmarks:__subpackages__",
"//packages/bazel/test/ng_package:__pkg__",
"//packages/compiler-cli/src/ngtsc/metadata/test:__subpackages__",
"//packages/compiler-cli/src/ngtsc/typecheck/extended/test:__subpackages__",
"//packages/compiler-cli/src/ngtsc/typecheck/test:__subpackages__",
"//packages/compiler-cli/test:__subpackages__",
"//packages/compiler/test:__pkg__",
"//packages/language-service/test:__pkg__",
],
deps = [
":core",
"//packages/core/primitives/event-dispatch",
"//packages/core/primitives/signals",
"//packages/core/rxjs-interop",
"//packages/core/testing",
],
)
api_golden_test_npm_package(
name = "core_api",
data = [
":npm_package",
"//goldens:public-api",
],
golden_dir = "angular/goldens/public-api/core",
npm_package = "angular/packages/core/npm_package",
strip_export_pattern = "^ɵ(?!.*ApiGuard)",
)
api_golden_test(
name = "ng_global_utils_api",
data = [
"//goldens:public-api",
"//packages/core",
# Additional targets the entry-point indirectly resolves `.d.ts` source files from.
# These are transitive to `:core`, but need to be listed explicitly here as only
# transitive `JSModule` information is collected (missing the type definitions).
"//packages/core/src/compiler",
"//packages/core/src/di/interface",
"//packages/core/src/interface",
"//packages/core/src/reflection",
"//packages/core/src/util",
],
entry_point = "angular/packages/core/src/render3/global_utils_api.d.ts",
golden = "angular/goldens/public-api/core/global_utils.api.md",
)
api_golden_test(
name = "core_errors",
data = [
"//goldens:public-api",
"//packages/core",
],
entry_point = "angular/packages/core/src/errors.d.ts",
golden = "angular/goldens/public-api/core/errors.api.md",
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + [
"PACKAGE.md",
],
)
generate_api_docs(
name = "core_docs",
srcs = [
"//packages:common_files_and_deps_for_docs",
],
entry_point = ":index.ts",
module_name = "@angular/core",
private_modules = [
"core/primitives/signals",
"core/primitives/event-dispatch",
],
)
genrule(
name = "event_dispatch_contract_binary",
srcs = ["//packages/core/primitives/event-dispatch:contract_bundle_min"],
outs = ["event-dispatch-contract.min.js"],
cmd = "cp $< $@",
)
| {
"end_byte": 4761,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/BUILD.bazel"
} |
angular/packages/core/index.ts_0_485 | /**
* @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": 485,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/index.ts"
} |
angular/packages/core/public_api.ts_0_395 | /**
* @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/core';
// This file only reexports content of the `src` folder. Keep it that way.
| {
"end_byte": 395,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/public_api.ts"
} |
angular/packages/core/test/error_handler_spec.ts_0_1252 | /**
* @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 {ErrorHandler} from '../src/error_handler';
class MockConsole {
res: any[][] = [];
error(...s: any[]): void {
this.res.push(s);
}
}
function errorToString(error: any) {
const logger = new MockConsole();
const errorHandler = new ErrorHandler();
(errorHandler as any)._console = logger as any;
errorHandler.handleError(error);
return logger.res.map((line) => line.map((x) => `${x}`).join('#')).join('\n');
}
describe('ErrorHandler', () => {
it('should output exception', () => {
const e = errorToString(new Error('message!'));
expect(e).toContain('message!');
});
it('should correctly handle primitive values', () => {
expect(errorToString('message')).toBe('ERROR#message');
expect(errorToString(404)).toBe('ERROR#404');
expect(errorToString(0)).toBe('ERROR#0');
expect(errorToString(true)).toBe('ERROR#true');
expect(errorToString(false)).toBe('ERROR#false');
expect(errorToString(null)).toBe('ERROR#null');
expect(errorToString(undefined)).toBe('ERROR#undefined');
});
});
| {
"end_byte": 1252,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/error_handler_spec.ts"
} |
angular/packages/core/test/transfer_state_spec.ts_0_5294 | /**
* @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_ID as APP_ID_TOKEN, PLATFORM_ID} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {getDocument} from '../src/render3/interfaces/document';
import {makeStateKey, TransferState} from '../src/transfer_state';
function removeScriptTag(doc: Document, id: string) {
doc.getElementById(id)?.remove();
}
function addScriptTag(doc: Document, appId: string, data: object | string) {
const script = doc.createElement('script');
const id = appId + '-state';
script.id = id;
script.setAttribute('type', 'application/json');
script.textContent = typeof data === 'string' ? data : JSON.stringify(data);
// Remove any stale script tags.
removeScriptTag(doc, id);
doc.body.appendChild(script);
}
describe('TransferState', () => {
const APP_ID = 'test-app';
let doc: Document;
const TEST_KEY = makeStateKey<number>('test');
const BOOLEAN_KEY = makeStateKey<boolean>('boolean');
const DELAYED_KEY = makeStateKey<string>('delayed');
beforeEach(() => {
doc = getDocument();
TestBed.configureTestingModule({
providers: [
{provide: APP_ID_TOKEN, useValue: APP_ID},
{provide: PLATFORM_ID, useValue: 'browser'},
],
});
});
afterEach(() => {
removeScriptTag(doc, APP_ID + '-state');
});
it('is initialized from script tag', () => {
addScriptTag(doc, APP_ID, {test: 10});
const transferState: TransferState = TestBed.inject(TransferState);
expect(transferState.get(TEST_KEY, 0)).toBe(10);
});
it('is initialized to empty state if script tag not found', () => {
const transferState: TransferState = TestBed.inject(TransferState);
expect(transferState.get(TEST_KEY, 0)).toBe(0);
});
it('supports adding new keys using set', () => {
const transferState: TransferState = TestBed.inject(TransferState);
transferState.set(TEST_KEY, 20);
expect(transferState.get(TEST_KEY, 0)).toBe(20);
expect(transferState.hasKey(TEST_KEY)).toBe(true);
});
it("supports setting and accessing value '0' via get", () => {
const transferState: TransferState = TestBed.inject(TransferState);
transferState.set(TEST_KEY, 0);
expect(transferState.get(TEST_KEY, 20)).toBe(0);
expect(transferState.hasKey(TEST_KEY)).toBe(true);
});
it("supports setting and accessing value 'false' via get", () => {
const transferState: TransferState = TestBed.inject(TransferState);
transferState.set(BOOLEAN_KEY, false);
expect(transferState.get(BOOLEAN_KEY, true)).toBe(false);
expect(transferState.hasKey(BOOLEAN_KEY)).toBe(true);
});
it("supports setting and accessing value 'null' via get", () => {
const transferState: TransferState = TestBed.inject(TransferState);
transferState.set(TEST_KEY, null);
expect(transferState.get(TEST_KEY, 20 as any)).toBe(null);
expect(transferState.hasKey(TEST_KEY)).toBe(true);
});
it('supports removing keys', () => {
const transferState: TransferState = TestBed.inject(TransferState);
transferState.set(TEST_KEY, 20);
transferState.remove(TEST_KEY);
expect(transferState.get(TEST_KEY, 0)).toBe(0);
expect(transferState.hasKey(TEST_KEY)).toBe(false);
});
it('supports serialization using toJson()', () => {
const transferState: TransferState = TestBed.inject(TransferState);
transferState.set(TEST_KEY, 20);
expect(transferState.toJson()).toBe('{"test":20}');
});
it('calls onSerialize callbacks when calling toJson()', () => {
const transferState: TransferState = TestBed.inject(TransferState);
transferState.set(TEST_KEY, 20);
let value = 'initial';
transferState.onSerialize(DELAYED_KEY, () => value);
value = 'changed';
expect(transferState.toJson()).toBe('{"test":20,"delayed":"changed"}');
});
it('should provide an ability to detect whether the state is empty', () => {
const transferState = TestBed.inject(TransferState);
// The state is empty initially.
expect(transferState.isEmpty).toBeTrue();
transferState.set(TEST_KEY, 20);
expect(transferState.isEmpty).toBeFalse();
transferState.remove(TEST_KEY);
expect(transferState.isEmpty).toBeTrue();
});
it('should encode `<` to avoid breaking out of <script> tag in serialized output', () => {
const transferState = TestBed.inject(TransferState);
// The state is empty initially.
expect(transferState.isEmpty).toBeTrue();
transferState.set(DELAYED_KEY, '</script><script>alert(\'Hello&\' + "World");');
expect(transferState.toJson()).toBe(
`{"delayed":"\\u003C/script>\\u003Cscript>alert('Hello&' + \\"World\\");"}`,
);
});
it('should decode `\\u003C` (<) when restoring stating', () => {
const encodedState = `{"delayed":"\\u003C/script>\\u003Cscript>alert('Hello&' + \\"World\\");"}`;
addScriptTag(doc, APP_ID, encodedState);
const transferState = TestBed.inject(TransferState);
expect(transferState.toJson()).toBe(encodedState);
expect(transferState.get(DELAYED_KEY, null)).toBe(
'</script><script>alert(\'Hello&\' + "World");',
);
});
});
| {
"end_byte": 5294,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/transfer_state_spec.ts"
} |
angular/packages/core/test/change_detection_scheduler_spec.ts_0_1634 | /**
* @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 {PLATFORM_BROWSER_ID} from '@angular/common/src/platform_id';
import {
afterNextRender,
afterRender,
ApplicationRef,
ChangeDetectorRef,
Component,
createComponent,
destroyPlatform,
ElementRef,
EnvironmentInjector,
ErrorHandler,
EventEmitter,
inject,
Input,
NgZone,
Output,
PLATFORM_ID,
provideExperimentalZonelessChangeDetection as provideZonelessChangeDetection,
provideZoneChangeDetection,
signal,
TemplateRef,
Type,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import {toSignal} from '@angular/core/rxjs-interop';
import {
ComponentFixture,
ComponentFixtureAutoDetect,
TestBed,
fakeAsync,
flush,
tick,
} from '@angular/core/testing';
import {bootstrapApplication} from '@angular/platform-browser';
import {withBody} from '@angular/private/testing';
import {BehaviorSubject, firstValueFrom} from 'rxjs';
import {filter, take, tap} from 'rxjs/operators';
import {RuntimeError, RuntimeErrorCode} from '../src/errors';
import {scheduleCallbackWithRafRace} from '../src/util/callback_scheduler';
import {ChangeDetectionSchedulerImpl} from '../src/change_detection/scheduling/zoneless_scheduling_impl';
import {global} from '../src/util/global';
function isStable(injector = TestBed.inject(EnvironmentInjector)): boolean {
return toSignal(injector.get(ApplicationRef).isStable, {requireSync: true, injector})();
} | {
"end_byte": 1634,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/change_detection_scheduler_spec.ts"
} |
angular/packages/core/test/change_detection_scheduler_spec.ts_1636_11443 | describe('Angular with zoneless enabled', () => {
async function createFixture<T>(type: Type<T>): Promise<ComponentFixture<T>> {
const fixture = TestBed.createComponent(type);
await fixture.whenStable();
return fixture;
}
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
{provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID},
],
});
});
describe('notifies scheduler', () => {
it('contributes to application stableness', async () => {
const val = signal('initial');
@Component({template: '{{val()}}', standalone: true})
class TestComponent {
val = val;
}
const fixture = await createFixture(TestComponent);
// Cause another pending CD immediately after render and verify app has not stabilized
await fixture.whenStable().then(() => {
val.set('new');
});
expect(fixture.isStable()).toBeFalse();
await fixture.whenStable();
expect(fixture.isStable()).toBeTrue();
});
it('when signal updates', async () => {
const val = signal('initial');
@Component({template: '{{val()}}', standalone: true})
class TestComponent {
val = val;
}
const fixture = await createFixture(TestComponent);
expect(fixture.nativeElement.innerText).toEqual('initial');
val.set('new');
expect(fixture.isStable()).toBeFalse();
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toEqual('new');
});
it('when using markForCheck()', async () => {
@Component({template: '{{val}}', standalone: true})
class TestComponent {
cdr = inject(ChangeDetectorRef);
val = 'initial';
setVal(val: string) {
this.val = val;
this.cdr.markForCheck();
}
}
const fixture = await createFixture(TestComponent);
expect(fixture.nativeElement.innerText).toEqual('initial');
fixture.componentInstance.setVal('new');
expect(fixture.isStable()).toBe(false);
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toEqual('new');
});
it('on input binding', async () => {
@Component({template: '{{val}}', standalone: true})
class TestComponent {
@Input() val = 'initial';
}
const fixture = await createFixture(TestComponent);
expect(fixture.nativeElement.innerText).toEqual('initial');
fixture.componentRef.setInput('val', 'new');
expect(fixture.isStable()).toBe(false);
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toEqual('new');
});
it('on event listener bound in template', async () => {
@Component({template: '<div (click)="updateVal()">{{val}}</div>', standalone: true})
class TestComponent {
val = 'initial';
updateVal() {
this.val = 'new';
}
}
const fixture = await createFixture(TestComponent);
expect(fixture.nativeElement.innerText).toEqual('initial');
fixture.debugElement
.query((p) => p.nativeElement.tagName === 'DIV')
.triggerEventHandler('click');
expect(fixture.isStable()).toBe(false);
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toEqual('new');
});
it('on event listener bound in host', async () => {
@Component({host: {'(click)': 'updateVal()'}, template: '{{val}}', standalone: true})
class TestComponent {
val = 'initial';
updateVal() {
this.val = 'new';
}
}
const fixture = await createFixture(TestComponent);
expect(fixture.nativeElement.innerText).toEqual('initial');
fixture.debugElement.triggerEventHandler('click');
expect(fixture.isStable()).toBe(false);
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toEqual('new');
});
it('with async pipe', async () => {
@Component({template: '{{val | async}}', standalone: true, imports: [AsyncPipe]})
class TestComponent {
val = new BehaviorSubject('initial');
}
const fixture = await createFixture(TestComponent);
expect(fixture.nativeElement.innerText).toEqual('initial');
fixture.componentInstance.val.next('new');
expect(fixture.isStable()).toBe(false);
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toEqual('new');
});
it('when creating a view', async () => {
@Component({
template: '<ng-template #ref>{{"binding"}}</ng-template>',
standalone: true,
})
class TestComponent {
@ViewChild(TemplateRef) template!: TemplateRef<unknown>;
@ViewChild('ref', {read: ViewContainerRef}) viewContainer!: ViewContainerRef;
createView(): any {
this.viewContainer.createEmbeddedView(this.template);
}
}
const fixture = await createFixture(TestComponent);
fixture.componentInstance.createView();
expect(fixture.isStable()).toBe(false);
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toEqual('binding');
});
it('when inserting a view', async () => {
@Component({
template: '{{"binding"}}',
standalone: true,
})
class DynamicCmp {
elementRef = inject(ElementRef);
}
@Component({
template: '<ng-template #ref></ng-template>',
standalone: true,
})
class TestComponent {
@ViewChild('ref', {read: ViewContainerRef}) viewContainer!: ViewContainerRef;
}
const fixture = await createFixture(TestComponent);
const otherComponent = createComponent(DynamicCmp, {
environmentInjector: TestBed.inject(EnvironmentInjector),
});
fixture.componentInstance.viewContainer.insert(otherComponent.hostView);
expect(fixture.isStable()).toBe(false);
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toEqual('binding');
});
it('when destroying a view (with animations)', async () => {
@Component({
template: '{{"binding"}}',
standalone: true,
})
class DynamicCmp {
elementRef = inject(ElementRef);
}
@Component({
template: '<ng-template #ref></ng-template>',
standalone: true,
})
class TestComponent {
@ViewChild('ref', {read: ViewContainerRef}) viewContainer!: ViewContainerRef;
}
const fixture = await createFixture(TestComponent);
const component = createComponent(DynamicCmp, {
environmentInjector: TestBed.inject(EnvironmentInjector),
});
fixture.componentInstance.viewContainer.insert(component.hostView);
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toEqual('binding');
fixture.componentInstance.viewContainer.remove();
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toEqual('');
const component2 = createComponent(DynamicCmp, {
environmentInjector: TestBed.inject(EnvironmentInjector),
});
fixture.componentInstance.viewContainer.insert(component2.hostView);
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toEqual('binding');
component2.destroy();
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toEqual('');
});
function whenStable(): Promise<void> {
return TestBed.inject(ApplicationRef).whenStable();
}
it(
'when destroying a view (*no* animations)',
withBody('<app></app>', async () => {
destroyPlatform();
let doCheckCount = 0;
let renderHookCalls = 0;
@Component({
template: '{{"binding"}}',
standalone: true,
})
class DynamicCmp {
elementRef = inject(ElementRef);
}
@Component({
selector: 'app',
template: '<ng-template #ref></ng-template>',
standalone: true,
})
class App {
@ViewChild('ref', {read: ViewContainerRef}) viewContainer!: ViewContainerRef;
unused = afterRender(() => {
renderHookCalls++;
});
ngDoCheck() {
doCheckCount++;
}
}
const applicationRef = await bootstrapApplication(App, {
providers: [
provideZonelessChangeDetection(),
{provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID},
],
});
const appViewRef = (applicationRef as any)._views[0] as {context: App; rootNodes: any[]};
await applicationRef.whenStable();
const component2 = createComponent(DynamicCmp, {
environmentInjector: applicationRef.injector,
});
appViewRef.context.viewContainer.insert(component2.hostView);
expect(isStable(applicationRef.injector)).toBe(false);
await applicationRef.whenStable();
component2.destroy();
// destroying the view synchronously removes element from DOM when not using animations
expect(appViewRef.rootNodes[0].innerText).toEqual('');
// Destroying the view notifies scheduler because render hooks need to run
expect(isStable(applicationRef.injector)).toBe(false);
let checkCountBeforeStable = doCheckCount;
let renderCountBeforeStable = renderHookCalls;
await applicationRef.whenStable();
// The view should not have refreshed
expect(doCheckCount).toEqual(checkCountBeforeStable);
// but render hooks should have run
expect(renderHookCalls).toEqual(renderCountBeforeStable + 1);
destroyPlatform();
}),
); | {
"end_byte": 11443,
"start_byte": 1636,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/change_detection_scheduler_spec.ts"
} |
angular/packages/core/test/change_detection_scheduler_spec.ts_11449_20679 | it('when attaching view to ApplicationRef', async () => {
@Component({
selector: 'dynamic-cmp',
template: '{{"binding"}}',
standalone: true,
})
class DynamicCmp {
elementRef = inject(ElementRef);
}
const environmentInjector = TestBed.inject(EnvironmentInjector);
const appRef = TestBed.inject(ApplicationRef);
const component = createComponent(DynamicCmp, {environmentInjector});
const host = document.createElement('div');
host.appendChild(component.instance.elementRef.nativeElement);
expect(host.innerHTML).toEqual('<dynamic-cmp></dynamic-cmp>');
appRef.attachView(component.hostView);
await whenStable();
expect(host.innerHTML).toEqual('<dynamic-cmp>binding</dynamic-cmp>');
const component2 = createComponent(DynamicCmp, {environmentInjector});
// TODO(atscott): Only needed because renderFactory will not run if ApplicationRef has no
// views. This should likely be fixed in ApplicationRef
appRef.attachView(component2.hostView);
appRef.detachView(component.hostView);
// DOM is not synchronously removed because change detection hasn't run
expect(host.innerHTML).toEqual('<dynamic-cmp>binding</dynamic-cmp>');
expect(isStable()).toBe(false);
await whenStable();
expect(host.innerHTML).toEqual('');
host.appendChild(component.instance.elementRef.nativeElement);
// reattaching non-dirty view notifies scheduler because afterRender hooks must run
appRef.attachView(component.hostView);
expect(isStable()).toBe(false);
});
it('when a stable subscription synchronously causes another notification', async () => {
const val = signal('initial');
@Component({template: '{{val()}}', standalone: true})
class TestComponent {
val = val;
}
const fixture = await createFixture(TestComponent);
expect(fixture.nativeElement.innerText).toEqual('initial');
val.set('new');
await TestBed.inject(ApplicationRef)
.isStable.pipe(
filter((stable) => stable),
take(1),
tap(() => val.set('newer')),
)
.toPromise();
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toEqual('newer');
});
it('executes render hooks when a new one is registered', async () => {
let resolveFn: Function;
let calledPromise = new Promise((resolve) => {
resolveFn = resolve;
});
TestBed.runInInjectionContext(() => {
afterNextRender(() => {
resolveFn();
});
});
await expectAsync(calledPromise).toBeResolved();
});
it('executes render hooks without refreshing CheckAlways views', async () => {
let checks = 0;
@Component({
template: '',
standalone: true,
})
class Dummy {
ngDoCheck() {
checks++;
}
}
const fixture = TestBed.createComponent(Dummy);
await fixture.whenStable();
expect(checks).toBe(1);
let resolveFn: Function;
let calledPromise = new Promise((resolve) => {
resolveFn = resolve;
});
TestBed.runInInjectionContext(() => {
afterNextRender(() => {
resolveFn();
});
});
await expectAsync(calledPromise).toBeResolved();
// render hooks was called but component was not refreshed
expect(checks).toBe(1);
});
});
it('can recover when an error is re-thrown by the ErrorHandler', async () => {
const val = signal('initial');
let throwError = false;
@Component({template: '{{val()}}{{maybeThrow()}}', standalone: true})
class TestComponent {
val = val;
maybeThrow() {
if (throwError) {
throw new Error('e');
} else {
return '';
}
}
}
TestBed.configureTestingModule({
providers: [
{
provide: ErrorHandler,
useClass: class extends ErrorHandler {
override handleError(error: any): void {
throw error;
}
},
},
],
});
const fixture = await createFixture(TestComponent);
expect(fixture.nativeElement.innerText).toEqual('initial');
val.set('new');
throwError = true;
// error is thrown in a timeout and can't really be "caught".
// Still need to wrap in expect so it happens in the expect context and doesn't fail the test.
expect(async () => await fixture.whenStable()).not.toThrow();
expect(fixture.nativeElement.innerText).toEqual('initial');
throwError = false;
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toEqual('new');
});
it('change detects embedded view when attached to a host on ApplicationRef and declaration is marked for check', async () => {
@Component({
template: '<ng-template #template><div>{{thing}}</div></ng-template>',
standalone: true,
})
class DynamicCmp {
@ViewChild('template') templateRef!: TemplateRef<{}>;
thing = 'initial';
}
@Component({
template: '',
standalone: true,
})
class Host {
readonly vcr = inject(ViewContainerRef);
}
const fixture = TestBed.createComponent(DynamicCmp);
const host = createComponent(Host, {environmentInjector: TestBed.inject(EnvironmentInjector)});
TestBed.inject(ApplicationRef).attachView(host.hostView);
await fixture.whenStable();
const embeddedViewRef = fixture.componentInstance.templateRef.createEmbeddedView({});
host.instance.vcr.insert(embeddedViewRef);
await fixture.whenStable();
expect(embeddedViewRef.rootNodes[0].innerHTML).toContain('initial');
fixture.componentInstance.thing = 'new';
fixture.changeDetectorRef.markForCheck();
await fixture.whenStable();
expect(embeddedViewRef.rootNodes[0].innerHTML).toContain('new');
});
it('change detects embedded view when attached directly to ApplicationRef and declaration is marked for check', async () => {
@Component({
template: '<ng-template #template><div>{{thing}}</div></ng-template>',
standalone: true,
})
class DynamicCmp {
@ViewChild('template') templateRef!: TemplateRef<{}>;
thing = 'initial';
}
const fixture = TestBed.createComponent(DynamicCmp);
await fixture.whenStable();
const embeddedViewRef = fixture.componentInstance.templateRef.createEmbeddedView({});
TestBed.inject(ApplicationRef).attachView(embeddedViewRef);
await fixture.whenStable();
expect(embeddedViewRef.rootNodes[0].innerHTML).toContain('initial');
fixture.componentInstance.thing = 'new';
fixture.changeDetectorRef.markForCheck();
await fixture.whenStable();
expect(embeddedViewRef.rootNodes[0].innerHTML).toContain('new');
});
it('does not fail when global timing functions are patched and unpatched', async () => {
@Component({template: '', standalone: true})
class App {
cdr = inject(ChangeDetectorRef);
}
let patched = false;
const originalSetTimeout = global.setTimeout;
global.setTimeout = (handler: any) => {
if (!patched) {
throw new Error('no longer patched');
}
originalSetTimeout(handler);
};
patched = true;
const fixture = TestBed.createComponent(App);
await fixture.whenStable();
global.setTimeout = originalSetTimeout;
patched = false;
expect(() => {
// cause another scheduler notification. This should not fail due to `setTimeout` being
// unpatched.
fixture.componentInstance.cdr.markForCheck();
}).not.toThrow();
await fixture.whenStable();
});
it('should not run change detection twice if manual tick called when CD was scheduled', async () => {
let changeDetectionRuns = 0;
TestBed.runInInjectionContext(() => {
afterRender(() => {
changeDetectionRuns++;
});
});
@Component({template: '', standalone: true})
class MyComponent {
cdr = inject(ChangeDetectorRef);
}
const fixture = TestBed.createComponent(MyComponent);
await fixture.whenStable();
expect(changeDetectionRuns).toEqual(1);
// notify the scheduler
fixture.componentInstance.cdr.markForCheck();
// call tick manually
TestBed.inject(ApplicationRef).tick();
await fixture.whenStable();
// ensure we only ran render hook 1 more time rather than once for tick and once for the
// scheduled run
expect(changeDetectionRuns).toEqual(2);
});
it('coalesces microtasks that happen during change detection into a single paint', async () => {
if (!isBrowser) {
return;
}
@Component({
template: '{{thing}}',
standalone: true,
})
class App {
thing = 'initial';
cdr = inject(ChangeDetectorRef);
ngAfterViewInit() {
queueMicrotask(() => {
this.thing = 'new';
this.cdr.markForCheck();
});
}
}
const fixture = TestBed.createComponent(App);
await new Promise<void>((resolve) => scheduleCallbackWithRafRace(resolve));
expect(fixture.nativeElement.innerText).toContain('new');
}); | {
"end_byte": 20679,
"start_byte": 11449,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/change_detection_scheduler_spec.ts"
} |
angular/packages/core/test/change_detection_scheduler_spec.ts_20683_22686 | it('throws a nice error when notifications prevent exiting the event loop (infinite CD)', async () => {
let caughtError: unknown;
let previousHandle = (Zone.root as any)._zoneDelegate.handleError;
(Zone.root as any)._zoneDelegate.handleError = (zone: ZoneSpec, e: unknown) => {
caughtError = e;
};
@Component({
template: '',
standalone: true,
})
class App {
cdr = inject(ChangeDetectorRef);
ngDoCheck() {
queueMicrotask(() => {
this.cdr.markForCheck();
});
}
}
const fixture = TestBed.createComponent(App);
await fixture.whenStable();
expect(caughtError).toBeInstanceOf(RuntimeError);
const runtimeError = caughtError as RuntimeError;
expect(runtimeError.code).toEqual(RuntimeErrorCode.INFINITE_CHANGE_DETECTION);
expect(runtimeError.message).toContain('markForCheck');
expect(runtimeError.message).toContain('notify');
(Zone.root as any)._zoneDelegate.handleError = previousHandle;
});
it('runs inside fakeAsync zone', fakeAsync(() => {
let didRun = false;
@Component({standalone: true, template: ''})
class App {
ngOnInit() {
didRun = true;
}
}
TestBed.createComponent(App);
expect(didRun).toBe(false);
tick();
expect(didRun).toBe(true);
didRun = false;
TestBed.createComponent(App);
expect(didRun).toBe(false);
flush();
expect(didRun).toBe(true);
}));
it('can run inside fakeAsync zone', fakeAsync(() => {
let didRun = false;
@Component({standalone: true, template: ''})
class App {
ngDoCheck() {
didRun = true;
}
}
// create component runs inside the zone and triggers CD as a result
const fixture = TestBed.createComponent(App);
didRun = false;
// schedules change detection
fixture.debugElement.injector.get(ChangeDetectorRef).markForCheck();
expect(didRun).toBe(false);
tick();
expect(didRun).toBe(true);
}));
}); | {
"end_byte": 22686,
"start_byte": 20683,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/change_detection_scheduler_spec.ts"
} |
angular/packages/core/test/change_detection_scheduler_spec.ts_22688_30746 | describe('Angular with scheduler and ZoneJS', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{provide: ComponentFixtureAutoDetect, useValue: true},
{provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID},
],
});
});
it('requires updates inside Angular zone when using ngZoneOnly', async () => {
TestBed.configureTestingModule({
providers: [provideZoneChangeDetection({ignoreChangesOutsideZone: true})],
});
@Component({template: '{{thing()}}', standalone: true})
class App {
thing = signal('initial');
}
const fixture = TestBed.createComponent(App);
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toContain('initial');
TestBed.inject(NgZone).runOutsideAngular(() => {
fixture.componentInstance.thing.set('new');
});
expect(fixture.isStable()).toBe(true);
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toContain('initial');
});
it('will not schedule change detection if listener callback is outside the zone', async () => {
let renders = 0;
TestBed.runInInjectionContext(() => {
afterRender(() => {
renders++;
});
});
@Component({selector: 'component-with-output', template: '', standalone: true})
class ComponentWithOutput {
@Output() out = new EventEmitter();
}
let called = false;
@Component({
standalone: true,
imports: [ComponentWithOutput],
template: '<component-with-output (out)="onOut()" />',
})
class App {
onOut() {
called = true;
}
}
const fixture = TestBed.createComponent(App);
await fixture.whenStable();
const outComponent = fixture.debugElement.query(
(debugNode) => debugNode.providerTokens!.indexOf(ComponentWithOutput) !== -1,
).componentInstance as ComponentWithOutput;
TestBed.inject(NgZone).runOutsideAngular(() => {
outComponent.out.emit();
});
await fixture.whenStable();
expect(renders).toBe(1);
expect(called).toBe(true);
expect(renders).toBe(1);
});
it('updating signal outside of zone still schedules update when in hybrid mode', async () => {
@Component({template: '{{thing()}}', standalone: true})
class App {
thing = signal('initial');
}
const fixture = TestBed.createComponent(App);
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toContain('initial');
TestBed.inject(NgZone).runOutsideAngular(() => {
fixture.componentInstance.thing.set('new');
});
expect(fixture.isStable()).toBe(false);
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toContain('new');
});
it('updating signal in another "Angular" zone schedules update when in hybrid mode', async () => {
@Component({template: '{{thing()}}', standalone: true})
class App {
thing = signal('initial');
}
const fixture = TestBed.createComponent(App);
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toContain('initial');
const differentAngularZone: NgZone = Zone.root.run(() => new NgZone({}));
differentAngularZone.run(() => {
fixture.componentInstance.thing.set('new');
});
expect(fixture.isStable()).toBe(false);
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toContain('new');
});
it('updating signal in a child zone of Angular does not schedule extra CD', async () => {
@Component({template: '{{thing()}}', standalone: true})
class App {
thing = signal('initial');
}
const fixture = TestBed.createComponent(App);
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toContain('initial');
const childZone = TestBed.inject(NgZone).run(() => Zone.current.fork({name: 'child'}));
childZone.run(() => {
fixture.componentInstance.thing.set('new');
expect(TestBed.inject(ChangeDetectionSchedulerImpl)['cancelScheduledCallback']).toBeNull();
});
});
it('updating signal in a child Angular zone of Angular does not schedule extra CD', async () => {
@Component({template: '{{thing()}}', standalone: true})
class App {
thing = signal('initial');
}
const fixture = TestBed.createComponent(App);
await fixture.whenStable();
expect(fixture.nativeElement.innerText).toContain('initial');
const childAngularZone = TestBed.inject(NgZone).run(() => new NgZone({}));
childAngularZone.run(() => {
fixture.componentInstance.thing.set('new');
expect(TestBed.inject(ChangeDetectionSchedulerImpl)['cancelScheduledCallback']).toBeNull();
});
});
it('should not run change detection twice if notified during AppRef.tick', async () => {
TestBed.configureTestingModule({
providers: [
provideZoneChangeDetection({ignoreChangesOutsideZone: false}),
{provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID},
],
});
let changeDetectionRuns = 0;
TestBed.runInInjectionContext(() => {
afterRender(() => {
changeDetectionRuns++;
});
});
@Component({template: '', standalone: true})
class MyComponent {
cdr = inject(ChangeDetectorRef);
ngDoCheck() {
// notify scheduler every time this component is checked
this.cdr.markForCheck();
}
}
const fixture = TestBed.createComponent(MyComponent);
await fixture.whenStable();
expect(changeDetectionRuns).toEqual(1);
// call tick manually
TestBed.inject(ApplicationRef).tick();
await fixture.whenStable();
// ensure we only ran render hook 1 more time rather than once for tick and once for the
// scheduled run
expect(changeDetectionRuns).toEqual(2);
});
it('does not cause double change detection with run coalescing', async () => {
if (isNode) {
return;
}
TestBed.configureTestingModule({
providers: [
provideZoneChangeDetection({runCoalescing: true, ignoreChangesOutsideZone: false}),
],
});
@Component({template: '{{thing()}}', standalone: true})
class App {
thing = signal('initial');
}
const fixture = TestBed.createComponent(App);
await fixture.whenStable();
let ticks = 0;
TestBed.runInInjectionContext(() => {
afterRender(() => {
ticks++;
});
});
fixture.componentInstance.thing.set('new');
await fixture.whenStable();
expect(ticks).toBe(1);
});
it('does not cause double change detection with run coalescing when both schedulers are notified', async () => {
if (isNode) {
return;
}
TestBed.configureTestingModule({
providers: [
provideZoneChangeDetection({runCoalescing: true, ignoreChangesOutsideZone: false}),
],
});
@Component({template: '{{thing()}}', standalone: true})
class App {
thing = signal('initial');
}
const fixture = TestBed.createComponent(App);
await fixture.whenStable();
let ticks = 0;
TestBed.runInInjectionContext(() => {
afterRender(() => {
ticks++;
});
});
// notifies the zoneless scheduler
fixture.componentInstance.thing.set('new');
// notifies the zone scheduler
TestBed.inject(NgZone).run(() => {});
await fixture.whenStable();
expect(ticks).toBe(1);
});
it('can run inside fakeAsync zone', fakeAsync(() => {
TestBed.configureTestingModule({
providers: [provideZoneChangeDetection({scheduleInRootZone: false} as any)],
});
let didRun = false;
@Component({standalone: true, template: ''})
class App {
ngDoCheck() {
didRun = true;
}
}
// create component runs inside the zone and triggers CD as a result
const fixture = TestBed.createComponent(App);
didRun = false;
// schedules change detection
fixture.debugElement.injector.get(ChangeDetectorRef).markForCheck();
expect(didRun).toBe(false);
tick();
expect(didRun).toBe(true);
}));
}); | {
"end_byte": 30746,
"start_byte": 22688,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/change_detection_scheduler_spec.ts"
} |
angular/packages/core/test/runtime_error_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 {RuntimeError, RuntimeErrorCode} from '../src/errors';
describe('RuntimeError utils', () => {
it('should correctly format an error without an error message', () => {
const error = new RuntimeError<RuntimeErrorCode>(RuntimeErrorCode.EXPORT_NOT_FOUND, '');
expect(error.toString()).toBe('Error: NG0301. Find more at https://angular.dev/errors/NG0301');
});
it('should correctly format an error without an error message not adev guide', () => {
const error = new RuntimeError(RuntimeErrorCode.TEMPLATE_STRUCTURE_ERROR, '');
expect(error.toString()).toBe('Error: NG0305');
});
it('should correctly format an error with an error message but without an adev guide', () => {
const error = new RuntimeError(RuntimeErrorCode.TEMPLATE_STRUCTURE_ERROR, 'Some error message');
expect(error.toString()).toBe('Error: NG0305: Some error message');
});
it('should correctly format an error with both an error message and an adev guide', () => {
const error = new RuntimeError(RuntimeErrorCode.EXPORT_NOT_FOUND, 'Some error message');
expect(error.toString()).toBe(
'Error: NG0301: Some error message. Find more at https://angular.dev/errors/NG0301',
);
});
['.', ',', ';', '!', '?'].forEach((character) =>
it(`should not add a period between the error message and the adev guide suffix if the message ends with '${character}'`, () => {
const errorMessage = `Pipe not found${character}`;
const error = new RuntimeError<RuntimeErrorCode>(
RuntimeErrorCode.PIPE_NOT_FOUND,
errorMessage,
);
expect(error.toString()).toBe(
`Error: NG0302: Pipe not found${character} Find more at https://angular.dev/errors/NG0302`,
);
}),
);
});
| {
"end_byte": 1948,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/runtime_error_spec.ts"
} |
angular/packages/core/test/test_bed_effect_spec.ts_0_4564 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ApplicationRef,
ChangeDetectionStrategy,
Component,
effect,
inject,
Injector,
Input,
NgZone,
provideZoneChangeDetection,
signal,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {setUseMicrotaskEffectsByDefault} from '../src/render3/reactivity/effect';
describe('effects in TestBed', () => {
let prev: boolean;
beforeEach(() => {
prev = setUseMicrotaskEffectsByDefault(false);
});
afterEach(() => setUseMicrotaskEffectsByDefault(prev));
it('created in the constructor should run with detectChanges()', () => {
const log: string[] = [];
@Component({
selector: 'test-cmp',
standalone: true,
template: '',
})
class Cmp {
constructor() {
log.push('Ctor');
effect(() => {
log.push('Effect');
});
}
ngDoCheck() {
log.push('DoCheck');
}
}
TestBed.createComponent(Cmp).detectChanges();
expect(log).toEqual([
// The component gets constructed, which creates the effect. Since the effect is created in a
// component, it doesn't get scheduled until the component is first change detected.
'Ctor',
// Next, the first change detection (update pass) happens.
'DoCheck',
// Then the effect runs.
'Effect',
]);
});
it('created in ngOnInit should run with detectChanges()', () => {
const log: string[] = [];
@Component({
selector: 'test-cmp',
standalone: true,
template: '',
})
class Cmp {
private injector = inject(Injector);
constructor() {
log.push('Ctor');
}
ngOnInit() {
effect(
() => {
log.push('Effect');
},
{injector: this.injector},
);
}
ngDoCheck() {
log.push('DoCheck');
}
}
TestBed.createComponent(Cmp).detectChanges();
expect(log).toEqual([
// The component gets constructed.
'Ctor',
// Next, the first change detection (update pass) happens, which creates the effect and
// schedules it for execution.
'DoCheck',
// Then the effect runs.
'Effect',
]);
});
it('will flush effects automatically when using autoDetectChanges', async () => {
const val = signal('initial');
let observed = '';
@Component({
selector: 'test-cmp',
standalone: true,
template: '',
})
class Cmp {
constructor() {
effect(() => {
observed = val();
});
}
}
const fixture = TestBed.createComponent(Cmp);
fixture.autoDetectChanges();
expect(observed).toBe('initial');
val.set('new');
expect(observed).toBe('initial');
await fixture.whenStable();
expect(observed).toBe('new');
});
it('will run an effect with an input signal on the first CD', () => {
let observed: string | null = null;
@Component({
standalone: true,
template: '',
})
class Cmp {
@Input() input!: string;
constructor() {
effect(() => {
observed = this.input;
});
}
}
const fix = TestBed.createComponent(Cmp);
fix.componentRef.setInput('input', 'hello');
fix.detectChanges();
expect(observed as string | null).toBe('hello');
});
it('should run root effects before detectChanges() when in zone mode', async () => {
TestBed.configureTestingModule({
providers: [provideZoneChangeDetection()],
});
const log: string[] = [];
@Component({
standalone: true,
template: `{{ sentinel }}`,
})
class TestCmp {
get sentinel(): string {
log.push('CD');
return '';
}
}
// Instantiate the component and CD it once.
const fix = TestBed.createComponent(TestCmp);
fix.detectChanges();
// Instantiate a root effect and run it once.
const counter = signal(0);
const appRef = TestBed.inject(ApplicationRef);
effect(() => log.push(`effect: ${counter()}`), {injector: appRef.injector});
await appRef.whenStable();
log.length = 0;
// Trigger the effect and call `detectChanges()` on the fixture.
counter.set(1);
fix.detectChanges(false);
// The effect should run before the component CD.
expect(log).toEqual(['effect: 1', 'CD']);
});
});
| {
"end_byte": 4564,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/test_bed_effect_spec.ts"
} |
angular/packages/core/test/directive_lifecycle_integration_spec.ts_0_2517 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
AfterContentChecked,
AfterContentInit,
AfterViewChecked,
AfterViewInit,
Component,
Directive,
DoCheck,
OnChanges,
OnInit,
} from '@angular/core';
import {inject, TestBed} from '@angular/core/testing';
import {Log} from '@angular/core/testing/src/testing_internal';
describe('directive lifecycle integration spec', () => {
let log: Log;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [LifecycleCmp, LifecycleDir, MyComp5],
providers: [Log],
}).overrideComponent(MyComp5, {set: {template: '<div [field]="123" lifecycle></div>'}});
});
beforeEach(inject([Log], (_log: any) => {
log = _log;
}));
it('should invoke lifecycle methods ngOnChanges > ngOnInit > ngDoCheck > ngAfterContentChecked', () => {
const fixture = TestBed.createComponent(MyComp5);
fixture.detectChanges();
expect(log.result()).toEqual(
'ngOnChanges; ngOnInit; ngDoCheck; ngAfterContentInit; ngAfterContentChecked; child_ngDoCheck; ' +
'ngAfterViewInit; ngAfterViewChecked',
);
log.clear();
fixture.detectChanges();
expect(log.result()).toEqual(
'ngDoCheck; ngAfterContentChecked; child_ngDoCheck; ngAfterViewChecked',
);
});
});
@Directive({
selector: '[lifecycle-dir]',
standalone: false,
})
class LifecycleDir implements DoCheck {
constructor(private _log: Log) {}
ngDoCheck() {
this._log.add('child_ngDoCheck');
}
}
@Component({
selector: '[lifecycle]',
inputs: ['field'],
template: `<div lifecycle-dir></div>`,
standalone: false,
})
class LifecycleCmp
implements
OnChanges,
OnInit,
DoCheck,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked
{
field: number = 0;
constructor(private _log: Log) {}
ngOnChanges() {
this._log.add('ngOnChanges');
}
ngOnInit() {
this._log.add('ngOnInit');
}
ngDoCheck() {
this._log.add('ngDoCheck');
}
ngAfterContentInit() {
this._log.add('ngAfterContentInit');
}
ngAfterContentChecked() {
this._log.add('ngAfterContentChecked');
}
ngAfterViewInit() {
this._log.add('ngAfterViewInit');
}
ngAfterViewChecked() {
this._log.add('ngAfterViewChecked');
}
}
@Component({
selector: 'my-comp',
standalone: false,
})
class MyComp5 {}
| {
"end_byte": 2517,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/directive_lifecycle_integration_spec.ts"
} |
angular/packages/core/test/application_init_spec.ts_0_7447 | /**
* @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_INITIALIZER,
ApplicationInitStatus,
Component,
inject,
InjectionToken,
provideAppInitializer,
} from '@angular/core';
import {EMPTY, Observable, Subscriber} from 'rxjs';
import {TestBed} from '../testing';
describe('ApplicationInitStatus', () => {
let status: ApplicationInitStatus;
const runInitializers = () =>
// Cast to `any` to access an internal function for testing purposes.
(status as any).runInitializers();
describe('no initializers', () => {
beforeEach(() => {
TestBed.configureTestingModule({providers: [{provide: APP_INITIALIZER, useValue: []}]});
status = TestBed.inject(ApplicationInitStatus);
});
it('should return true for `done`', () => {
runInitializers();
expect(status.done).toBe(true);
});
it('should return a promise that resolves immediately for `donePromise`', async () => {
runInitializers();
await status.donePromise;
expect(status.done).toBe(true);
});
});
describe('with async promise initializers', () => {
let resolve: (result: any) => void;
let reject: (reason?: any) => void;
let promise: Promise<any>;
let initFnInvoked = false;
beforeEach(() => {
promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
TestBed.configureTestingModule({
providers: [{provide: APP_INITIALIZER, useValue: [() => promise]}],
});
status = TestBed.inject(ApplicationInitStatus);
});
it('should update the status once all async promise initializers are done', async () => {
runInitializers();
setTimeout(() => {
initFnInvoked = true;
resolve(null);
});
expect(status.done).toBe(false);
await status.donePromise;
expect(status.done).toBe(true);
expect(initFnInvoked).toBe(true);
});
it('should handle a case when promise is rejected', async () => {
runInitializers();
setTimeout(() => {
initFnInvoked = true;
reject();
});
expect(status.done).toBe(false);
try {
await status.donePromise;
fail('donePromise should have been rejected when promise is rejected');
} catch {
expect(status.done).toBe(false);
expect(initFnInvoked).toBe(true);
}
});
});
describe('with app initializers represented using observables', () => {
let subscriber: Subscriber<any>;
let initFnInvoked = false;
beforeEach(() => {
const observable = new Observable((res) => {
subscriber = res;
});
TestBed.configureTestingModule({
providers: [{provide: APP_INITIALIZER, useValue: [() => observable]}],
});
status = TestBed.inject(ApplicationInitStatus);
});
it('should update the status once all async observable initializers are completed', async () => {
runInitializers();
setTimeout(() => {
initFnInvoked = true;
subscriber.complete();
});
expect(status.done).toBe(false);
await status.donePromise;
expect(status.done).toBe(true);
expect(initFnInvoked).toBe(true);
});
it('should update the status once all async observable initializers emitted and completed', async () => {
runInitializers();
subscriber.next('one');
subscriber.next('two');
setTimeout(() => {
initFnInvoked = true;
subscriber.complete();
});
await status.donePromise;
expect(status.done).toBe(true);
expect(initFnInvoked).toBe(true);
});
it('should update the status if all async observable initializers are completed synchronously', async () => {
// Create a status instance using an initializer that returns the `EMPTY` Observable
// which completes synchronously upon subscription.
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [{provide: APP_INITIALIZER, useValue: [() => EMPTY]}],
});
status = TestBed.inject(ApplicationInitStatus);
runInitializers();
// Although the Observable completes synchronously, we still queue a promise for
// simplicity. This means that the `done` flag will not be `true` immediately, even
// though there was not actually any asynchronous activity.
expect(status.done).toBe(false);
await status.donePromise;
expect(status.done).toBe(true);
});
it('should handle a case when observable emits an error', async () => {
runInitializers();
setTimeout(() => {
initFnInvoked = true;
subscriber.error();
});
expect(status.done).toBe(false);
try {
await status.donePromise;
fail('donePromise should have been rejected when observable emits an error');
} catch {
expect(status.done).toBe(false);
expect(initFnInvoked).toBe(true);
}
});
});
describe('wrong initializers', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{provide: APP_INITIALIZER, useValue: 'notAnArray'}],
});
});
it('should throw', () => {
expect(() => TestBed.inject(ApplicationInitStatus)).toThrowError(
'NG0209: Unexpected type of the `APP_INITIALIZER` token value ' +
`(expected an array, but got string). ` +
'Please check that the `APP_INITIALIZER` token is configured as a ' +
'`multi: true` provider. Find more at https://angular.dev/errors/NG0209',
);
});
});
describe('provideAppInitializer', () => {
it('should call the provided function when app is initialized', async () => {
let isInitialized = false;
TestBed.configureTestingModule({
providers: [
provideAppInitializer(() => {
isInitialized = true;
}),
],
});
expect(isInitialized).toBeFalse();
await initApp();
expect(isInitialized).toBeTrue();
});
it('should be able to inject dependencies', async () => {
const TEST_TOKEN = new InjectionToken<string>('TEST_TOKEN', {
providedIn: 'root',
factory: () => 'test',
});
let injectedValue!: string;
TestBed.configureTestingModule({
providers: [
provideAppInitializer(() => {
injectedValue = inject(TEST_TOKEN);
}),
],
});
await initApp();
expect(injectedValue).toBe('test');
});
it('should handle async initializer', async () => {
let isInitialized = false;
TestBed.configureTestingModule({
providers: [
provideAppInitializer(async () => {
await new Promise((resolve) => setTimeout(resolve));
isInitialized = true;
}),
],
});
await initApp();
expect(isInitialized).toBeTrue();
});
});
});
async function initApp() {
return await TestBed.inject(ApplicationInitStatus).donePromise;
}
/**
* Typing tests.
*/
@Component({
template: '',
// @ts-expect-error: `provideAppInitializer()` should not work with Component.providers, as it
// wouldn't be executed anyway.
providers: [provideAppInitializer(() => {})],
})
class Test {}
| {
"end_byte": 7447,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/application_init_spec.ts"
} |
angular/packages/core/test/test_bed_spec.ts_0_5782 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {PLATFORM_BROWSER_ID} from '@angular/common/src/platform_id';
import {
APP_INITIALIZER,
ChangeDetectorRef,
Compiler,
Component,
Directive,
ElementRef,
ErrorHandler,
getNgModuleById,
inject,
Inject,
Injectable,
InjectFlags,
InjectionToken,
InjectOptions,
Injector,
Input,
LOCALE_ID,
ModuleWithProviders,
NgModule,
Optional,
Pipe,
PLATFORM_ID,
Type,
ViewChild,
ɵsetClassMetadata as setClassMetadata,
ɵɵdefineComponent as defineComponent,
ɵɵdefineInjector as defineInjector,
ɵɵdefineNgModule as defineNgModule,
ɵɵelementEnd as elementEnd,
ɵɵelementStart as elementStart,
ɵɵsetNgModuleScope as setNgModuleScope,
ɵɵtext as text,
} from '@angular/core';
import {DeferBlockBehavior} from '@angular/core/testing';
import {TestBed, TestBedImpl} from '@angular/core/testing/src/test_bed';
import {By} from '@angular/platform-browser';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {NgModuleType} from '../src/render3';
import {depsTracker} from '../src/render3/deps_tracker/deps_tracker';
import {setClassMetadataAsync} from '../src/render3/metadata';
import {
TEARDOWN_TESTING_MODULE_ON_DESTROY_DEFAULT,
THROW_ON_UNKNOWN_ELEMENTS_DEFAULT,
THROW_ON_UNKNOWN_PROPERTIES_DEFAULT,
} from '../testing/src/test_bed_common';
import {DOCUMENT} from '@angular/common/src/dom_tokens';
const NAME = new InjectionToken<string>('name');
@Injectable({providedIn: 'root'})
class SimpleService {
static ngOnDestroyCalls: number = 0;
id: number = 1;
ngOnDestroy() {
SimpleService.ngOnDestroyCalls++;
}
}
// -- module: HWModule
@Component({
selector: 'hello-world',
template: '<greeting-cmp></greeting-cmp>',
standalone: false,
})
export class HelloWorld {}
// -- module: Greeting
@Component({
selector: 'greeting-cmp',
template: 'Hello {{ name }}',
standalone: false,
})
export class GreetingCmp {
name: string;
constructor(
@Inject(NAME) @Optional() name: string,
@Inject(SimpleService) @Optional() service: SimpleService,
) {
this.name = name || 'nobody!';
}
}
@Component({
selector: 'cmp-with-providers',
template: '<hello-world></hello-world>',
providers: [
SimpleService, //
{provide: NAME, useValue: `from Component`},
],
standalone: false,
})
class CmpWithProviders {}
@NgModule({
declarations: [GreetingCmp],
exports: [GreetingCmp],
})
export class GreetingModule {}
@Component({
selector: 'simple-cmp',
template: '<b>simple</b>',
standalone: false,
})
export class SimpleCmp {}
@Component({
selector: 'with-refs-cmp',
template: '<div #firstDiv></div>',
standalone: false,
})
export class WithRefsCmp {}
@Component({
selector: 'inherited-cmp',
template: 'inherited',
standalone: false,
})
export class InheritedCmp extends SimpleCmp {}
@Directive({
selector: '[hostBindingDir]',
host: {'[id]': 'id'},
standalone: false,
})
export class HostBindingDir {
id = 'one';
}
@Component({
selector: 'component-with-prop-bindings',
template: `
<div hostBindingDir [title]="title" [attr.aria-label]="label"></div>
<p title="( {{ label }} - {{ title }} )" [attr.aria-label]="label" id="[ {{ label }} ] [ {{ title }} ]">
</p>
`,
standalone: false,
})
export class ComponentWithPropBindings {
title = 'some title';
label = 'some label';
}
@Component({
selector: 'simple-app',
template: `
<simple-cmp></simple-cmp> - <inherited-cmp></inherited-cmp>
`,
standalone: false,
})
export class SimpleApp {}
@Component({
selector: 'inline-template',
template: '<p>Hello</p>',
standalone: false,
})
export class ComponentWithInlineTemplate {}
@NgModule({
declarations: [
HelloWorld,
SimpleCmp,
WithRefsCmp,
InheritedCmp,
SimpleApp,
ComponentWithPropBindings,
HostBindingDir,
CmpWithProviders,
],
imports: [GreetingModule],
providers: [{provide: NAME, useValue: 'World!'}],
})
export class HelloWorldModule {}
describe('TestBed', () => {
// This test is extracted to an individual `describe` block to avoid any extra TestBed
// initialization logic that happens in the `beforeEach` functions in other `describe` sections.
it('should apply scopes correctly for components in the lazy-loaded module', () => {
// Reset TestBed to the initial state, emulating an invocation of a first test.
// Check `TestBed.checkGlobalCompilationFinished` for additional info.
TestBedImpl.INSTANCE.globalCompilationChecked = false;
@Component({
selector: 'root',
template: '<div dirA></div>',
standalone: false,
})
class Root {}
@Directive({
selector: '[dirA]',
host: {'title': 'Test title'},
standalone: false,
})
class DirA {}
// Note: this module is not directly reference in the test intentionally.
// Its presence triggers a side-effect of patching correct scopes on the declared components.
@NgModule({
declarations: [Root, DirA],
})
class Module {}
TestBed.configureTestingModule({});
// Trigger TestBed initialization.
TestBed.inject(Injector);
// Emulate the end of a test (trigger module scoping queue flush).
TestBed.resetTestingModule();
// Emulate a lazy-loading scenario by creating a component
// without importing a module into a TestBed testing module.
TestBed.configureTestingModule({});
const fixture = TestBed.createComponent(Root);
fixture.detectChanges();
expect(fixture.nativeElement.firstChild.getAttribute('title')).toEqual('Test title');
});
});
describe('Tes | {
"end_byte": 5782,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/test_bed_spec.ts"
} |
angular/packages/core/test/test_bed_spec.ts_5784_14659 | ed with Standalone types', () => {
beforeEach(() => {
TestBed.resetTestingModule();
});
it('should override dependencies of standalone components', () => {
@Component({
selector: 'dep',
standalone: true,
template: 'main dep',
})
class MainDep {}
@Component({
selector: 'dep',
standalone: true,
template: 'mock dep',
})
class MockDep {}
@Component({
selector: 'app-root',
standalone: true,
imports: [MainDep],
template: '<dep />',
})
class AppComponent {}
TestBed.configureTestingModule({imports: [AppComponent]});
let fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
// No overrides defined, expecting main dependency to be used.
expect(fixture.nativeElement.innerHTML).toBe('<dep>main dep</dep>');
// Emulate an end of a test.
TestBed.resetTestingModule();
// Emulate the start of a next test, make sure previous overrides
// are not persisted across tests.
TestBed.configureTestingModule({imports: [AppComponent]});
TestBed.overrideComponent(AppComponent, {set: {imports: [MockDep]}});
fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
// Main dependency was overridden, expect to see a mock.
expect(fixture.nativeElement.innerHTML).toBe('<dep>mock dep</dep>');
});
it('should override providers on standalone component itself', () => {
const A = new InjectionToken('A');
@Component({
standalone: true,
template: '{{ a }}',
providers: [{provide: A, useValue: 'A'}],
})
class MyStandaloneComp {
constructor(@Inject(A) public a: string) {}
}
// NOTE: the `TestBed.configureTestingModule` is load-bearing here: it instructs
// TestBed to examine and override providers in dependencies.
TestBed.configureTestingModule({imports: [MyStandaloneComp]});
TestBed.overrideProvider(A, {useValue: 'Overridden A'});
const fixture = TestBed.createComponent(MyStandaloneComp);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toBe('Overridden A');
});
it('should override providers on components used as standalone component dependency', () => {
@Injectable()
class Service {
id = 'Service(original)';
}
@Injectable()
class MockService {
id = 'Service(mock)';
}
@Component({
selector: 'dep',
standalone: true,
template: '{{ service.id }}',
providers: [Service],
})
class Dep {
service = inject(Service);
}
@Component({
standalone: true,
template: '<dep />',
imports: [Dep],
})
class MyStandaloneComp {}
TestBed.configureTestingModule({imports: [MyStandaloneComp]});
TestBed.overrideProvider(Service, {useFactory: () => new MockService()});
let fixture = TestBed.createComponent(MyStandaloneComp);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toBe('<dep>Service(mock)</dep>');
// Emulate an end of a test.
TestBed.resetTestingModule();
// Emulate the start of a next test, make sure previous overrides
// are not persisted across tests.
TestBed.configureTestingModule({imports: [MyStandaloneComp]});
fixture = TestBed.createComponent(MyStandaloneComp);
fixture.detectChanges();
// No provider overrides, expect original provider value to be used.
expect(fixture.nativeElement.innerHTML).toBe('<dep>Service(original)</dep>');
});
it('should override providers in standalone component dependencies via overrideProvider', () => {
const A = new InjectionToken('A');
@NgModule({
providers: [{provide: A, useValue: 'A'}],
})
class ComponentDependenciesModule {}
@Component({
standalone: true,
template: '{{ a }}',
imports: [ComponentDependenciesModule],
})
class MyStandaloneComp {
constructor(@Inject(A) public a: string) {}
}
// NOTE: the `TestBed.configureTestingModule` is load-bearing here: it instructs
// TestBed to examine and override providers in dependencies.
TestBed.configureTestingModule({imports: [MyStandaloneComp]});
TestBed.overrideProvider(A, {useValue: 'Overridden A'});
const fixture = TestBed.createComponent(MyStandaloneComp);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toBe('Overridden A');
});
it('should override providers in standalone component dependencies via overrideModule', () => {
const A = new InjectionToken('A');
@NgModule({
providers: [{provide: A, useValue: 'A'}],
})
class ComponentDependenciesModule {}
@Component({
standalone: true,
template: '{{ a }}',
imports: [ComponentDependenciesModule],
})
class MyStandaloneComp {
constructor(@Inject(A) public a: string) {}
}
// NOTE: the `TestBed.configureTestingModule` is *not* needed here, since the TestBed
// knows which NgModule was overridden and needs re-compilation.
TestBed.overrideModule(ComponentDependenciesModule, {
set: {providers: [{provide: A, useValue: 'Overridden A'}]},
});
const fixture = TestBed.createComponent(MyStandaloneComp);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toBe('Overridden A');
});
it('should allow overriding a template of a standalone component', () => {
@Component({
standalone: true,
template: 'Original',
})
class MyStandaloneComp {}
// NOTE: the `TestBed.configureTestingModule` call is *not* required here, since TestBed already
// knows that the `MyStandaloneComp` should be overridden/recompiled.
TestBed.overrideComponent(MyStandaloneComp, {set: {template: 'Overridden'}});
const fixture = TestBed.createComponent(MyStandaloneComp);
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toBe('Overridden');
});
it('should allow overriding the set of directives and pipes used in a standalone component', () => {
@Directive({
selector: '[dir]',
standalone: true,
host: {'[id]': 'id'},
})
class MyStandaloneDirectiveA {
id = 'A';
}
@Directive({
selector: '[dir]',
standalone: true,
host: {'[id]': 'id'},
})
class MyStandaloneDirectiveB {
id = 'B';
}
@Pipe({name: 'pipe', standalone: true})
class MyStandalonePipeA {
transform(value: string): string {
return `transformed ${value} (A)`;
}
}
@Pipe({name: 'pipe', standalone: true})
class MyStandalonePipeB {
transform(value: string): string {
return `transformed ${value} (B)`;
}
}
@Component({
standalone: true,
template: '<div dir>{{ name | pipe }}</div>',
imports: [MyStandalonePipeA, MyStandaloneDirectiveA],
})
class MyStandaloneComp {
name = 'MyStandaloneComp';
}
// NOTE: the `TestBed.configureTestingModule` call is *not* required here, since TestBed
// already knows that the `MyStandaloneComp` should be overridden/recompiled.
TestBed.overrideComponent(MyStandaloneComp, {
set: {imports: [MyStandalonePipeB, MyStandaloneDirectiveB]},
});
const fixture = TestBed.createComponent(MyStandaloneComp);
fixture.detectChanges();
const rootElement = fixture.nativeElement.firstChild;
expect(rootElement.id).toBe('B');
expect(rootElement.innerHTML).toBe('transformed MyStandaloneComp (B)');
});
it('should reflect overrides on imported standalone directive', () => {
@Directive({
selector: '[dir]',
standalone: true,
host: {'[id]': 'id'},
})
class DepStandaloneDirective {
id = 'A';
}
@Component({
selector: 'standalone-cmp',
standalone: true,
template: 'Original MyStandaloneComponent',
})
class DepStandaloneComponent {
id = 'A';
}
@Component({
standalone: true,
template: '<standalone-cmp dir>Hello world!</standalone-cmp>',
imports: [DepStandaloneDirective, DepStandaloneComponent],
})
class RootStandaloneComp {}
// NOTE: the `TestBed.configureTestingModule` call is *not* required here, since TestBed
// already knows which Components/Directives are overridden and should be recompiled.
TestBed.overrideComponent(DepStandaloneComponent, {
set: {template: 'Overridden MyStandaloneComponent'},
});
TestBed.overrideDirective(DepStandaloneDirective, {set: {host: {'[id]': "'Overridden'"}}});
const fixture = TestBed.createComponent(RootStandaloneComp);
fixture.detectChanges();
const rootElement = fixture.nativeElement.firstChild;
expect(rootElement.id).toBe('Overridden');
expect(rootElement.innerHTML).toBe('Overridden MyStandaloneComponent');
});
it('should | {
"end_byte": 14659,
"start_byte": 5784,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/test_bed_spec.ts"
} |
angular/packages/core/test/test_bed_spec.ts_14663_18080 | overridden providers available in pipes', () => {
const TOKEN_A = new InjectionToken('TOKEN_A');
@Pipe({
name: 'testPipe',
standalone: true,
})
class TestPipe {
constructor(@Inject(TOKEN_A) private token: string) {}
transform(value: string): string {
return `transformed ${value} using ${this.token} token`;
}
}
@NgModule({
imports: [TestPipe],
exports: [TestPipe],
providers: [{provide: TOKEN_A, useValue: 'A'}],
})
class TestNgModule {}
@Component({
selector: 'test-component',
standalone: true,
imports: [TestNgModule],
template: `{{ 'original value' | testPipe }}`,
})
class TestComponent {}
TestBed.configureTestingModule({
imports: [TestComponent],
});
TestBed.overrideProvider(TOKEN_A, {useValue: 'Overridden A'});
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const hostElement = fixture.nativeElement.firstChild;
expect(hostElement.textContent).toBe('transformed original value using Overridden A token');
});
describe('NgModules as dependencies', () => {
@Component({
selector: 'test-cmp',
template: '...',
standalone: false,
})
class TestComponent {
testField = 'default';
}
@Component({
selector: 'test-cmp',
template: '...',
standalone: false,
})
class MockTestComponent {
testField = 'overridden';
}
@NgModule({
declarations: [TestComponent],
exports: [TestComponent],
})
class TestModule {}
@Component({
standalone: true,
selector: 'app-root',
template: `<test-cmp #testCmpCtrl></test-cmp>`,
imports: [TestModule],
})
class AppComponent {
@ViewChild('testCmpCtrl', {static: true}) testCmpCtrl!: TestComponent;
}
it('should allow declarations and exports overrides on an imported NgModule', () => {
// replace TestComponent with MockTestComponent
TestBed.overrideModule(TestModule, {
remove: {declarations: [TestComponent], exports: [TestComponent]},
add: {declarations: [MockTestComponent], exports: [MockTestComponent]},
});
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.testCmpCtrl.testField).toBe('overridden');
});
it('should allow removing an import via `overrideModule`', () => {
const fooToken = new InjectionToken<string>('foo');
@NgModule({
providers: [{provide: fooToken, useValue: 'FOO'}],
})
class ImportedModule {}
@NgModule({
imports: [ImportedModule],
})
class ImportingModule {}
TestBed.configureTestingModule({
imports: [ImportingModule],
});
TestBed.overrideModule(ImportingModule, {
remove: {
imports: [ImportedModule],
},
});
expect(TestBed.inject(fooToken, 'BAR')).toBe('BAR');
// Emulate an end of a test.
TestBed.resetTestingModule();
// Emulate the start of a next test, make sure previous overrides
// are not persisted across tests.
TestBed.configureTestingModule({
imports: [ImportingModule],
});
expect(TestBed.inject(fooToken, 'BAR')).toBe('FOO');
});
});
});
describe('Tes | {
"end_byte": 18080,
"start_byte": 14663,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/test_bed_spec.ts"
} |
angular/packages/core/test/test_bed_spec.ts_18082_26995 | ed', () => {
beforeEach(() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({imports: [HelloWorldModule]});
});
it('should compile and render a component', () => {
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
expect(hello.nativeElement).toHaveText('Hello World!');
});
it('should not allow overrides of the `standalone` field', () => {
@Component({
standalone: true,
selector: 'standalone-comp',
template: '...',
})
class StandaloneComponent {}
@Component({
selector: 'non-standalone-comp',
template: '...',
standalone: false,
})
class NonStandaloneComponent {}
@Directive({standalone: true})
class StandaloneDirective {}
@Directive({
standalone: false,
})
class NonStandaloneDirective {}
@Pipe({standalone: true, name: 'test'})
class StandalonePipe {}
@Pipe({
name: 'test',
standalone: false,
})
class NonStandalonePipe {}
const getExpectedError = (typeName: string) =>
`An override for the ${typeName} class has the \`standalone\` flag. ` +
`Changing the \`standalone\` flag via TestBed overrides is not supported.`;
const overrides = [
{set: {standalone: false}},
{add: {standalone: false}},
{remove: {standalone: true}},
];
const scenarios = [
[TestBed.overrideComponent, StandaloneComponent, NonStandaloneComponent],
[TestBed.overrideDirective, StandaloneDirective, NonStandaloneDirective],
[TestBed.overridePipe, StandalonePipe, NonStandalonePipe],
];
overrides.forEach((override) => {
scenarios.forEach(([fn, standaloneType, nonStandaloneType]) => {
expect(() => (fn as Function)(standaloneType, override)).toThrowError(
getExpectedError(standaloneType.name),
);
expect(() => (fn as Function)(nonStandaloneType, override)).toThrowError(
getExpectedError(nonStandaloneType.name),
);
});
});
});
it('should give access to the component instance', () => {
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
expect(hello.componentInstance).toBeInstanceOf(HelloWorld);
});
it('should give the ability to query by css', () => {
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
const greetingByCss = hello.debugElement.query(By.css('greeting-cmp'));
expect(greetingByCss.nativeElement).toHaveText('Hello World!');
expect(greetingByCss.componentInstance).toBeInstanceOf(GreetingCmp);
});
it('should give the ability to trigger the change detection', () => {
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
const greetingByCss = hello.debugElement.query(By.css('greeting-cmp'));
expect(greetingByCss.nativeElement).toHaveText('Hello World!');
greetingByCss.componentInstance.name = 'TestBed!';
hello.detectChanges();
expect(greetingByCss.nativeElement).toHaveText('Hello TestBed!');
});
it('should give the ability to access property bindings on a node', () => {
const fixture = TestBed.createComponent(ComponentWithPropBindings);
fixture.detectChanges();
const divElement = fixture.debugElement.query(By.css('div'));
expect(divElement.properties['id']).toEqual('one');
expect(divElement.properties['title']).toEqual('some title');
});
it('should give the ability to access interpolated properties on a node', () => {
const fixture = TestBed.createComponent(ComponentWithPropBindings);
fixture.detectChanges();
const paragraphEl = fixture.debugElement.query(By.css('p'));
expect(paragraphEl.properties['title']).toEqual('( some label - some title )');
expect(paragraphEl.properties['id']).toEqual('[ some label ] [ some title ]');
});
it('should give access to the node injector', () => {
const fixture = TestBed.createComponent(HelloWorld);
fixture.detectChanges();
const injector = fixture.debugElement.query(By.css('greeting-cmp')).injector;
// from the node injector
const greetingCmp = injector.get(GreetingCmp);
expect(greetingCmp.constructor).toBe(GreetingCmp);
// from the node injector (inherited from a parent node)
const helloWorldCmp = injector.get(HelloWorld);
expect(fixture.componentInstance).toBe(helloWorldCmp);
const nameInjected = injector.get(NAME);
expect(nameInjected).toEqual('World!');
});
it('should give access to the node injector for root node', () => {
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
const injector = hello.debugElement.injector;
// from the node injector
const helloInjected = injector.get(HelloWorld);
expect(helloInjected).toBe(hello.componentInstance);
// from the module injector
const nameInjected = injector.get(NAME);
expect(nameInjected).toEqual('World!');
});
it('should give access to local refs on a node', () => {
const withRefsCmp = TestBed.createComponent(WithRefsCmp);
const firstDivDebugEl = withRefsCmp.debugElement.query(By.css('div'));
// assert that a native element is referenced by a local ref
expect(firstDivDebugEl.references['firstDiv'].tagName.toLowerCase()).toBe('div');
});
it('should give the ability to query by directive', () => {
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
const greetingByDirective = hello.debugElement.query(By.directive(GreetingCmp));
expect(greetingByDirective.componentInstance).toBeInstanceOf(GreetingCmp);
});
it('should allow duplicate NgModule registrations with the same id', () => {
const id = 'registered';
@NgModule({id})
class ModuleA {}
expect(getNgModuleById(id)).toBe(ModuleA);
// This would ordinarily error, if not in a test scenario.
@NgModule({id})
class ModuleB {}
expect(getNgModuleById(id)).toBe(ModuleB);
});
it('allow to override a template', () => {
// use original template when there is no override
let hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
expect(hello.nativeElement).toHaveText('Hello World!');
// override the template
TestBed.resetTestingModule();
TestBed.configureTestingModule({imports: [HelloWorldModule]});
TestBed.overrideComponent(GreetingCmp, {set: {template: `Bonjour {{ name }}`}});
hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
expect(hello.nativeElement).toHaveText('Bonjour World!');
// restore the original template by calling `.resetTestingModule()`
TestBed.resetTestingModule();
TestBed.configureTestingModule({imports: [HelloWorldModule]});
hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
expect(hello.nativeElement).toHaveText('Hello World!');
});
// https://github.com/angular/angular/issues/42734
it('should override a component which is declared in an NgModule which is imported as a `ModuleWithProviders`', () => {
// This test verifies that an overridden component that is declared in an NgModule that has
// been imported as a `ModuleWithProviders` continues to have access to the declaration scope
// of the NgModule.
TestBed.resetTestingModule();
const moduleWithProviders: ModuleWithProviders<HelloWorldModule> = {ngModule: HelloWorldModule};
TestBed.configureTestingModule({imports: [moduleWithProviders]});
TestBed.overrideComponent(HelloWorld, {
set: {template: 'Overridden <greeting-cmp></greeting-cmp>'},
});
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
expect(hello.nativeElement).toHaveText('Overridden Hello World!');
});
it('should run `APP_INITIALIZER` before accessing `LOCALE_ID` provider', () => {
let locale: string = '';
@NgModule({
providers: [
{provide: APP_INITIALIZER, useValue: () => (locale = 'fr-FR'), multi: true},
{provide: LOCALE_ID, useFactory: () => locale},
],
})
class TestModule {}
TestBed.configureTestingModule({imports: [TestModule]});
expect(TestBed.inject(LOCALE_ID)).toBe('fr-FR');
});
it('allow to override a provider', () => {
TestBed.overrideProvider(NAME, {useValue: 'injected World!'});
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
expect(hello.nativeElement).toHaveText('Hello injected World!');
});
it('uses the most recent provider override', () => {
TestBed.overrideProvider(NAME, {useValue: 'injected World!'});
TestBed.overrideProvider(NAME, {useValue: 'injected World a second time!'});
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
expect(hello.nativeElement).toHaveText('Hello injected World a second time!');
});
it('overrid | {
"end_byte": 26995,
"start_byte": 18082,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/test_bed_spec.ts"
} |
angular/packages/core/test/test_bed_spec.ts_26999_36038 | providers in an array', () => {
TestBed.configureTestingModule({
imports: [HelloWorldModule],
providers: [[{provide: NAME, useValue: 'injected World!'}]],
});
TestBed.overrideProvider(NAME, {useValue: 'injected World a second time!'});
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
expect(hello.nativeElement).toHaveText('Hello injected World a second time!');
});
it('should not call ngOnDestroy for a service that was overridden', () => {
SimpleService.ngOnDestroyCalls = 0;
TestBed.overrideProvider(SimpleService, {useValue: {id: 2, ngOnDestroy: () => {}}});
const fixture = TestBed.createComponent(CmpWithProviders);
fixture.detectChanges();
const service = TestBed.inject(SimpleService);
expect(service.id).toBe(2);
fixture.destroy();
// verify that original `ngOnDestroy` was not called
expect(SimpleService.ngOnDestroyCalls).toBe(0);
});
it('should be able to create a fixture if a test module is reset mid-compilation', async () => {
const token = new InjectionToken<number>('value');
@Component({
template: 'hello {{_token}}',
standalone: false,
})
class TestComponent {
constructor(@Inject(token) public _token: number) {}
}
TestBed.resetTestingModule(); // Reset the state from `beforeEach`.
function compile(tokenValue: number) {
return TestBed.configureTestingModule({
declarations: [TestComponent],
providers: [{provide: token, useValue: tokenValue}],
teardown: {destroyAfterEach: true},
}).compileComponents();
}
const initialCompilation = compile(1);
TestBed.resetTestingModule();
await initialCompilation;
await compile(2);
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('hello 2');
});
describe('module overrides using TestBed.overrideModule', () => {
@Component({
selector: 'test-cmp',
template: '...',
standalone: false,
})
class TestComponent {
testField = 'default';
}
@NgModule({
declarations: [TestComponent],
exports: [TestComponent],
})
class TestModule {}
@Component({
selector: 'app-root',
template: `<test-cmp #testCmpCtrl></test-cmp>`,
standalone: false,
})
class AppComponent {
@ViewChild('testCmpCtrl', {static: true}) testCmpCtrl!: TestComponent;
}
@NgModule({
declarations: [AppComponent],
imports: [TestModule],
})
class AppModule {}
@Component({
selector: 'test-cmp',
template: '...',
standalone: false,
})
class MockTestComponent {
testField = 'overwritten';
}
it('should allow declarations override', () => {
TestBed.configureTestingModule({
imports: [AppModule],
});
// replace TestComponent with MockTestComponent
TestBed.overrideModule(TestModule, {
remove: {declarations: [TestComponent], exports: [TestComponent]},
add: {declarations: [MockTestComponent], exports: [MockTestComponent]},
});
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.testCmpCtrl.testField).toBe('overwritten');
});
});
describe('nested module overrides using TestBed.overrideModule', () => {
// Set up an NgModule hierarchy with two modules, A and B, each with their own component.
// Module B additionally re-exports module A. Also declare two mock components which can be
// used in tests to verify that overrides within this hierarchy are working correctly.
// ModuleA content:
@Component({
selector: 'comp-a',
template: 'comp-a content',
standalone: false,
})
class CompA {}
@Component({
selector: 'comp-a',
template: 'comp-a mock content',
standalone: false,
})
class MockCompA {}
@NgModule({
declarations: [CompA],
exports: [CompA],
})
class ModuleA {}
// ModuleB content:
@Component({
selector: 'comp-b',
template: 'comp-b content',
standalone: false,
})
class CompB {}
@Component({
selector: 'comp-b',
template: 'comp-b mock content',
standalone: false,
})
class MockCompB {}
@NgModule({
imports: [ModuleA],
declarations: [CompB],
exports: [CompB, ModuleA],
})
class ModuleB {}
// AppModule content:
@Component({
selector: 'app',
template: `
<comp-a></comp-a>
<comp-b></comp-b>
`,
standalone: false,
})
class App {}
@NgModule({
imports: [ModuleB],
exports: [ModuleB],
})
class AppModule {}
it('should detect nested module override', () => {
TestBed.configureTestingModule({
declarations: [App],
// AppModule -> ModuleB -> ModuleA (to be overridden)
imports: [AppModule],
})
.overrideModule(ModuleA, {
remove: {declarations: [CompA], exports: [CompA]},
add: {declarations: [MockCompA], exports: [MockCompA]},
})
.compileComponents();
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
// CompA is overridden, expect mock content.
expect(fixture.nativeElement.textContent).toContain('comp-a mock content');
// CompB is not overridden, expect original content.
expect(fixture.nativeElement.textContent).toContain('comp-b content');
});
it('should detect chained modules override', () => {
TestBed.configureTestingModule({
declarations: [App],
// AppModule -> ModuleB (to be overridden) -> ModuleA (to be overridden)
imports: [AppModule],
})
.overrideModule(ModuleA, {
remove: {declarations: [CompA], exports: [CompA]},
add: {declarations: [MockCompA], exports: [MockCompA]},
})
.overrideModule(ModuleB, {
remove: {declarations: [CompB], exports: [CompB]},
add: {declarations: [MockCompB], exports: [MockCompB]},
})
.compileComponents();
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
// Both CompA and CompB are overridden, expect mock content for both.
expect(fixture.nativeElement.textContent).toContain('comp-a mock content');
expect(fixture.nativeElement.textContent).toContain('comp-b mock content');
});
});
describe('multi providers', () => {
const multiToken = new InjectionToken<string[]>('multiToken');
const singleToken = new InjectionToken<string>('singleToken');
const multiTokenToOverrideAtModuleLevel = new InjectionToken<string[]>(
'moduleLevelMultiOverride',
);
@NgModule({providers: [{provide: multiToken, useValue: 'valueFromModule', multi: true}]})
class MyModule {}
@NgModule({
providers: [
{provide: singleToken, useValue: 't1'},
{
provide: multiTokenToOverrideAtModuleLevel,
useValue: 'multiTokenToOverrideAtModuleLevelOriginal',
multi: true,
},
{provide: multiToken, useValue: 'valueFromModule2', multi: true},
{provide: multiToken, useValue: 'secondValueFromModule2', multi: true},
],
})
class MyModule2 {}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
MyModule,
{
ngModule: MyModule2,
providers: [
{provide: multiTokenToOverrideAtModuleLevel, useValue: 'override', multi: true},
],
},
],
});
});
it('is preserved when other provider is overridden', () => {
TestBed.overrideProvider(singleToken, {useValue: ''});
expect(TestBed.inject(multiToken).length).toEqual(3);
expect(TestBed.inject(multiTokenToOverrideAtModuleLevel).length).toEqual(2);
expect(TestBed.inject(multiTokenToOverrideAtModuleLevel)).toEqual([
'multiTokenToOverrideAtModuleLevelOriginal',
'override',
]);
});
it('overridden with an array', () => {
const overrideValue = ['override'];
TestBed.overrideProvider(multiToken, {useValue: overrideValue, multi: true});
const value = TestBed.inject(multiToken);
expect(value.length).toEqual(overrideValue.length);
expect(value).toEqual(overrideValue);
});
it('overridden with a non-array', () => {
// This is actually invalid because multi providers return arrays. We have this here so we can
// ensure Ivy behaves the same as VE does currently.
const overrideValue = 'override';
TestBed.overrideProvider(multiToken, {useValue: overrideValue, multi: true});
const value = TestBed.inject(multiToken);
expect(value.length).toEqual(overrideValue.length);
expect(value).toEqual(overrideValue as {} as string[]);
});
});
describe('o | {
"end_byte": 36038,
"start_byte": 26999,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/test_bed_spec.ts"
} |
angular/packages/core/test/test_bed_spec.ts_36042_44588 | ides providers in ModuleWithProviders', () => {
const TOKEN = new InjectionToken<string[]>('token');
@NgModule()
class MyMod {
static multi = false;
static forRoot() {
return {
ngModule: MyMod,
providers: [{provide: TOKEN, multi: MyMod.multi, useValue: 'forRootValue'}],
};
}
}
beforeEach(() => (MyMod.multi = true));
it('when provider is a "regular" provider', () => {
MyMod.multi = false;
@NgModule({imports: [MyMod.forRoot()]})
class MyMod2 {}
TestBed.configureTestingModule({imports: [MyMod2]});
TestBed.overrideProvider(TOKEN, {useValue: ['override']});
expect(TestBed.inject(TOKEN)).toEqual(['override']);
});
it('when provider is multi', () => {
@NgModule({imports: [MyMod.forRoot()]})
class MyMod2 {}
TestBed.configureTestingModule({imports: [MyMod2]});
TestBed.overrideProvider(TOKEN, {useValue: ['override']});
expect(TestBed.inject(TOKEN)).toEqual(['override']);
});
it('restores the original value', () => {
@NgModule({imports: [MyMod.forRoot()]})
class MyMod2 {}
TestBed.configureTestingModule({imports: [MyMod2]});
TestBed.overrideProvider(TOKEN, {useValue: ['override']});
expect(TestBed.inject(TOKEN)).toEqual(['override']);
TestBed.resetTestingModule();
TestBed.configureTestingModule({imports: [MyMod2]});
expect(TestBed.inject(TOKEN)).toEqual(['forRootValue']);
});
});
it('should allow overriding a provider defined via ModuleWithProviders (using TestBed.overrideProvider)', () => {
const serviceOverride = {
get() {
return 'override';
},
};
@Injectable({providedIn: 'root'})
class MyService {
get() {
return 'original';
}
}
@NgModule({})
class MyModule {
static forRoot(): ModuleWithProviders<MyModule> {
return {
ngModule: MyModule,
providers: [MyService],
};
}
}
TestBed.overrideProvider(MyService, {useValue: serviceOverride});
TestBed.configureTestingModule({
imports: [MyModule.forRoot()],
});
const service = TestBed.inject(MyService);
expect(service.get()).toEqual('override');
});
it('should handle overrides for a provider that has `ChangeDetectorRef` as a dependency', () => {
@Injectable({providedIn: 'root'})
class MyService {
token = 'original';
constructor(public cdr: ChangeDetectorRef) {}
}
TestBed.configureTestingModule({});
TestBed.overrideProvider(MyService, {useValue: {token: 'override'}});
const service = TestBed.inject(MyService);
expect(service.token).toBe('override');
});
it('should allow overriding a provider defined via ModuleWithProviders (using TestBed.configureTestingModule)', () => {
const serviceOverride = {
get() {
return 'override';
},
};
@Injectable({providedIn: 'root'})
class MyService {
get() {
return 'original';
}
}
@NgModule({})
class MyModule {
static forRoot(): ModuleWithProviders<MyModule> {
return {
ngModule: MyModule,
providers: [MyService],
};
}
}
TestBed.configureTestingModule({
imports: [MyModule.forRoot()],
providers: [{provide: MyService, useValue: serviceOverride}],
});
const service = TestBed.inject(MyService);
expect(service.get()).toEqual('override');
});
it('should allowing overriding a module with a cyclic structure in its metadata', () => {
class Cyclic {
cycle = this;
constructor(public name: string) {}
}
const CYCLES = new InjectionToken<Cyclic[]>('cycles', {factory: () => []});
@NgModule({
providers: [
{provide: CYCLES, useValue: new Cyclic('a'), multi: true},
{provide: CYCLES, useValue: new Cyclic('b'), multi: true},
],
})
class TestModule {}
TestBed.configureTestingModule({
imports: [TestModule],
})
.overrideModule(TestModule, {
remove: {
providers: [
// Removing the cycle named "a" should result in removing the provider for "a".
// Note: although this removes a different instance than the one provided, metadata
// overrides compare objects by value, not by reference.
{provide: CYCLES, useValue: new Cyclic('a'), multi: true},
// Also attempt to remove a cycle named "B" (which does not exist) to verify that
// objects are correctly compared by value.
{provide: CYCLES, useValue: new Cyclic('B'), multi: true},
],
},
add: {
providers: [{provide: CYCLES, useValue: new Cyclic('c'), multi: true}],
},
})
.compileComponents();
const values = TestBed.inject(CYCLES);
expect(values.map((v) => v.name)).toEqual(['b', 'c']);
});
it('overrides injectable that is using providedIn: AModule', () => {
@NgModule()
class ServiceModule {}
@Injectable({providedIn: ServiceModule})
class Service {}
const fake = 'fake';
TestBed.overrideProvider(Service, {useValue: fake});
// Create an injector whose source is the ServiceModule, not DynamicTestModule.
const ngModuleFactory = TestBed.inject(Compiler).compileModuleSync(ServiceModule);
const injector = ngModuleFactory.create(TestBed.inject(Injector)).injector;
const service = injector.get(Service);
expect(service).toBe(fake);
});
it('allow to override multi provider', () => {
const MY_TOKEN = new InjectionToken('MyProvider');
class MyProvider {}
@Component({
selector: 'my-comp',
template: ``,
standalone: false,
})
class MyComp {
constructor(@Inject(MY_TOKEN) public myProviders: MyProvider[]) {}
}
TestBed.configureTestingModule({
declarations: [MyComp],
providers: [{provide: MY_TOKEN, useValue: {value: 'old provider'}, multi: true}],
});
const multiOverride = {useValue: [{value: 'new provider'}], multi: true};
TestBed.overrideProvider(MY_TOKEN, multiOverride);
const fixture = TestBed.createComponent(MyComp);
expect(fixture.componentInstance.myProviders).toEqual([{value: 'new provider'}]);
});
it('should resolve components that are extended by other components', () => {
// SimpleApp uses SimpleCmp in its template, which is extended by InheritedCmp
const simpleApp = TestBed.createComponent(SimpleApp);
simpleApp.detectChanges();
expect(simpleApp.nativeElement).toHaveText('simple - inherited');
});
it('should not trigger change detection for ComponentA while calling TestBed.createComponent for ComponentB', () => {
const log: string[] = [];
@Component({
selector: 'comp-a',
template: '...',
standalone: false,
})
class CompA {
@Input() inputA: string = '';
ngOnInit() {
log.push('CompA:ngOnInit', this.inputA);
}
}
@Component({
selector: 'comp-b',
template: '...',
standalone: false,
})
class CompB {
@Input() inputB: string = '';
ngOnInit() {
log.push('CompB:ngOnInit', this.inputB);
}
}
TestBed.configureTestingModule({declarations: [CompA, CompB]});
log.length = 0;
const appA = TestBed.createComponent(CompA);
appA.componentInstance.inputA = 'a';
appA.autoDetectChanges();
expect(log).toEqual(['CompA:ngOnInit', 'a']);
log.length = 0;
const appB = TestBed.createComponent(CompB);
appB.componentInstance.inputB = 'b';
appB.autoDetectChanges();
expect(log).toEqual(['CompB:ngOnInit', 'b']);
});
it('should resolve components without async resources synchronously', (done) => {
TestBed.configureTestingModule({
declarations: [ComponentWithInlineTemplate],
})
.compileComponents()
.then(done)
.catch((error) => {
// This should not throw any errors. If an error is thrown, the test will fail.
// Specifically use `catch` here to mark the test as done and *then* throw the error
// so that the test isn't treated as a timeout.
done();
throw error;
});
// Intentionally call `createComponent` before `compileComponents` is resolved. We want this to
// work for components that don't have any async resources (templateUrl, styleUrls).
TestBed.createComponent(ComponentWithInlineTemplate);
});
it('should | {
"end_byte": 44588,
"start_byte": 36042,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/test_bed_spec.ts"
} |
angular/packages/core/test/test_bed_spec.ts_44592_49175 | ble to override the ErrorHandler via an import', () => {
class CustomErrorHandler {}
@NgModule({providers: [{provide: ErrorHandler, useClass: CustomErrorHandler}]})
class ProvidesErrorHandler {}
TestBed.resetTestingModule();
TestBed.configureTestingModule({imports: [ProvidesErrorHandler, HelloWorldModule]});
expect(TestBed.inject(ErrorHandler)).toEqual(jasmine.any(CustomErrorHandler));
});
it('should throw errors in CD', () => {
@Component({
selector: 'my-comp',
template: '',
standalone: false,
})
class MyComp {
name!: {hello: string};
ngOnInit() {
// this should throw because this.name is undefined
this.name.hello = 'hello';
}
}
TestBed.configureTestingModule({declarations: [MyComp]});
expect(() => {
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
}).toThrowError();
});
// TODO(FW-1245): properly fix issue where errors in listeners aren't thrown and don't cause
// tests to fail. This is an issue in both View Engine and Ivy, and may require a breaking
// change to completely fix (since simple re-throwing breaks handlers in ngrx, etc).
xit('should throw errors in listeners', () => {
@Component({
selector: 'my-comp',
template: '<button (click)="onClick()">Click me</button>',
standalone: false,
})
class MyComp {
name!: {hello: string};
onClick() {
// this should throw because this.name is undefined
this.name.hello = 'hello';
}
}
TestBed.configureTestingModule({declarations: [MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(() => {
const button = fixture.nativeElement.querySelector('button');
button.click();
}).toThrowError();
});
it('should allow both the declaration and import of a component into the testing module', () => {
// This test validates that a component (Outer) which is both declared and imported
// (via its module) in the testing module behaves correctly. That is:
//
// 1) the component should be compiled in the scope of its original module.
//
// This condition is tested by having the component (Outer) use another component
// (Inner) within its template. Thus, if it's compiled in the correct scope then the
// text 'Inner' from the template of (Inner) should appear in the result.
//
// 2) the component should be available in the TestingModule scope.
//
// This condition is tested by attempting to use the component (Outer) inside a test
// fixture component (Fixture) which is declared in the testing module only.
@Component({
selector: 'inner',
template: 'Inner',
standalone: false,
})
class Inner {}
@Component({
selector: 'outer',
template: '<inner></inner>',
standalone: false,
})
class Outer {}
@NgModule({
declarations: [Inner, Outer],
})
class Module {}
@Component({
template: '<outer></outer>',
selector: 'fixture',
standalone: false,
})
class Fixture {}
TestBed.configureTestingModule({
declarations: [Outer, Fixture],
imports: [Module],
});
const fixture = TestBed.createComponent(Fixture);
// The Outer component should have its template stamped out, and that template should
// include a correct instance of the Inner component with the 'Inner' text from its
// template.
expect(fixture.nativeElement.innerHTML).toEqual('<outer><inner>Inner</inner></outer>');
});
describe('checking types before compiling them', () => {
@Directive({
selector: 'my-dir',
standalone: false,
})
class MyDir {}
@NgModule()
class MyModule {}
// [decorator, type, overrideFn]
const cases: [string, Type<any>, string][] = [
['Component', MyDir, 'overrideComponent'],
['NgModule', MyDir, 'overrideModule'],
['Pipe', MyModule, 'overridePipe'],
['Directive', MyModule, 'overrideDirective'],
];
cases.forEach(([decorator, type, overrideFn]) => {
it(`should throw an error in case invalid type is used in ${overrideFn} function`, () => {
TestBed.configureTestingModule({declarations: [MyDir]});
expect(() => {
(TestBed as any)[overrideFn](type, {});
TestBed.createComponent(type);
}).toThrowError(new RegExp(`class doesn't have @${decorator} decorator`, 'g'));
});
});
});
describe('d | {
"end_byte": 49175,
"start_byte": 44592,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/test_bed_spec.ts"
} |
angular/packages/core/test/test_bed_spec.ts_49179_55774 | blocks', () => {
/**
* Function returns a class that represents AOT-compiled version of the following Component:
*
* @Component({
* standalone: true,
* imports: [...],
* selector: '...',
* template: '...',
* })
* class ComponentClass {}
*
* This is needed to closer match the behavior of AOT pre-compiled components (compiled
* outside of TestBed) for cases when defer blocks are used.
*/
const getAOTCompiledComponent = (
selector: string,
dependencies: Array<Type<unknown>> = [],
deferrableDependencies: Array<Type<unknown>> = [],
) => {
class ComponentClass {
static ɵfac = () => new ComponentClass();
static ɵcmp = defineComponent({
standalone: true,
type: ComponentClass,
selectors: [[selector]],
decls: 2,
vars: 0,
dependencies,
consts: [['dir']],
template: (rf: any, ctx: any) => {
if (rf & 1) {
elementStart(0, 'div', 0);
text(1, `${selector} cmp!`);
elementEnd();
}
},
});
}
setClassMetadataAsync(
ComponentClass,
function () {
const promises: Array<Promise<Type<unknown>>> = deferrableDependencies.map(
// Emulates a dynamic import, e.g. `import('./cmp-a').then(m => m.CmpA)`
(dep) => new Promise((resolve) => setTimeout(() => resolve(dep))),
);
return promises;
},
function (...deferrableSymbols) {
setClassMetadata(
ComponentClass,
[
{
type: Component,
args: [
{
selector,
standalone: true,
imports: [...dependencies, ...deferrableSymbols],
template: `<div>root cmp!</div>`,
},
],
},
],
null,
null,
);
},
);
return ComponentClass;
};
it('should handle async metadata on root and nested components', async () => {
@Component({
standalone: true,
selector: 'cmp-a',
template: 'CmpA!',
})
class CmpA {}
const NestedAotComponent = getAOTCompiledComponent('nested-cmp', [], [CmpA]);
const RootAotComponent = getAOTCompiledComponent('root', [], [NestedAotComponent]);
TestBed.configureTestingModule({imports: [RootAotComponent]});
TestBed.overrideComponent(RootAotComponent, {
set: {template: `Override of a root template! <nested-cmp />`},
});
TestBed.overrideComponent(NestedAotComponent, {
set: {template: `Override of a nested template! <cmp-a />`},
});
await TestBed.compileComponents();
const fixture = TestBed.createComponent(RootAotComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe(
'Override of a root template! Override of a nested template! CmpA!',
);
});
it('should override providers on dependencies of dynamically loaded components', async () => {
function timer(delay: number): Promise<void> {
return new Promise<void>((resolve) => {
setTimeout(() => resolve(), delay);
});
}
@Injectable({providedIn: 'root'})
class ImportantService {
value = 'original';
}
@NgModule({
providers: [ImportantService],
})
class ThisModuleProvidesService {}
@Component({
standalone: true,
selector: 'child',
imports: [ThisModuleProvidesService],
template: '<h1>{{value}}</h1>',
})
class ChildCmp {
service = inject(ImportantService);
value = this.service.value;
}
@Component({
standalone: true,
selector: 'parent',
imports: [ChildCmp],
template: `
@defer (when true) {
<child />
}
`,
})
class ParentCmp {}
const deferrableDependencies = [ChildCmp];
setClassMetadataAsync(
ParentCmp,
function () {
const promises: Array<Promise<Type<unknown>>> = deferrableDependencies.map(
// Emulates a dynamic import, e.g. `import('./cmp-a').then(m => m.CmpA)`
(dep) => new Promise((resolve) => setTimeout(() => resolve(dep))),
);
return promises;
},
function (...deferrableSymbols) {
setClassMetadata(
ParentCmp,
[
{
type: Component,
args: [
{
selector: 'parent',
standalone: true,
imports: [...deferrableSymbols],
template: `<div>root cmp!</div>`,
},
],
},
],
null,
null,
);
},
);
// Set `PLATFORM_ID` to a browser platform value to trigger defer loading
// while running tests in Node.
const COMMON_PROVIDERS = [{provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID}];
TestBed.configureTestingModule({imports: [ParentCmp], providers: [COMMON_PROVIDERS]});
TestBed.overrideProvider(ImportantService, {useValue: {value: 'overridden'}});
await TestBed.compileComponents();
const fixture = TestBed.createComponent(ParentCmp);
fixture.detectChanges();
await timer(10);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('overridden');
});
it('should allow import overrides on components with async metadata', async () => {
const NestedAotComponent = getAOTCompiledComponent('nested-cmp', [], []);
const RootAotComponent = getAOTCompiledComponent('root', [], []);
TestBed.configureTestingModule({imports: [RootAotComponent]});
TestBed.overrideComponent(RootAotComponent, {
set: {
// Adding an import that was not present originally
imports: [NestedAotComponent],
template: `Override of a root template! <nested-cmp />`,
},
});
await TestBed.compileComponents();
const fixture = TestBed.createComponent(RootAotComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe(
'Override of a root template! nested-cmp cmp!',
);
});
});
describe('AOT | {
"end_byte": 55774,
"start_byte": 49179,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/test_bed_spec.ts"
} |
angular/packages/core/test/test_bed_spec.ts_55778_60743 | -compiled components', () => {
/**
* Function returns a class that represents AOT-compiled version of the following Component:
*
* @Component({
* standalone: true|false,
* imports: [...], // for standalone only
* selector: 'comp',
* templateUrl: './template.ng.html',
* styleUrls: ['./style.css']
* })
* class ComponentClass {}
*
* This is needed to closer match the behavior of AOT pre-compiled components (compiled
* outside of TestBed) without changing TestBed state and/or Component metadata to compile
* them via TestBed with external resources.
*/
const getAOTCompiledComponent = (standalone: boolean = false, dependencies: any[] = []) => {
class ComponentClass {
static ɵfac = () => new ComponentClass();
static ɵcmp = defineComponent({
standalone,
type: ComponentClass,
selectors: [['comp']],
decls: 2,
vars: 0,
dependencies,
consts: [['dir']],
template: (rf: any, ctx: any) => {
if (rf & 1) {
elementStart(0, 'div', 0);
text(1, 'Some template');
elementEnd();
}
},
styles: ['body { margin: 0; }'],
});
}
setClassMetadata(
ComponentClass,
[
{
type: Component,
args: [
{
standalone,
imports: dependencies,
selector: 'comp',
templateUrl: './template.ng.html',
styleUrls: ['./style.css'],
},
],
},
],
null,
null,
);
return ComponentClass;
};
it('should allow to override a provider used in a dependency of a standalone component', () => {
const A = new InjectionToken('A');
@Directive({
selector: '[dir]',
providers: [{provide: A, useValue: 'A'}],
standalone: false,
})
class SomeDir {
constructor(
@Inject(A) private tokenA: string,
private elementRef: ElementRef,
) {}
ngAfterViewInit() {
this.elementRef.nativeElement.innerHTML = this.tokenA;
}
}
const SomeComponent = getAOTCompiledComponent(true, [SomeDir]);
TestBed.configureTestingModule({imports: [SomeComponent]});
TestBed.overrideProvider(A, {useValue: 'Overridden A'});
const fixture = TestBed.createComponent(SomeComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('Overridden A');
});
it('should have an ability to override template', () => {
const SomeComponent = getAOTCompiledComponent();
TestBed.configureTestingModule({declarations: [SomeComponent]});
TestBed.overrideTemplateUsingTestingModule(SomeComponent, 'Template override');
const fixture = TestBed.createComponent(SomeComponent);
expect(fixture.nativeElement.innerHTML).toBe('Template override');
});
it('should have an ability to override template with empty string', () => {
const SomeComponent = getAOTCompiledComponent();
TestBed.configureTestingModule({declarations: [SomeComponent]});
TestBed.overrideTemplateUsingTestingModule(SomeComponent, '');
const fixture = TestBed.createComponent(SomeComponent);
expect(fixture.nativeElement.innerHTML).toBe('');
});
it('should allow component in both in declarations and imports', () => {
const SomeComponent = getAOTCompiledComponent();
// This is an AOT compiled module which declares (but does not export) SomeComponent.
class ModuleClass {
static ɵmod = defineNgModule({
type: ModuleClass,
declarations: [SomeComponent],
});
}
@Component({
template: '<comp></comp>',
selector: 'fixture',
standalone: false,
})
class TestFixture {}
TestBed.configureTestingModule({
// Here, SomeComponent is both declared, and then the module which declares it is
// also imported. This used to be a duplicate declaration error, but is now interpreted
// to mean:
// 1) Compile (or reuse) SomeComponent in the context of its original NgModule
// 2) Make SomeComponent available in the scope of the testing module, even if it wasn't
// originally exported from its NgModule.
//
// This allows TestFixture to use SomeComponent, which is asserted below.
declarations: [SomeComponent, TestFixture],
imports: [ModuleClass],
});
const fixture = TestBed.createComponent(TestFixture);
// The regex avoids any issues with styling attributes.
expect(fixture.nativeElement.innerHTML).toMatch(
/<comp[^>]*><div[^>]*>Some template<\/div><\/comp>/,
);
});
});
describe('resett | {
"end_byte": 60743,
"start_byte": 55778,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/test_bed_spec.ts"
} |
angular/packages/core/test/test_bed_spec.ts_60747_70278 | ng defs', () => {
it('should restore ng defs to their initial states', () => {
@Pipe({
name: 'somePipe',
pure: true,
standalone: false,
})
class SomePipe {
transform(value: string): string {
return `transformed ${value}`;
}
}
@Directive({
selector: 'someDirective',
standalone: false,
})
class SomeDirective {
someProp = 'hello';
}
@Component({
selector: 'comp',
template: 'someText',
standalone: false,
})
class SomeComponent {}
@NgModule({declarations: [SomeComponent]})
class SomeModule {}
TestBed.configureTestingModule({imports: [SomeModule]});
// adding Pipe and Directive via metadata override
TestBed.overrideModule(SomeModule, {
set: {declarations: [SomeComponent, SomePipe, SomeDirective]},
});
TestBed.overrideComponent(SomeComponent, {
set: {template: `<span someDirective>{{'hello' | somePipe}}</span>`},
});
TestBed.createComponent(SomeComponent);
const cmpDefBeforeReset = (SomeComponent as any).ɵcmp;
expect(cmpDefBeforeReset.pipeDefs().length).toEqual(1);
expect(cmpDefBeforeReset.directiveDefs().length).toEqual(2); // directive + component
const scopeBeforeReset = depsTracker.getNgModuleScope(SomeModule as NgModuleType);
expect(scopeBeforeReset.compilation.pipes.size).toEqual(1);
expect(scopeBeforeReset.compilation.directives.size).toEqual(2);
TestBed.resetTestingModule();
const cmpDefAfterReset = (SomeComponent as any).ɵcmp;
expect(cmpDefAfterReset.pipeDefs).toBe(null);
expect(cmpDefAfterReset.directiveDefs).toBe(null);
const scopeAfterReset = depsTracker.getNgModuleScope(SomeModule as NgModuleType);
expect(scopeAfterReset).toEqual({
compilation: {
pipes: new Set(),
directives: new Set([SomeComponent]),
},
exported: {
pipes: new Set(),
directives: new Set(),
},
});
});
it('should cleanup ng defs for classes with no ng annotations (in case of inheritance)', () => {
@Component({
selector: 'someDirective',
template: '...',
standalone: false,
})
class SomeComponent {}
class ComponentWithNoAnnotations extends SomeComponent {}
@Directive({
selector: 'some-directive',
standalone: false,
})
class SomeDirective {}
class DirectiveWithNoAnnotations extends SomeDirective {}
@Pipe({
name: 'some-pipe',
standalone: false,
})
class SomePipe {}
class PipeWithNoAnnotations extends SomePipe {}
TestBed.configureTestingModule({
declarations: [
ComponentWithNoAnnotations,
DirectiveWithNoAnnotations,
PipeWithNoAnnotations,
],
});
TestBed.createComponent(ComponentWithNoAnnotations);
expect(ComponentWithNoAnnotations.hasOwnProperty('ɵcmp')).toBeTruthy();
expect(SomeComponent.hasOwnProperty('ɵcmp')).toBeTruthy();
expect(DirectiveWithNoAnnotations.hasOwnProperty('ɵdir')).toBeTruthy();
expect(SomeDirective.hasOwnProperty('ɵdir')).toBeTruthy();
expect(PipeWithNoAnnotations.hasOwnProperty('ɵpipe')).toBeTruthy();
expect(SomePipe.hasOwnProperty('ɵpipe')).toBeTruthy();
TestBed.resetTestingModule();
// ng defs should be removed from classes with no annotations
expect(ComponentWithNoAnnotations.hasOwnProperty('ɵcmp')).toBeFalsy();
expect(DirectiveWithNoAnnotations.hasOwnProperty('ɵdir')).toBeFalsy();
expect(PipeWithNoAnnotations.hasOwnProperty('ɵpipe')).toBeFalsy();
// ng defs should be preserved on super types
expect(SomeComponent.hasOwnProperty('ɵcmp')).toBeTruthy();
expect(SomeDirective.hasOwnProperty('ɵdir')).toBeTruthy();
expect(SomePipe.hasOwnProperty('ɵpipe')).toBeTruthy();
});
it('should cleanup scopes (configured via `TestBed.configureTestingModule`) between tests', () => {
@Component({
selector: 'child',
template: 'Child comp',
standalone: false,
})
class ChildCmp {}
@Component({
selector: 'root',
template: '<child></child>',
standalone: false,
})
class RootCmp {}
// Case #1: `RootCmp` and `ChildCmp` are both included in the `declarations` field of
// the testing module, so `ChildCmp` is in the scope of `RootCmp`.
TestBed.configureTestingModule({
declarations: [RootCmp, ChildCmp],
});
let fixture = TestBed.createComponent(RootCmp);
fixture.detectChanges();
let childCmpInstance = fixture.debugElement.query(By.directive(ChildCmp));
expect(childCmpInstance.componentInstance).toBeInstanceOf(ChildCmp);
expect(fixture.nativeElement.textContent).toBe('Child comp');
TestBed.resetTestingModule();
const spy = spyOn(console, 'error');
// Case #2: the `TestBed.configureTestingModule` was not invoked, thus the `ChildCmp`
// should not be available in the `RootCmp` scope and no child content should be
// rendered.
fixture = TestBed.createComponent(RootCmp);
// also an error should be logged to the user informing them that
// the child component is not part of the module
expect(spy).toHaveBeenCalledTimes(1);
fixture.detectChanges();
childCmpInstance = fixture.debugElement.query(By.directive(ChildCmp));
expect(childCmpInstance).toBeNull();
expect(fixture.nativeElement.textContent).toBe('');
TestBed.resetTestingModule();
// Case #3: `ChildCmp` is included in the `declarations` field, but `RootCmp` is not,
// so `ChildCmp` is NOT in the scope of `RootCmp` component.
TestBed.configureTestingModule({
declarations: [ChildCmp],
});
fixture = TestBed.createComponent(RootCmp);
fixture.detectChanges();
childCmpInstance = fixture.debugElement.query(By.directive(ChildCmp));
expect(childCmpInstance).toBeNull();
expect(fixture.nativeElement.textContent).toBe('');
});
it('should clean up overridden providers for modules that are imported more than once', () => {
@Injectable()
class Token {
name: string = 'real';
}
@NgModule({
providers: [Token],
})
class Module {}
TestBed.configureTestingModule({imports: [Module, Module]});
TestBed.overrideProvider(Token, {useValue: {name: 'fake'}});
expect(TestBed.inject(Token).name).toEqual('fake');
TestBed.resetTestingModule();
// The providers for the module should have been restored to the original array, with
// no trace of the overridden providers.
expect((Module as any).ɵinj.providers).toEqual([Token]);
});
it('should clean up overridden providers on components whose modules are compiled more than once', async () => {
@Injectable()
class SomeInjectable {
id: string | undefined;
}
@Component({
providers: [SomeInjectable],
standalone: false,
})
class ComponentWithProvider {
constructor(readonly injectable: SomeInjectable) {}
}
@NgModule({declarations: [ComponentWithProvider]})
class MyModule {}
TestBed.configureTestingModule({imports: [MyModule]});
const originalResolver = (ComponentWithProvider as any).ɵcmp.providersResolver;
TestBed.overrideProvider(SomeInjectable, {useValue: {id: 'fake'}});
const compiler = TestBed.inject(Compiler);
await compiler.compileModuleAsync(MyModule);
compiler.compileModuleSync(MyModule);
TestBed.resetTestingModule();
expect((ComponentWithProvider as any).ɵcmp.providersResolver).toEqual(originalResolver);
});
});
describe('overrides provider', () => {
it('with empty provider object', () => {
@Injectable()
class Service {}
TestBed.overrideProvider(Service, {});
// Should be able to get a Service instance because it has no dependencies that can't be
// resolved
expect(TestBed.inject(Service)).toBeDefined();
});
});
it('should handle provider overrides when module imports are provided as a function', () => {
class InjectedString {
value?: string;
}
@Component({
template: '{{injectedString.value}}',
standalone: false,
})
class AppComponent {
constructor(public injectedString: InjectedString) {}
}
@NgModule({})
class DependencyModule {}
// We need to write the compiler output manually here,
// because it depends on code generated by ngcc.
class TestingModule {
static ɵmod = defineNgModule({type: TestingModule});
static ɵinj = defineInjector({imports: [DependencyModule]});
}
setNgModuleScope(TestingModule, {imports: () => [DependencyModule]});
TestBed.configureTestingModule({
imports: [TestingModule],
declarations: [AppComponent],
providers: [{provide: InjectedString, useValue: {value: 'initial'}}],
}).compileComponents();
TestBed.overrideProvider(InjectedString, {useValue: {value: 'changed'}}).compileComponents();
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(fixture!.nativeElement.textContent).toContain('changed');
});
describe('TestBed.inject', () => {
| {
"end_byte": 70278,
"start_byte": 60747,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/test_bed_spec.ts"
} |
angular/packages/core/test/test_bed_spec.ts_70282_73275 | describe('injection flags', () => {
it('should be able to optionally inject a token', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
expect(TestBed.inject(TOKEN, undefined, {optional: true})).toBeNull();
expect(TestBed.inject(TOKEN, undefined, InjectFlags.Optional)).toBeNull();
expect(TestBed.inject(TOKEN, undefined, {optional: true})).toBeNull();
expect(TestBed.inject(TOKEN, undefined, InjectFlags.Optional)).toBeNull();
});
it('should include `null` into the result type when the optional flag is used', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
const flags: InjectOptions = {optional: true};
let result = TestBed.inject(TOKEN, undefined, flags);
expect(result).toBe(null);
// Verify that `null` can be a valid value (from typing standpoint),
// the line below would fail a type check in case the result doesn't
// have `null` in the type.
result = null;
});
it('should be able to use skipSelf injection', () => {
const TOKEN = new InjectionToken<string>('TOKEN');
TestBed.configureTestingModule({
providers: [{provide: TOKEN, useValue: 'from TestBed'}],
});
expect(TestBed.inject(TOKEN)).toBe('from TestBed');
expect(TestBed.inject(TOKEN, undefined, {skipSelf: true, optional: true})).toBeNull();
expect(
TestBed.inject(TOKEN, undefined, InjectFlags.SkipSelf | InjectFlags.Optional),
).toBeNull();
});
});
});
it('should be able to call Testbed.runInInjectionContext in tests', () => {
const expectedValue = 'testValue';
@Injectable({providedIn: 'root'})
class SomeInjectable {
readonly instanceValue = expectedValue;
}
function functionThatUsesInject(): string {
return inject(SomeInjectable).instanceValue;
}
expect(TestBed.runInInjectionContext(functionThatUsesInject)).toEqual(expectedValue);
});
});
describe('TestBed defer block behavior', () => {
beforeEach(() => {
TestBed.resetTestingModule();
});
it('should default defer block behavior to playthrough', () => {
expect(TestBedImpl.INSTANCE.getDeferBlockBehavior()).toBe(DeferBlockBehavior.Playthrough);
});
it('should be able to configure defer block behavior', () => {
TestBed.configureTestingModule({deferBlockBehavior: DeferBlockBehavior.Manual});
expect(TestBedImpl.INSTANCE.getDeferBlockBehavior()).toBe(DeferBlockBehavior.Manual);
});
it('should reset the defer block behavior back to the default when TestBed is reset', () => {
TestBed.configureTestingModule({deferBlockBehavior: DeferBlockBehavior.Manual});
expect(TestBedImpl.INSTANCE.getDeferBlockBehavior()).toBe(DeferBlockBehavior.Manual);
TestBed.resetTestingModule();
expect(TestBedImpl.INSTANCE.getDeferBlockBehavior()).toBe(DeferBlockBehavior.Playthrough);
});
});
describe('TestBed module teardown', ( | {
"end_byte": 73275,
"start_byte": 70282,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/test_bed_spec.ts"
} |
angular/packages/core/test/test_bed_spec.ts_73277_82315 | => {
beforeEach(() => {
TestBed.resetTestingModule();
});
it('should tear down the test module by default', () => {
expect(TestBedImpl.INSTANCE.shouldTearDownTestingModule()).toBe(true);
});
it('should be able to configure the teardown behavior', () => {
TestBed.configureTestingModule({teardown: {destroyAfterEach: false}});
expect(TestBedImpl.INSTANCE.shouldTearDownTestingModule()).toBe(false);
});
it('should reset the teardown behavior back to the default when TestBed is reset', () => {
TestBed.configureTestingModule({teardown: {destroyAfterEach: false}});
expect(TestBedImpl.INSTANCE.shouldTearDownTestingModule()).toBe(false);
TestBed.resetTestingModule();
expect(TestBedImpl.INSTANCE.shouldTearDownTestingModule()).toBe(true);
});
it('should destroy test module providers when test module teardown is enabled', () => {
SimpleService.ngOnDestroyCalls = 0;
TestBed.configureTestingModule({
providers: [SimpleService],
declarations: [GreetingCmp],
teardown: {destroyAfterEach: true},
});
TestBed.createComponent(GreetingCmp);
expect(SimpleService.ngOnDestroyCalls).toBe(0);
TestBed.resetTestingModule();
expect(SimpleService.ngOnDestroyCalls).toBe(1);
});
it('should not error on mocked and partially-implemented `DOCUMENT`', () => {
SimpleService.ngOnDestroyCalls = 0;
TestBed.configureTestingModule({
providers: [SimpleService, {provide: DOCUMENT, useValue: {}}],
teardown: {destroyAfterEach: true},
});
TestBed.inject(SimpleService);
expect(SimpleService.ngOnDestroyCalls).toBe(0);
TestBed.resetTestingModule();
expect(SimpleService.ngOnDestroyCalls).toBe(1);
});
it('should remove the fixture root element from the DOM when module teardown is enabled', () => {
TestBed.configureTestingModule({
declarations: [SimpleCmp],
teardown: {destroyAfterEach: true},
});
const fixture = TestBed.createComponent(SimpleCmp);
const fixtureDocument = fixture.nativeElement.ownerDocument;
expect(fixtureDocument.body.contains(fixture.nativeElement)).toBe(true);
TestBed.resetTestingModule();
expect(fixtureDocument.body.contains(fixture.nativeElement)).toBe(false);
});
it('should re-throw errors that were thrown during fixture cleanup', () => {
@Component({
template: '',
standalone: false,
})
class ThrowsOnDestroy {
ngOnDestroy() {
throw Error('oh no');
}
}
TestBed.configureTestingModule({
declarations: [ThrowsOnDestroy],
teardown: {destroyAfterEach: true},
});
TestBed.createComponent(ThrowsOnDestroy);
const spy = spyOn(console, 'error');
expect(() => TestBed.resetTestingModule()).toThrowError(
'1 component threw errors during cleanup',
);
expect(spy).toHaveBeenCalledTimes(1);
});
it('should not interrupt fixture destruction if an error is thrown', () => {
@Component({
template: '',
standalone: false,
})
class ThrowsOnDestroy {
ngOnDestroy() {
throw Error('oh no');
}
}
TestBed.configureTestingModule({
declarations: [ThrowsOnDestroy],
teardown: {destroyAfterEach: true},
});
for (let i = 0; i < 3; i++) {
TestBed.createComponent(ThrowsOnDestroy);
}
const spy = spyOn(console, 'error');
expect(() => TestBed.resetTestingModule()).toThrowError(
'3 components threw errors during cleanup',
);
expect(spy).toHaveBeenCalledTimes(3);
});
it('should re-throw errors that were thrown during module teardown by default', () => {
@Injectable()
class ThrowsOnDestroy {
ngOnDestroy() {
throw Error('oh no');
}
}
@Component({
template: '',
standalone: false,
})
class App {
constructor(_service: ThrowsOnDestroy) {}
}
TestBed.configureTestingModule({
providers: [ThrowsOnDestroy],
declarations: [App],
teardown: {destroyAfterEach: true},
});
TestBed.createComponent(App);
expect(() => TestBed.resetTestingModule()).toThrowError('oh no');
});
it('should be able to opt out of rethrowing of errors coming from module teardown', () => {
@Injectable()
class ThrowsOnDestroy {
ngOnDestroy() {
throw Error('oh no');
}
}
@Component({
template: '',
standalone: false,
})
class App {
constructor(_service: ThrowsOnDestroy) {}
}
TestBed.configureTestingModule({
providers: [ThrowsOnDestroy],
declarations: [App],
teardown: {destroyAfterEach: true, rethrowErrors: false},
});
TestBed.createComponent(App);
const spy = spyOn(console, 'error');
expect(() => TestBed.resetTestingModule()).not.toThrow();
expect(spy).toHaveBeenCalledTimes(1);
});
it('should remove the styles associated with a test component when the test module is torn down', () => {
@Component({
template: '<span>Hello</span>',
styles: [`span {color: hotpink;}`],
standalone: false,
})
class StyledComp1 {}
@Component({
template: '<div>Hello</div>',
styles: [`div {color: red;}`],
standalone: false,
})
class StyledComp2 {}
TestBed.configureTestingModule({
declarations: [StyledComp1, StyledComp2],
teardown: {destroyAfterEach: true},
});
const fixtures = [TestBed.createComponent(StyledComp1), TestBed.createComponent(StyledComp2)];
const fixtureDocument = fixtures[0].nativeElement.ownerDocument;
const styleCountBefore = fixtureDocument.querySelectorAll('style').length;
// Note that we can only assert that the behavior works as expected by checking that the
// number of stylesheets has decreased. We can't expect that they'll be zero, because there
// may by stylesheets leaking in from other tests that don't use the module teardown
// behavior.
expect(styleCountBefore).toBeGreaterThan(0);
TestBed.resetTestingModule();
expect(fixtureDocument.querySelectorAll('style').length).toBeLessThan(styleCountBefore);
});
it('should remove the fixture root element from the DOM when module teardown is enabled', () => {
TestBed.configureTestingModule({
declarations: [SimpleCmp],
teardown: {destroyAfterEach: true},
});
const fixture = TestBed.createComponent(SimpleCmp);
const fixtureDocument = fixture.nativeElement.ownerDocument;
expect(fixtureDocument.body.contains(fixture.nativeElement)).toBe(true);
TestBed.resetTestingModule();
expect(fixtureDocument.body.contains(fixture.nativeElement)).toBe(false);
});
it('should rethrow errors based on the default teardown behavior', () => {
expect(TestBedImpl.INSTANCE.shouldRethrowTeardownErrors()).toBe(
TEARDOWN_TESTING_MODULE_ON_DESTROY_DEFAULT,
);
});
it('should rethrow errors if the option is omitted and test teardown is enabled', () => {
TestBed.configureTestingModule({teardown: {destroyAfterEach: true}});
expect(TestBedImpl.INSTANCE.shouldRethrowTeardownErrors()).toBe(true);
});
it('should not rethrow errors if the option is omitted and test teardown is disabled', () => {
TestBed.configureTestingModule({teardown: {destroyAfterEach: false}});
expect(TestBedImpl.INSTANCE.shouldRethrowTeardownErrors()).toBe(false);
});
it('should rethrow errors if the option is enabled, but teardown is disabled', () => {
TestBed.configureTestingModule({teardown: {destroyAfterEach: false, rethrowErrors: true}});
expect(TestBedImpl.INSTANCE.shouldRethrowTeardownErrors()).toBe(true);
});
it('should not rethrow errors if the option is disabled, but teardown is enabled', () => {
TestBed.configureTestingModule({teardown: {destroyAfterEach: true, rethrowErrors: false}});
expect(TestBedImpl.INSTANCE.shouldRethrowTeardownErrors()).toBe(false);
});
});
describe('TestBed module `errorOnUnknownElements`', () => {
beforeEach(() => {
TestBed.resetTestingModule();
});
it('should not throw based on the default behavior', () => {
expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownElements()).toBe(
THROW_ON_UNKNOWN_ELEMENTS_DEFAULT,
);
});
it('should not throw if the option is omitted', () => {
TestBed.configureTestingModule({});
expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownElements()).toBe(false);
});
it('should be able to configure the option', () => {
TestBed.configureTestingModule({errorOnUnknownElements: true});
expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownElements()).toBe(true);
});
it('should reset the option back to the default when TestBed is reset', () => {
TestBed.configureTestingModule({errorOnUnknownElements: true});
expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownElements()).toBe(true);
TestBed.resetTestingModule();
expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownElements()).toBe(false);
});
});
describe('TestBed module `errorOnUnkn | {
"end_byte": 82315,
"start_byte": 73277,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/test_bed_spec.ts"
} |
angular/packages/core/test/test_bed_spec.ts_82317_83404 | nProperties`', () => {
beforeEach(() => {
TestBed.resetTestingModule();
});
it('should not throw based on the default behavior', () => {
expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownProperties()).toBe(
THROW_ON_UNKNOWN_PROPERTIES_DEFAULT,
);
});
it('should not throw if the option is omitted', () => {
TestBed.configureTestingModule({});
expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownProperties()).toBe(false);
});
it('should be able to configure the option', () => {
TestBed.configureTestingModule({errorOnUnknownProperties: true});
expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownProperties()).toBe(true);
});
it('should reset the option back to the default when TestBed is reset', () => {
TestBed.configureTestingModule({errorOnUnknownProperties: true});
expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownProperties()).toBe(true);
TestBed.resetTestingModule();
expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownProperties()).toBe(false);
});
});
| {
"end_byte": 83404,
"start_byte": 82317,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/test_bed_spec.ts"
} |
angular/packages/core/test/event_emitter_spec.ts_0_5368 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {TestBed} from '@angular/core/testing';
import {filter, tap} from 'rxjs/operators';
import {EventEmitter} from '../src/event_emitter';
import {ApplicationRef} from '../public_api';
describe('EventEmitter', () => {
let emitter: EventEmitter<number>;
beforeEach(() => {
emitter = new EventEmitter();
});
it('should call the next callback', (done) => {
emitter.subscribe((value: number) => {
expect(value).toEqual(99);
done();
});
emitter.emit(99);
});
it('should call the throw callback', (done) => {
emitter.subscribe({
next: () => {},
error: (error: any) => {
expect(error).toEqual('Boom');
done();
},
});
emitter.error('Boom');
});
it('should work when no throw callback is provided', (done) => {
emitter.subscribe({
next: () => {},
error: () => {
done();
},
});
emitter.error('Boom');
});
it('should call the return callback', (done) => {
emitter.subscribe({
next: () => {},
error: () => {},
complete: () => {
done();
},
});
emitter.complete();
});
it('should subscribe to the wrapper synchronously', () => {
let called = false;
emitter.subscribe({
next: () => {
called = true;
},
});
emitter.emit(99);
expect(called).toBe(true);
});
it('delivers next and error events synchronously', (done) => {
const log: number[] = [];
emitter.subscribe(
(x: number) => {
log.push(x);
expect(log).toEqual([1, 2]);
},
(err: any) => {
log.push(err);
expect(log).toEqual([1, 2, 3, 4]);
done();
},
);
log.push(1);
emitter.emit(2);
log.push(3);
emitter.error(4);
log.push(5);
});
it('delivers next and complete events synchronously', () => {
const log: number[] = [];
emitter.subscribe({
next: (x: number) => {
log.push(x);
expect(log).toEqual([1, 2]);
},
error: undefined,
complete: () => {
log.push(4);
expect(log).toEqual([1, 2, 3, 4]);
},
});
log.push(1);
emitter.emit(2);
log.push(3);
emitter.complete();
log.push(5);
expect(log).toEqual([1, 2, 3, 4, 5]);
});
it('delivers events asynchronously when forced to async mode', (done) => {
const e = new EventEmitter<number>(true);
const log: number[] = [];
e.subscribe((x) => {
log.push(x);
expect(log).toEqual([1, 3, 2]);
done();
});
log.push(1);
e.emit(2);
log.push(3);
});
it('reports whether it has subscribers', () => {
const e = new EventEmitter(false);
expect(e.observers.length > 0).toBe(false);
e.subscribe({next: () => {}});
expect(e.observers.length > 0).toBe(true);
});
it('remove a subscriber subscribed directly to EventEmitter', () => {
const sub = emitter.subscribe();
expect(emitter.observers.length).toBe(1);
sub.unsubscribe();
expect(emitter.observers.length).toBe(0);
});
it('remove a subscriber subscribed after applying operators with pipe()', () => {
const sub = emitter.pipe(filter(() => true)).subscribe();
expect(emitter.observers.length).toBe(1);
sub.unsubscribe();
expect(emitter.observers.length).toBe(0);
});
it('unsubscribing a subscriber invokes the dispose method', (done) => {
const sub = emitter.subscribe();
sub.add(() => done());
sub.unsubscribe();
});
it('unsubscribing a subscriber after applying operators with pipe() invokes the dispose method', (done) => {
const sub = emitter.pipe(filter(() => true)).subscribe();
sub.add(() => done());
sub.unsubscribe();
});
it('error thrown inside an Rx chain propagates to the error handler and disposes the chain', () => {
let errorPropagated = false;
emitter
.pipe(
filter(() => {
throw new Error();
}),
)
.subscribe(
() => {},
(err) => (errorPropagated = true),
);
emitter.next(1);
expect(errorPropagated).toBe(true);
expect(emitter.observers.length).toBe(0);
});
it('error sent by EventEmitter should dispose the Rx chain and remove subscribers', () => {
let errorPropagated = false;
emitter.pipe(filter(() => true)).subscribe(
() => {},
() => (errorPropagated = true),
);
emitter.error(1);
expect(errorPropagated).toBe(true);
expect(emitter.observers.length).toBe(0);
});
it('contributes to app stability', async () => {
const emitter = TestBed.runInInjectionContext(() => new EventEmitter<number>(true));
let emitValue: number;
emitter.subscribe({
next: (v: number) => {
emitValue = v;
},
});
emitter.emit(1);
await TestBed.inject(ApplicationRef).whenStable();
expect(emitValue!).toBeDefined();
expect(emitValue!).toEqual(1);
});
// TODO: vsavkin: add tests cases
// should call dispose on the subscription if generator returns {done:true}
// should call dispose on the subscription on throw
// should call dispose on the subscription on return
});
| {
"end_byte": 5368,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/event_emitter_spec.ts"
} |
angular/packages/core/test/defer_fixture_spec.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 {ɵPLATFORM_BROWSER_ID as PLATFORM_BROWSER_ID} from '@angular/common';
import {Component, PLATFORM_ID, ɵPendingTasks as PendingTasks} from '@angular/core';
import {DeferBlockBehavior, DeferBlockState, TestBed} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers';
@Component({
selector: 'second-deferred-comp',
standalone: true,
template: `<div class="more">More Deferred Component</div>`,
})
class SecondDeferredComp {}
const COMMON_PROVIDERS = [{provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID}];
| {
"end_byte": 769,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/defer_fixture_spec.ts"
} |
angular/packages/core/test/defer_fixture_spec.ts_771_10073 | scribe('DeferFixture', () => {
it('should start in manual behavior mode', async () => {
@Component({
selector: 'defer-comp',
standalone: true,
imports: [SecondDeferredComp],
template: `
<div>
@defer (on immediate) {
<second-deferred-comp />
}
</div>
`,
})
class DeferComp {}
TestBed.configureTestingModule({
imports: [DeferComp, SecondDeferredComp],
providers: COMMON_PROVIDERS,
deferBlockBehavior: DeferBlockBehavior.Manual,
teardown: {destroyAfterEach: true},
});
const componentFixture = TestBed.createComponent(DeferComp);
const el = componentFixture.nativeElement as HTMLElement;
expect(el.querySelectorAll('.more').length).toBe(0);
});
it('should start in manual trigger mode by default', async () => {
@Component({
selector: 'defer-comp',
standalone: true,
imports: [SecondDeferredComp],
template: `
<div>
@defer (on immediate) {
<second-deferred-comp />
}
</div>
`,
})
class DeferComp {}
TestBed.configureTestingModule({
imports: [DeferComp, SecondDeferredComp],
providers: COMMON_PROVIDERS,
});
const componentFixture = TestBed.createComponent(DeferComp);
const el = componentFixture.nativeElement as HTMLElement;
expect(el.querySelectorAll('.more').length).toBe(0);
});
it('should defer load immediately on playthrough', async () => {
@Component({
selector: 'defer-comp',
standalone: true,
imports: [SecondDeferredComp],
template: `
<div>
@defer (when shouldLoad) {
<second-deferred-comp />
}
</div>
`,
})
class DeferComp {
shouldLoad = false;
}
TestBed.configureTestingModule({
imports: [DeferComp, SecondDeferredComp],
providers: COMMON_PROVIDERS,
});
const componentFixture = TestBed.createComponent(DeferComp);
const el = componentFixture.nativeElement as HTMLElement;
expect(el.querySelectorAll('.more').length).toBe(0);
componentFixture.componentInstance.shouldLoad = true;
componentFixture.detectChanges();
await componentFixture.whenStable(); // await loading of deps
expect(el.querySelector('.more')).toBeDefined();
});
it('should not defer load immediately when set to manual', async () => {
@Component({
selector: 'defer-comp',
standalone: true,
imports: [SecondDeferredComp],
template: `
<div>
@defer (when shouldLoad) {
<second-deferred-comp />
}
</div>
`,
})
class DeferComp {
shouldLoad = false;
}
TestBed.configureTestingModule({
imports: [DeferComp, SecondDeferredComp],
providers: COMMON_PROVIDERS,
deferBlockBehavior: DeferBlockBehavior.Manual,
});
const componentFixture = TestBed.createComponent(DeferComp);
const el = componentFixture.nativeElement as HTMLElement;
expect(el.querySelectorAll('.more').length).toBe(0);
componentFixture.componentInstance.shouldLoad = true;
componentFixture.detectChanges();
await componentFixture.whenStable(); // await loading of deps
expect(el.querySelectorAll('.more').length).toBe(0);
});
it('should render a completed defer state', async () => {
@Component({
selector: 'defer-comp',
standalone: true,
imports: [SecondDeferredComp],
template: `
<div>
@defer (on immediate) {
<second-deferred-comp />
}
</div>
`,
})
class DeferComp {}
TestBed.configureTestingModule({
imports: [DeferComp, SecondDeferredComp],
providers: COMMON_PROVIDERS,
deferBlockBehavior: DeferBlockBehavior.Manual,
});
const componentFixture = TestBed.createComponent(DeferComp);
const deferBlock = (await componentFixture.getDeferBlocks())[0];
const el = componentFixture.nativeElement as HTMLElement;
await deferBlock.render(DeferBlockState.Complete);
expect(el.querySelector('.more')).toBeDefined();
});
it('should not wait forever if application is unstable for a long time', async () => {
@Component({
selector: 'defer-comp',
standalone: true,
imports: [SecondDeferredComp],
template: `
<div>
@defer (on immediate) {
<second-deferred-comp />
}
</div>
`,
})
class DeferComp {
constructor(taskService: PendingTasks) {
// Add a task and never remove it. Keeps application unstable forever
taskService.add();
}
}
TestBed.configureTestingModule({
imports: [DeferComp, SecondDeferredComp],
providers: COMMON_PROVIDERS,
deferBlockBehavior: DeferBlockBehavior.Manual,
});
const componentFixture = TestBed.createComponent(DeferComp);
const deferBlock = (await componentFixture.getDeferBlocks())[0];
const el = componentFixture.nativeElement as HTMLElement;
await deferBlock.render(DeferBlockState.Complete);
expect(el.querySelector('.more')).toBeDefined();
});
it('should work with templates that have local refs', async () => {
@Component({
selector: 'defer-comp',
standalone: true,
imports: [SecondDeferredComp],
template: `
<ng-template #template>Hello</ng-template>
<div>
@defer (on immediate) {
<second-deferred-comp />
}
</div>
`,
})
class DeferComp {}
TestBed.configureTestingModule({
imports: [DeferComp, SecondDeferredComp],
providers: COMMON_PROVIDERS,
deferBlockBehavior: DeferBlockBehavior.Manual,
});
const componentFixture = TestBed.createComponent(DeferComp);
const deferBlock = (await componentFixture.getDeferBlocks())[0];
const el = componentFixture.nativeElement as HTMLElement;
await deferBlock.render(DeferBlockState.Complete);
expect(el.querySelector('.more')).toBeDefined();
});
it('should render a placeholder defer state', async () => {
@Component({
selector: 'defer-comp',
standalone: true,
imports: [SecondDeferredComp],
template: `
<div>
@defer (on immediate) {
<second-deferred-comp />
} @placeholder {
<span class="ph">This is placeholder content</span>
}
</div>
`,
})
class DeferComp {}
TestBed.configureTestingModule({
imports: [DeferComp, SecondDeferredComp],
providers: COMMON_PROVIDERS,
deferBlockBehavior: DeferBlockBehavior.Manual,
});
const componentFixture = TestBed.createComponent(DeferComp);
const deferBlock = (await componentFixture.getDeferBlocks())[0];
const el = componentFixture.nativeElement as HTMLElement;
await deferBlock.render(DeferBlockState.Placeholder);
expect(el.querySelectorAll('.more').length).toBe(0);
const phContent = el.querySelector('.ph');
expect(phContent).toBeDefined();
expect(phContent?.innerHTML).toBe('This is placeholder content');
});
it('should render a loading defer state', async () => {
@Component({
selector: 'defer-comp',
standalone: true,
imports: [SecondDeferredComp],
template: `
<div>
@defer (on immediate) {
<second-deferred-comp />
} @loading {
<span class="loading">Loading...</span>
}w
</div>
`,
})
class DeferComp {}
TestBed.configureTestingModule({
imports: [DeferComp, SecondDeferredComp],
providers: COMMON_PROVIDERS,
deferBlockBehavior: DeferBlockBehavior.Manual,
});
const componentFixture = TestBed.createComponent(DeferComp);
const deferBlock = (await componentFixture.getDeferBlocks())[0];
const el = componentFixture.nativeElement as HTMLElement;
await deferBlock.render(DeferBlockState.Loading);
expect(el.querySelectorAll('.more').length).toBe(0);
const loadingContent = el.querySelector('.loading');
expect(loadingContent).toBeDefined();
expect(loadingContent?.innerHTML).toBe('Loading...');
});
it('should render an error defer state', async () => {
@Component({
selector: 'defer-comp',
standalone: true,
imports: [SecondDeferredComp],
template: `
<div>
@defer (on immediate) {
<second-deferred-comp />
} @error {
<span class="error">Flagrant Error!</span>
}
</div>
`,
})
class DeferComp {}
TestBed.configureTestingModule({
imports: [DeferComp, SecondDeferredComp],
providers: COMMON_PROVIDERS,
deferBlockBehavior: DeferBlockBehavior.Manual,
});
const componentFixture = TestBed.createComponent(DeferComp);
const deferBlock = (await componentFixture.getDeferBlocks())[0];
const el = componentFixture.nativeElement as HTMLElement;
await deferBlock.render(DeferBlockState.Error);
expect(el.querySelectorAll('.more').length).toBe(0);
const errContent = el.querySelector('.error');
expect(errContent).toBeDefined();
expect(errContent?.innerHTML).toBe('Flagrant Error!');
});
| {
"end_byte": 10073,
"start_byte": 771,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/defer_fixture_spec.ts"
} |
angular/packages/core/test/defer_fixture_spec.ts_10077_13272 | ('should throw when rendering a template that does not exist', async () => {
@Component({
selector: 'defer-comp',
standalone: true,
imports: [SecondDeferredComp],
template: `
<div>
@defer (on immediate) {
<second-deferred-comp />
}
</div>
`,
})
class DeferComp {}
TestBed.configureTestingModule({
imports: [DeferComp, SecondDeferredComp],
providers: COMMON_PROVIDERS,
deferBlockBehavior: DeferBlockBehavior.Manual,
});
const componentFixture = TestBed.createComponent(DeferComp);
const deferBlock = (await componentFixture.getDeferBlocks())[0];
try {
await deferBlock.render(DeferBlockState.Placeholder);
} catch (er: any) {
expect(er.message).toBe(
'Tried to render this defer block in the `Placeholder` state, but' +
' there was no @placeholder block defined in a template.',
);
}
});
it('should transition between states when `after` and `minimum` are used', async () => {
@Component({
selector: 'defer-comp',
standalone: true,
imports: [SecondDeferredComp],
template: `
<div>
@defer (on immediate) {
Main content
} @loading (after 1s) {
Loading
} @placeholder (minimum 2s) {
Placeholder
}
</div>
`,
})
class DeferComp {}
TestBed.configureTestingModule({
imports: [DeferComp, SecondDeferredComp],
providers: COMMON_PROVIDERS,
deferBlockBehavior: DeferBlockBehavior.Manual,
});
const componentFixture = TestBed.createComponent(DeferComp);
const deferBlock = (await componentFixture.getDeferBlocks())[0];
await deferBlock.render(DeferBlockState.Placeholder);
expect(componentFixture.nativeElement.outerHTML).toContain('Placeholder');
await deferBlock.render(DeferBlockState.Loading);
expect(componentFixture.nativeElement.outerHTML).toContain('Loading');
await deferBlock.render(DeferBlockState.Complete);
expect(componentFixture.nativeElement.outerHTML).toContain('Main');
});
it('should get child defer blocks', async () => {
@Component({
selector: 'deferred-comp',
standalone: true,
imports: [SecondDeferredComp],
template: `
<div>
@defer (on immediate) {
<second-deferred-comp />
}
</div>
`,
})
class DeferredComp {}
@Component({
selector: 'defer-comp',
standalone: true,
imports: [DeferredComp],
template: `
<div>
@defer (on immediate) {
<deferred-comp />
}
</div>
`,
})
class DeferComp {}
TestBed.configureTestingModule({
imports: [DeferComp, DeferredComp, SecondDeferredComp],
providers: COMMON_PROVIDERS,
});
const componentFixture = TestBed.createComponent(DeferComp);
const deferBlock = (await componentFixture.getDeferBlocks())[0];
await deferBlock.render(DeferBlockState.Complete);
const fixtures = await deferBlock.getDeferBlocks();
expect(fixtures.length).toBe(1);
});
});
| {
"end_byte": 13272,
"start_byte": 10077,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/defer_fixture_spec.ts"
} |
angular/packages/core/test/component_fixture_spec.ts_0_2956 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ApplicationRef,
Component,
EnvironmentInjector,
ErrorHandler,
Injectable,
Input,
NgZone,
createComponent,
provideExperimentalZonelessChangeDetection,
signal,
} from '@angular/core';
import {
ComponentFixtureAutoDetect,
ComponentFixtureNoNgZone,
TestBed,
waitForAsync,
withModule,
} from '@angular/core/testing';
import {dispatchEvent} from '@angular/platform-browser/testing/src/browser_util';
import {expect} from '@angular/platform-browser/testing/src/matchers';
@Component({
selector: 'simple-comp',
template: `<span>Original {{simpleBinding}}</span>`,
standalone: false,
})
@Injectable()
class SimpleComp {
simpleBinding: string;
constructor() {
this.simpleBinding = 'Simple';
}
}
@Component({
selector: 'deferred-comp',
standalone: true,
template: `<div>Deferred Component</div>`,
})
class DeferredComp {}
@Component({
selector: 'second-deferred-comp',
standalone: true,
template: `<div>More Deferred Component</div>`,
})
class SecondDeferredComp {}
@Component({
selector: 'my-if-comp',
template: `MyIf(<span *ngIf="showMore">More</span>)`,
standalone: false,
})
@Injectable()
class MyIfComp {
showMore: boolean = false;
}
@Component({
selector: 'autodetect-comp',
template: `<span (click)='click()'>{{text}}</span>`,
standalone: false,
})
class AutoDetectComp {
text: string = '1';
click() {
this.text += '1';
}
}
@Component({
selector: 'async-comp',
template: `<span (click)='click()'>{{text}}</span>`,
standalone: false,
})
class AsyncComp {
text: string = '1';
click() {
Promise.resolve(null).then((_) => {
this.text += '1';
});
}
}
@Component({
selector: 'async-child-comp',
template: '<span>{{localText}}</span>',
standalone: false,
})
class AsyncChildComp {
localText: string = '';
@Input()
set text(value: string) {
Promise.resolve(null).then((_) => {
this.localText = value;
});
}
}
@Component({
selector: 'async-change-comp',
template: `<async-child-comp (click)='click()' [text]="text"></async-child-comp>`,
standalone: false,
})
class AsyncChangeComp {
text: string = '1';
click() {
this.text += '1';
}
}
@Component({
selector: 'async-timeout-comp',
template: `<span (click)='click()'>{{text}}</span>`,
standalone: false,
})
class AsyncTimeoutComp {
text: string = '1';
click() {
setTimeout(() => {
this.text += '1';
}, 10);
}
}
@Component({
selector: 'nested-async-timeout-comp',
template: `<span (click)='click()'>{{text}}</span>`,
standalone: false,
})
class NestedAsyncTimeoutComp {
text: string = '1';
click() {
setTimeout(() => {
setTimeout(() => {
this.text += '1';
}, 10);
}, 10);
}
} | {
"end_byte": 2956,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/component_fixture_spec.ts"
} |
angular/packages/core/test/component_fixture_spec.ts_2958_13084 | describe('ComponentFixture', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [
AutoDetectComp,
AsyncComp,
AsyncTimeoutComp,
NestedAsyncTimeoutComp,
AsyncChangeComp,
MyIfComp,
SimpleComp,
AsyncChildComp,
],
});
}));
it('should auto detect changes if autoDetectChanges is called', () => {
const componentFixture = TestBed.createComponent(AutoDetectComp);
expect(componentFixture.ngZone).not.toBeNull();
componentFixture.autoDetectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
const element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('11');
});
it(
'should auto detect changes if ComponentFixtureAutoDetect is provided as true',
withModule({providers: [{provide: ComponentFixtureAutoDetect, useValue: true}]}, () => {
const componentFixture = TestBed.createComponent(AutoDetectComp);
expect(componentFixture.nativeElement).toHaveText('1');
const element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('11');
}),
);
it('should signal through whenStable when the fixture is stable (autoDetectChanges)', waitForAsync(() => {
const componentFixture = TestBed.createComponent(AsyncComp);
componentFixture.autoDetectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
const element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
// Component is updated asynchronously. Wait for the fixture to become stable
// before checking for new value.
expect(componentFixture.isStable()).toBe(false);
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
expect(componentFixture.nativeElement).toHaveText('11');
});
}));
it('should signal through isStable when the fixture is stable (no autoDetectChanges)', waitForAsync(() => {
const componentFixture = TestBed.createComponent(AsyncComp);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
const element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
// Component is updated asynchronously. Wait for the fixture to become stable
// before checking.
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('11');
});
}));
it(
'should wait for macroTask(setTimeout) while checking for whenStable ' + '(autoDetectChanges)',
waitForAsync(() => {
const componentFixture = TestBed.createComponent(AsyncTimeoutComp);
componentFixture.autoDetectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
const element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
// Component is updated asynchronously. Wait for the fixture to become
// stable before checking for new value.
expect(componentFixture.isStable()).toBe(false);
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
expect(componentFixture.nativeElement).toHaveText('11');
});
}),
);
it(
'should wait for macroTask(setTimeout) while checking for whenStable ' +
'(no autoDetectChanges)',
waitForAsync(() => {
const componentFixture = TestBed.createComponent(AsyncTimeoutComp);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
const element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
// Component is updated asynchronously. Wait for the fixture to become
// stable before checking for new value.
expect(componentFixture.isStable()).toBe(false);
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('11');
});
}),
);
it(
'should wait for nested macroTasks(setTimeout) while checking for whenStable ' +
'(autoDetectChanges)',
waitForAsync(() => {
const componentFixture = TestBed.createComponent(NestedAsyncTimeoutComp);
componentFixture.autoDetectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
const element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
// Component is updated asynchronously. Wait for the fixture to become
// stable before checking for new value.
expect(componentFixture.isStable()).toBe(false);
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
expect(componentFixture.nativeElement).toHaveText('11');
});
}),
);
it(
'should wait for nested macroTasks(setTimeout) while checking for whenStable ' +
'(no autoDetectChanges)',
waitForAsync(() => {
const componentFixture = TestBed.createComponent(NestedAsyncTimeoutComp);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
const element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
expect(componentFixture.nativeElement).toHaveText('1');
// Component is updated asynchronously. Wait for the fixture to become
// stable before checking for new value.
expect(componentFixture.isStable()).toBe(false);
componentFixture.whenStable().then((waited) => {
expect(waited).toBe(true);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('11');
});
}),
);
it('should stabilize after async task in change detection (autoDetectChanges)', waitForAsync(() => {
const componentFixture = TestBed.createComponent(AsyncChangeComp);
componentFixture.autoDetectChanges();
componentFixture.whenStable().then((_) => {
expect(componentFixture.nativeElement).toHaveText('1');
const element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
componentFixture.whenStable().then((_) => {
expect(componentFixture.nativeElement).toHaveText('11');
});
});
}));
it('should stabilize after async task in change detection(no autoDetectChanges)', waitForAsync(() => {
const componentFixture = TestBed.createComponent(AsyncChangeComp);
componentFixture.detectChanges();
componentFixture.whenStable().then((_) => {
// Run detectChanges again so that stabilized value is reflected in the
// DOM.
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('1');
const element = componentFixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
componentFixture.detectChanges();
componentFixture.whenStable().then((_) => {
// Run detectChanges again so that stabilized value is reflected in
// the DOM.
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('11');
});
});
}));
it('throws errors that happen during detectChanges', () => {
@Component({
template: '',
standalone: true,
})
class App {
ngOnInit() {
throw new Error();
}
}
const fixture = TestBed.createComponent(App);
expect(() => fixture.detectChanges()).toThrow();
});
describe('errors during ApplicationRef.tick', () => {
@Component({
template: '',
standalone: true,
})
class ThrowingThing {
ngOnInit() {
throw new Error();
}
}
@Component({
template: '',
standalone: true,
})
class Blank {}
it('rejects whenStable promise when errors happen during appRef.tick', async () => {
const fixture = TestBed.createComponent(Blank);
const throwingThing = createComponent(ThrowingThing, {
environmentInjector: TestBed.inject(EnvironmentInjector),
});
TestBed.inject(ApplicationRef).attachView(throwingThing.hostView);
await expectAsync(fixture.whenStable()).toBeRejected();
});
it('can opt-out of rethrowing application errors and rejecting whenStable promises', async () => {
TestBed.configureTestingModule({rethrowApplicationErrors: false});
const fixture = TestBed.createComponent(Blank);
const throwingThing = createComponent(ThrowingThing, {
environmentInjector: TestBed.inject(EnvironmentInjector),
});
TestBed.inject(ApplicationRef).attachView(throwingThing.hostView);
await expectAsync(fixture.whenStable()).toBeResolved();
});
});
describe('defer', () => {
it('should return all defer blocks in the component', async () => {
@Component({
selector: 'defer-comp',
standalone: true,
imports: [DeferredComp, SecondDeferredComp],
template: `<div>
@defer (on immediate) {
<DeferredComp />
}
@defer (on idle) {
<SecondDeferredComp />
}
</div>`,
})
class DeferComp {}
const componentFixture = TestBed.createComponent(DeferComp);
const deferBlocks = await componentFixture.getDeferBlocks();
expect(deferBlocks.length).toBe(2);
});
}); | {
"end_byte": 13084,
"start_byte": 2958,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/component_fixture_spec.ts"
} |
angular/packages/core/test/component_fixture_spec.ts_13088_18686 | describe('No NgZone', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{provide: ComponentFixtureNoNgZone, useValue: true}],
});
});
it('calling autoDetectChanges raises an error', () => {
const componentFixture = TestBed.createComponent(SimpleComp);
expect(() => {
componentFixture.autoDetectChanges();
}).toThrowError(/Cannot call autoDetectChanges when ComponentFixtureNoNgZone is set/);
});
it('should instantiate a component with valid DOM', waitForAsync(() => {
const componentFixture = TestBed.createComponent(SimpleComp);
expect(componentFixture.ngZone).toBeNull();
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('Original Simple');
}));
it('should allow changing members of the component', waitForAsync(() => {
const componentFixture = TestBed.createComponent(MyIfComp);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('MyIf()');
componentFixture.componentInstance.showMore = true;
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('MyIf(More)');
}));
it('throws errors that happen during detectChanges', () => {
@Component({
template: '',
standalone: true,
})
class App {
ngOnInit() {
throw new Error();
}
}
const fixture = TestBed.createComponent(App);
expect(() => fixture.detectChanges()).toThrow();
});
});
it('reports errors from autoDetect change detection to error handler', () => {
let throwError = false;
@Component({
template: '',
standalone: false,
})
class TestComponent {
ngDoCheck() {
if (throwError) {
throw new Error();
}
}
}
const fixture = TestBed.createComponent(TestComponent);
fixture.autoDetectChanges();
const errorHandler = TestBed.inject(ErrorHandler);
const spy = spyOn(errorHandler, 'handleError').and.callThrough();
throwError = true;
TestBed.inject(NgZone).run(() => {});
expect(spy).toHaveBeenCalled();
});
it('reports errors from checkNoChanges in autoDetect to error handler', () => {
let throwError = false;
@Component({
template: '{{thing}}',
standalone: false,
})
class TestComponent {
thing = 'initial';
ngAfterViewChecked() {
if (throwError) {
this.thing = 'new';
}
}
}
const fixture = TestBed.createComponent(TestComponent);
fixture.autoDetectChanges();
const errorHandler = TestBed.inject(ErrorHandler);
const spy = spyOn(errorHandler, 'handleError').and.callThrough();
throwError = true;
TestBed.inject(NgZone).run(() => {});
expect(spy).toHaveBeenCalled();
});
});
describe('ComponentFixture with zoneless', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideExperimentalZonelessChangeDetection(),
{provide: ErrorHandler, useValue: {handleError: () => {}}},
],
});
});
it('will not refresh CheckAlways views when detectChanges is called if not marked dirty', () => {
@Component({standalone: true, template: '{{signalThing()}}|{{regularThing}}'})
class CheckAlwaysCmp {
regularThing = 'initial';
signalThing = signal('initial');
}
const fixture = TestBed.createComponent(CheckAlwaysCmp);
// components are created dirty
fixture.detectChanges();
expect(fixture.nativeElement.innerText).toEqual('initial|initial');
fixture.componentInstance.regularThing = 'new';
// Expression changed after checked
expect(() => fixture.detectChanges()).toThrow();
expect(fixture.nativeElement.innerText).toEqual('initial|initial');
fixture.componentInstance.signalThing.set('new');
fixture.detectChanges();
expect(fixture.nativeElement.innerText).toEqual('new|new');
});
it('throws errors that happen during detectChanges', () => {
@Component({
template: '',
standalone: true,
})
class App {
ngOnInit() {
throw new Error();
}
}
const fixture = TestBed.createComponent(App);
expect(() => fixture.detectChanges()).toThrow();
});
it('rejects whenStable promise when errors happen during detectChanges', async () => {
@Component({
template: '',
standalone: true,
})
class App {
ngOnInit() {
throw new Error();
}
}
const fixture = TestBed.createComponent(App);
await expectAsync(fixture.whenStable()).toBeRejected();
});
it('can disable checkNoChanges', () => {
@Component({
template: '{{thing}}',
standalone: true,
})
class App {
thing = 1;
ngAfterViewChecked() {
++this.thing;
}
}
const fixture = TestBed.createComponent(App);
expect(() => fixture.detectChanges(false /*checkNoChanges*/)).not.toThrow();
// still throws if checkNoChanges is not disabled
expect(() => fixture.detectChanges()).toThrowError(/ExpressionChanged/);
});
it('runs change detection when autoDetect is false', () => {
@Component({
template: '{{thing()}}',
standalone: true,
})
class App {
thing = signal(1);
}
const fixture = TestBed.createComponent(App);
fixture.autoDetectChanges(false);
fixture.componentInstance.thing.set(2);
fixture.detectChanges();
expect(fixture.nativeElement.innerText).toBe('2');
});
}); | {
"end_byte": 18686,
"start_byte": 13088,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/component_fixture_spec.ts"
} |
angular/packages/core/test/application_module_spec.ts_0_2761 | /**
* @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 {DEFAULT_CURRENCY_CODE, LOCALE_ID} from '@angular/core';
import {inject} from '@angular/core/testing';
import {DEFAULT_LOCALE_ID} from '../src/i18n/localization';
import {getLocaleId, setLocaleId} from '../src/render3';
import {global} from '../src/util/global';
import {TestBed} from '../testing';
describe('Application module', () => {
beforeEach(() => {
setLocaleId(DEFAULT_LOCALE_ID);
});
it('should set the default locale to "en-US"', inject([LOCALE_ID], (defaultLocale: string) => {
expect(defaultLocale).toEqual('en-US');
}));
it('should set the default currency code to "USD"', inject(
[DEFAULT_CURRENCY_CODE],
(defaultCurrencyCode: string) => {
expect(defaultCurrencyCode).toEqual('USD');
},
));
it('should set the ivy locale with the configured LOCALE_ID', () => {
TestBed.configureTestingModule({providers: [{provide: LOCALE_ID, useValue: 'fr'}]});
const before = getLocaleId();
const locale = TestBed.inject(LOCALE_ID);
const after = getLocaleId();
expect(before).toEqual('en-us');
expect(locale).toEqual('fr');
expect(after).toEqual('fr');
});
describe('$localize.locale', () => {
beforeEach(() => initLocale('de'));
afterEach(() => restoreLocale());
it('should set the ivy locale to `$localize.locale` value if it is defined', () => {
// Injecting `LOCALE_ID` should also initialize the ivy locale
const locale = TestBed.inject(LOCALE_ID);
expect(locale).toEqual('de');
expect(getLocaleId()).toEqual('de');
});
it('should set the ivy locale to an application provided LOCALE_ID even if `$localize.locale` is defined', () => {
TestBed.configureTestingModule({providers: [{provide: LOCALE_ID, useValue: 'fr'}]});
const locale = TestBed.inject(LOCALE_ID);
expect(locale).toEqual('fr');
expect(getLocaleId()).toEqual('fr');
});
});
});
let hasGlobalLocalize: boolean;
let hasGlobalLocale: boolean;
let originalLocale: string;
function initLocale(locale: string) {
hasGlobalLocalize = Object.getOwnPropertyNames(global).includes('$localize');
if (!hasGlobalLocalize) {
global.$localize = {};
}
hasGlobalLocale = Object.getOwnPropertyNames(global.$localize).includes('locale');
originalLocale = global.$localize.locale;
global.$localize.locale = locale;
}
function restoreLocale() {
if (hasGlobalLocale) {
global.$localize.locale = originalLocale;
} else {
delete global.$localize.locale;
}
if (!hasGlobalLocalize) {
delete global.$localize;
}
}
| {
"end_byte": 2761,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/application_module_spec.ts"
} |
angular/packages/core/test/fake_async_spec.ts_0_3111 | /**
* @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 {
discardPeriodicTasks,
fakeAsync,
flush,
flushMicrotasks,
inject,
tick,
} from '@angular/core/testing';
import {Log} from '@angular/core/testing/src/testing_internal';
import {EventManager} from '@angular/platform-browser';
const resolvedPromise = Promise.resolve(null);
const ProxyZoneSpec: {assertPresent: () => void} = (Zone as any)['ProxyZoneSpec'];
describe('fake async', () => {
it('should run synchronous code', () => {
let ran = false;
fakeAsync(() => {
ran = true;
})();
expect(ran).toEqual(true);
});
it('should pass arguments to the wrapped function', () => {
fakeAsync((foo: string, bar: string) => {
expect(foo).toEqual('foo');
expect(bar).toEqual('bar');
})('foo', 'bar');
});
it('should work with inject()', fakeAsync(
inject([EventManager], (eventManager: EventManager) => {
expect(eventManager).toBeInstanceOf(EventManager);
}),
));
it('should throw on nested calls', () => {
expect(() => {
fakeAsync(() => {
fakeAsync((): null => null)();
})();
}).toThrowError('fakeAsync() calls can not be nested');
});
it('should flush microtasks before returning', () => {
let thenRan = false;
fakeAsync(() => {
resolvedPromise.then((_) => {
thenRan = true;
});
})();
expect(thenRan).toEqual(true);
});
it('should propagate the return value', () => {
expect(fakeAsync(() => 'foo')()).toEqual('foo');
});
describe('Promise', () => {
it('should run asynchronous code', fakeAsync(() => {
let thenRan = false;
resolvedPromise.then((_) => {
thenRan = true;
});
expect(thenRan).toEqual(false);
flushMicrotasks();
expect(thenRan).toEqual(true);
}));
it('should run chained thens', fakeAsync(() => {
const log = new Log<number>();
resolvedPromise.then((_) => log.add(1)).then((_) => log.add(2));
expect(log.result()).toEqual('');
flushMicrotasks();
expect(log.result()).toEqual('1; 2');
}));
it('should run Promise created in Promise', fakeAsync(() => {
const log = new Log<number>();
resolvedPromise.then((_) => {
log.add(1);
resolvedPromise.then((_) => log.add(2));
});
expect(log.result()).toEqual('');
flushMicrotasks();
expect(log.result()).toEqual('1; 2');
}));
it('should complain if the test throws an exception during async calls', () => {
expect(() => {
fakeAsync(() => {
resolvedPromise.then((_) => {
throw new Error('async');
});
flushMicrotasks();
})();
}).toThrow();
});
it('should complain if a test throws an exception', () => {
expect(() => {
fakeAsync(() => {
throw new Error('sync');
})();
}).toThrowError('sync');
});
}); | {
"end_byte": 3111,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/fake_async_spec.ts"
} |
angular/packages/core/test/fake_async_spec.ts_3115_11067 | describe('timers', () => {
it('should run queued zero duration timer on zero tick', fakeAsync(() => {
let ran = false;
setTimeout(() => {
ran = true;
}, 0);
expect(ran).toEqual(false);
tick();
expect(ran).toEqual(true);
}));
it('should run queued timer after sufficient clock ticks', fakeAsync(() => {
let ran = false;
setTimeout(() => {
ran = true;
}, 10);
tick(6);
expect(ran).toEqual(false);
tick(6);
expect(ran).toEqual(true);
}));
it('should run new macro tasks created by timer callback', fakeAsync(() => {
function nestedTimer(callback: () => any): void {
setTimeout(() => setTimeout(() => callback()));
}
const callback = jasmine.createSpy('callback');
nestedTimer(callback);
expect(callback).not.toHaveBeenCalled();
tick(0);
expect(callback).toHaveBeenCalled();
}));
it('should not queue nested timer on tick with processNewMacroTasksSynchronously=false', fakeAsync(() => {
function nestedTimer(callback: () => any): void {
setTimeout(() => setTimeout(() => callback()));
}
const callback = jasmine.createSpy('callback');
nestedTimer(callback);
expect(callback).not.toHaveBeenCalled();
tick(0, {processNewMacroTasksSynchronously: false});
expect(callback).not.toHaveBeenCalled();
flush();
expect(callback).toHaveBeenCalled();
}));
it('should run queued timer only once', fakeAsync(() => {
let cycles = 0;
setTimeout(() => {
cycles++;
}, 10);
tick(10);
expect(cycles).toEqual(1);
tick(10);
expect(cycles).toEqual(1);
tick(10);
expect(cycles).toEqual(1);
}));
it('should not run cancelled timer', fakeAsync(() => {
let ran = false;
const id = setTimeout(() => {
ran = true;
}, 10);
clearTimeout(id);
tick(10);
expect(ran).toEqual(false);
}));
it('should throw an error on dangling timers', () => {
expect(() => {
fakeAsync(
() => {
setTimeout(() => {}, 10);
},
{flush: false},
)();
}).toThrowError('1 timer(s) still in the queue.');
});
it('should throw an error on dangling periodic timers', () => {
expect(() => {
fakeAsync(
() => {
setInterval(() => {}, 10);
},
{flush: false},
)();
}).toThrowError('1 periodic timer(s) still in the queue.');
});
it('should run periodic timers', fakeAsync(() => {
let cycles = 0;
const id = setInterval(() => {
cycles++;
}, 10);
tick(10);
expect(cycles).toEqual(1);
tick(10);
expect(cycles).toEqual(2);
tick(10);
expect(cycles).toEqual(3);
clearInterval(id);
}));
it('should not run cancelled periodic timer', fakeAsync(() => {
let ran = false;
const id = setInterval(() => {
ran = true;
}, 10);
clearInterval(id);
tick(10);
expect(ran).toEqual(false);
}));
it('should be able to cancel periodic timers from a callback', fakeAsync(() => {
let cycles = 0;
const id = setInterval(() => {
cycles++;
clearInterval(id);
}, 10);
tick(10);
expect(cycles).toEqual(1);
tick(10);
expect(cycles).toEqual(1);
}));
it('should clear periodic timers', fakeAsync(() => {
let cycles = 0;
setInterval(() => {
cycles++;
}, 10);
tick(10);
expect(cycles).toEqual(1);
discardPeriodicTasks();
// Tick once to clear out the timer which already started.
tick(10);
expect(cycles).toEqual(2);
tick(10);
// Nothing should change
expect(cycles).toEqual(2);
}));
it('should process microtasks before timers', fakeAsync(() => {
const log = new Log();
resolvedPromise.then((_) => log.add('microtask'));
setTimeout(() => log.add('timer'), 9);
const id = setInterval(() => log.add('periodic timer'), 10);
expect(log.result()).toEqual('');
tick(10);
expect(log.result()).toEqual('microtask; timer; periodic timer');
clearInterval(id);
}));
it('should process micro-tasks created in timers before next timers', fakeAsync(() => {
const log = new Log();
resolvedPromise.then((_) => log.add('microtask'));
setTimeout(() => {
log.add('timer');
resolvedPromise.then((_) => log.add('t microtask'));
}, 9);
const id = setInterval(() => {
log.add('periodic timer');
resolvedPromise.then((_) => log.add('pt microtask'));
}, 10);
tick(10);
expect(log.result()).toEqual('microtask; timer; t microtask; periodic timer; pt microtask');
tick(10);
expect(log.result()).toEqual(
'microtask; timer; t microtask; periodic timer; pt microtask; periodic timer; pt microtask',
);
clearInterval(id);
}));
it('should flush tasks', fakeAsync(() => {
let ran = false;
setTimeout(() => {
ran = true;
}, 10);
flush();
expect(ran).toEqual(true);
}));
it('should flush multiple tasks', fakeAsync(() => {
let ran = false;
let ran2 = false;
setTimeout(() => {
ran = true;
}, 10);
setTimeout(() => {
ran2 = true;
}, 30);
let elapsed = flush();
expect(ran).toEqual(true);
expect(ran2).toEqual(true);
expect(elapsed).toEqual(30);
}));
it('should move periodic tasks', fakeAsync(() => {
let ran = false;
let count = 0;
setInterval(() => {
count++;
}, 10);
setTimeout(() => {
ran = true;
}, 35);
let elapsed = flush();
expect(count).toEqual(3);
expect(ran).toEqual(true);
expect(elapsed).toEqual(35);
discardPeriodicTasks();
}));
});
describe('outside of the fakeAsync zone', () => {
it('calling flushMicrotasks should throw', () => {
expect(() => {
flushMicrotasks();
}).toThrowError('The code should be running in the fakeAsync zone to call this function');
});
it('calling tick should throw', () => {
expect(() => {
tick();
}).toThrowError('The code should be running in the fakeAsync zone to call this function');
});
it('calling flush should throw', () => {
expect(() => {
flush();
}).toThrowError('The code should be running in the fakeAsync zone to call this function');
});
it('calling discardPeriodicTasks should throw', () => {
expect(() => {
discardPeriodicTasks();
}).toThrowError('The code should be running in the fakeAsync zone to call this function');
});
});
describe('only one `fakeAsync` zone per test', () => {
let zoneInBeforeEach: Zone;
let zoneInTest1: Zone;
beforeEach(fakeAsync(() => {
zoneInBeforeEach = Zone.current;
}));
it('should use the same zone as in beforeEach', fakeAsync(() => {
zoneInTest1 = Zone.current;
expect(zoneInTest1).toBe(zoneInBeforeEach);
}));
});
});
describe('ProxyZone', () => {
beforeEach(() => {
ProxyZoneSpec.assertPresent();
});
afterEach(() => {
ProxyZoneSpec.assertPresent();
});
it('should allow fakeAsync zone to retroactively set a zoneSpec outside of fakeAsync', () => {
ProxyZoneSpec.assertPresent();
let state: string = 'not run';
const testZone = Zone.current.fork({name: 'test-zone'});
fakeAsync(() => {
testZone.run(() => {
Promise.resolve('works').then((v) => (state = v));
expect(state).toEqual('not run');
flushMicrotasks();
expect(state).toEqual('works');
});
})();
expect(state).toEqual('works');
});
}); | {
"end_byte": 11067,
"start_byte": 3115,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/fake_async_spec.ts"
} |
angular/packages/core/test/util_spec.ts_0_575 | /**
* @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 {stringify} from '../src/util/stringify';
describe('stringify', () => {
it('should return string undefined when toString returns undefined', () =>
expect(stringify({toString: (): any => undefined})).toBe('undefined'));
it('should return string null when toString returns null', () =>
expect(stringify({toString: (): any => null})).toBe('null'));
});
| {
"end_byte": 575,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/util_spec.ts"
} |
angular/packages/core/test/dev_mode_spec.ts_0_372 | /**
* @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 {isDevMode} from '@angular/core';
describe('dev mode', () => {
it('is enabled in our tests by default', () => {
expect(isDevMode()).toBe(true);
});
});
| {
"end_byte": 372,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/dev_mode_spec.ts"
} |
angular/packages/core/test/BUILD.bazel_0_3763 | load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library")
load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test")
package(default_visibility = ["//visibility:public"])
circular_dependency_test(
name = "circular_deps_test",
entry_point = "angular/packages/core/index.mjs",
deps = ["//packages/core"],
)
circular_dependency_test(
name = "testing_circular_deps_test",
entry_point = "angular/packages/core/testing/index.mjs",
deps = ["//packages/core/testing"],
)
genrule(
name = "downleveled_es5_fixture",
srcs = ["reflection/es2015_inheritance_fixture.ts"],
outs = ["reflection/es5_downleveled_inheritance_fixture.js"],
cmd = """
es2015_out_dir="/tmp/downleveled_es5_fixture/"
es2015_out_file="$$es2015_out_dir/es2015_inheritance_fixture.js"
# Build the ES2015 output and then downlevel it to ES5.
$(execpath @npm//typescript/bin:tsc) $< --outDir $$es2015_out_dir --target ES2015 \
--types --module umd
$(execpath @npm//typescript/bin:tsc) --outFile $@ $$es2015_out_file --allowJs \
--types --target ES5 --downlevelIteration
""",
tools = ["@npm//typescript/bin:tsc"],
)
UTILS = [
"linker/source_map_util.ts",
]
ts_library(
name = "test_utils",
testonly = True,
srcs = UTILS,
deps = [
"//packages/compiler",
"@npm//source-map",
],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(
["**/*.ts"],
exclude = UTILS + [
"**/*_node_only_spec.ts",
"reflection/es2015_inheritance_fixture.ts",
],
),
# Visible to //:saucelabs_unit_tests_poc target
visibility = ["//:__pkg__"],
deps = [
":test_utils",
"//packages/animations",
"//packages/animations/browser",
"//packages/animations/browser/testing",
"//packages/common",
"//packages/common/locales",
"//packages/compiler",
"//packages/core",
"//packages/core/rxjs-interop",
"//packages/core/src/di/interface",
"//packages/core/src/interface",
"//packages/core/src/reflection",
"//packages/core/src/util",
"//packages/core/testing",
"//packages/localize/init",
"//packages/platform-browser",
"//packages/platform-browser-dynamic",
"//packages/platform-browser/animations",
"//packages/platform-browser/testing",
"//packages/platform-server",
"//packages/private/testing",
"//packages/router",
"//packages/router/testing",
"//packages/zone.js/lib:zone_d_ts",
"@npm//rxjs",
],
)
ts_library(
name = "test_node_only_lib",
testonly = True,
srcs = glob(
["**/*_node_only_spec.ts"],
exclude = UTILS,
),
deps = [
":test_lib",
":test_utils",
"//packages/compiler",
"//packages/core",
"//packages/core/src/compiler",
"//packages/core/testing",
"//packages/platform-server",
"//packages/platform-server/testing",
"//packages/private/testing",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node"],
data = [
":downleveled_es5_fixture",
],
shard_count = 4,
deps = [
":test_lib",
":test_node_only_lib",
"//packages/platform-server",
"//packages/platform-server/testing",
"//packages/zone.js/lib:zone_d_ts",
"@npm//source-map",
],
)
karma_web_test_suite(
name = "test_web",
external = ["@angular/platform-server"],
runtime_deps = [":downleveled_es5_fixture"],
deps = [
":test_lib",
],
)
| {
"end_byte": 3763,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/BUILD.bazel"
} |
angular/packages/core/test/application_ref_spec.ts_0_8167 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {DOCUMENT, ɵgetDOM as getDOM} from '@angular/common';
import {ResourceLoader} from '@angular/compiler';
import {
APP_BOOTSTRAP_LISTENER,
APP_INITIALIZER,
ChangeDetectionStrategy,
Compiler,
CompilerFactory,
Component,
EnvironmentInjector,
InjectionToken,
LOCALE_ID,
NgModule,
NgZone,
PlatformRef,
provideZoneChangeDetection,
RendererFactory2,
TemplateRef,
Type,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import {ErrorHandler} from '@angular/core/src/error_handler';
import {ComponentRef} from '@angular/core/src/linker/component_factory';
import {createEnvironmentInjector, getLocaleId} from '@angular/core/src/render3';
import {BrowserModule} from '@angular/platform-browser';
import {DomRendererFactory2} from '@angular/platform-browser/src/dom/dom_renderer';
import {
createTemplate,
dispatchEvent,
getContent,
} from '@angular/platform-browser/testing/src/browser_util';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import type {ServerModule} from '@angular/platform-server';
import {ApplicationRef} from '../src/application/application_ref';
import {NoopNgZone} from '../src/zone/ng_zone';
import {ComponentFixtureNoNgZone, inject, TestBed, waitForAsync, withModule} from '../testing';
import {take} from 'rxjs/operators';
let serverPlatformModule: Promise<Type<ServerModule>> | null = null;
if (isNode) {
// Only when we are in Node, we load the platform-server module. It will
// be required later in specs for declaring the platform module.
serverPlatformModule = import('@angular/platform-server').then((m) => m.ServerModule);
}
@Component({
selector: 'bootstrap-app',
template: 'hello',
standalone: false,
})
class SomeComponent {}
describe('bootstrap', () => {
let mockConsole: MockConsole;
beforeEach(() => {
mockConsole = new MockConsole();
});
function createRootEl(selector = 'bootstrap-app') {
const doc = TestBed.inject(DOCUMENT);
const rootEl = <HTMLElement>(
getContent(createTemplate(`<${selector}></${selector}>`)).firstChild
);
const oldRoots = doc.querySelectorAll(selector);
for (let i = 0; i < oldRoots.length; i++) {
getDOM().remove(oldRoots[i]);
}
doc.body.appendChild(rootEl);
}
type CreateModuleOptions = {
providers?: any[];
ngDoBootstrap?: any;
bootstrap?: any[];
component?: Type<any>;
};
async function createModule(providers?: any[]): Promise<Type<any>>;
async function createModule(options: CreateModuleOptions): Promise<Type<any>>;
async function createModule(
providersOrOptions: any[] | CreateModuleOptions | undefined,
): Promise<Type<any>> {
let options: CreateModuleOptions = {};
if (Array.isArray(providersOrOptions)) {
options = {providers: providersOrOptions};
} else {
options = providersOrOptions || {};
}
const errorHandler = new ErrorHandler();
(errorHandler as any)._console = mockConsole as any;
const platformModule = getDOM().supportsDOMEvents ? BrowserModule : await serverPlatformModule!;
@NgModule({
providers: [{provide: ErrorHandler, useValue: errorHandler}, options.providers || []],
imports: [platformModule],
declarations: [options.component || SomeComponent],
bootstrap: options.bootstrap || [],
})
class MyModule {}
if (options.ngDoBootstrap !== false) {
(<any>MyModule.prototype).ngDoBootstrap = options.ngDoBootstrap || (() => {});
}
return MyModule;
}
it('should bootstrap a component from a child module', waitForAsync(
inject([ApplicationRef, Compiler], (app: ApplicationRef, compiler: Compiler) => {
@Component({
selector: 'bootstrap-app',
template: '',
standalone: false,
})
class SomeComponent {}
const helloToken = new InjectionToken<string>('hello');
@NgModule({
providers: [{provide: helloToken, useValue: 'component'}],
declarations: [SomeComponent],
})
class SomeModule {}
createRootEl();
const modFactory = compiler.compileModuleSync(SomeModule);
const module = modFactory.create(TestBed);
const cmpFactory = module.componentFactoryResolver.resolveComponentFactory(SomeComponent);
const component = app.bootstrap(cmpFactory);
// The component should see the child module providers
expect(component.injector.get(helloToken)).toEqual('component');
}),
));
it('should bootstrap a component with a custom selector', waitForAsync(
inject([ApplicationRef, Compiler], (app: ApplicationRef, compiler: Compiler) => {
@Component({
selector: 'bootstrap-app',
template: '',
standalone: false,
})
class SomeComponent {}
const helloToken = new InjectionToken<string>('hello');
@NgModule({
providers: [{provide: helloToken, useValue: 'component'}],
declarations: [SomeComponent],
})
class SomeModule {}
createRootEl('custom-selector');
const modFactory = compiler.compileModuleSync(SomeModule);
const module = modFactory.create(TestBed);
const cmpFactory = module.componentFactoryResolver.resolveComponentFactory(SomeComponent);
const component = app.bootstrap(cmpFactory, 'custom-selector');
// The component should see the child module providers
expect(component.injector.get(helloToken)).toEqual('component');
}),
));
describe('ApplicationRef', () => {
beforeEach(async () => {
TestBed.configureTestingModule({imports: [await createModule()]});
});
it('should throw when reentering tick', () => {
@Component({
template: '{{reenter()}}',
standalone: false,
})
class ReenteringComponent {
reenterCount = 1;
reenterErr: any;
constructor(private appRef: ApplicationRef) {}
reenter() {
if (this.reenterCount--) {
try {
this.appRef.tick();
} catch (e) {
this.reenterErr = e;
}
}
}
}
const fixture = TestBed.configureTestingModule({
declarations: [ReenteringComponent],
}).createComponent(ReenteringComponent);
const appRef = TestBed.inject(ApplicationRef);
appRef.attachView(fixture.componentRef.hostView);
appRef.tick();
expect(fixture.componentInstance.reenterErr.message).toBe(
'NG0101: ApplicationRef.tick is called recursively',
);
});
describe('APP_BOOTSTRAP_LISTENER', () => {
let capturedCompRefs: ComponentRef<any>[];
beforeEach(() => {
capturedCompRefs = [];
TestBed.configureTestingModule({
providers: [
{
provide: APP_BOOTSTRAP_LISTENER,
multi: true,
useValue: (compRef: any) => {
capturedCompRefs.push(compRef);
},
},
],
});
});
it('should be called when a component is bootstrapped', inject(
[ApplicationRef],
(ref: ApplicationRef) => {
createRootEl();
const compRef = ref.bootstrap(SomeComponent);
expect(capturedCompRefs).toEqual([compRef]);
},
));
});
describe('bootstrap', () => {
it(
'should throw if an APP_INITIIALIZER is not yet resolved',
withModule(
{
providers: [
{provide: APP_INITIALIZER, useValue: () => new Promise(() => {}), multi: true},
],
},
inject([ApplicationRef], (ref: ApplicationRef) => {
createRootEl();
expect(() => ref.bootstrap(SomeComponent)).toThrowError(
'NG0405: Cannot bootstrap as there are still asynchronous initializers running. Bootstrap components in the `ngDoBootstrap` method of the root module.',
);
}),
),
);
});
});
| {
"end_byte": 8167,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/application_ref_spec.ts"
} |
angular/packages/core/test/application_ref_spec.ts_8171_14428 | escribe('destroy', () => {
const providers = [
{provide: DOCUMENT, useFactory: () => document, deps: []},
// Use the `DomRendererFactory2` as a renderer factory instead of the
// `AnimationRendererFactory` one, which is configured as a part of the `ServerModule`, see
// platform module setup above. This simplifies the tests (so they are sync vs async when
// animations are in use) that verify that the DOM has been cleaned up after tests.
{provide: RendererFactory2, useClass: DomRendererFactory2},
];
// This function creates a new Injector instance with the `ApplicationRef` as a provider, so
// that the instance of the `ApplicationRef` class is created on that injector (vs in the
// app-level injector). It is needed to verify `ApplicationRef.destroy` scenarios, which
// includes destroying an underlying injector.
function createApplicationRefInjector(parentInjector: EnvironmentInjector) {
const extraProviders = [{provide: ApplicationRef, useClass: ApplicationRef}];
return createEnvironmentInjector(extraProviders, parentInjector);
}
function createApplicationRef(parentInjector: EnvironmentInjector) {
const injector = createApplicationRefInjector(parentInjector);
return injector.get(ApplicationRef);
}
it(
'should cleanup the DOM',
withModule(
{providers},
waitForAsync(
inject(
[EnvironmentInjector, DOCUMENT],
(parentInjector: EnvironmentInjector, doc: Document) => {
createRootEl();
const appRef = createApplicationRef(parentInjector);
appRef.bootstrap(SomeComponent);
// The component template content (`hello`) is present in the document body.
expect(doc.body.textContent!.indexOf('hello') > -1).toBeTrue();
appRef.destroy();
// The component template content (`hello`) is *not* present in the document
// body, i.e. the DOM has been cleaned up.
expect(doc.body.textContent!.indexOf('hello') === -1).toBeTrue();
},
),
),
),
);
it(
'should throw when trying to call `destroy` method on already destroyed ApplicationRef',
withModule(
{providers},
waitForAsync(
inject([EnvironmentInjector], (parentInjector: EnvironmentInjector) => {
createRootEl();
const appRef = createApplicationRef(parentInjector);
appRef.bootstrap(SomeComponent);
appRef.destroy();
expect(() => appRef.destroy()).toThrowError(
'NG0406: This instance of the `ApplicationRef` has already been destroyed.',
);
}),
),
),
);
it(
'should invoke all registered `onDestroy` callbacks (internal API)',
withModule(
{providers},
waitForAsync(
inject([EnvironmentInjector], (parentInjector: EnvironmentInjector) => {
const onDestroyA = jasmine.createSpy('onDestroyA');
const onDestroyB = jasmine.createSpy('onDestroyB');
createRootEl();
const appRef = createApplicationRef(parentInjector) as unknown as ApplicationRef & {
onDestroy: Function;
};
appRef.bootstrap(SomeComponent);
appRef.onDestroy(onDestroyA);
appRef.onDestroy(onDestroyB);
appRef.destroy();
expect(onDestroyA).toHaveBeenCalledTimes(1);
expect(onDestroyB).toHaveBeenCalledTimes(1);
}),
),
),
);
it(
'should allow to unsubscribe a registered `onDestroy` callback (internal API)',
withModule(
{providers},
waitForAsync(
inject([EnvironmentInjector], (parentInjector: EnvironmentInjector) => {
createRootEl();
const appRef = createApplicationRef(parentInjector) as unknown as ApplicationRef & {
onDestroy: Function;
};
appRef.bootstrap(SomeComponent);
const onDestroyA = jasmine.createSpy('onDestroyA');
const onDestroyB = jasmine.createSpy('onDestroyB');
const unsubscribeOnDestroyA = appRef.onDestroy(onDestroyA);
const unsubscribeOnDestroyB = appRef.onDestroy(onDestroyB);
// Unsubscribe registered listeners.
unsubscribeOnDestroyA();
unsubscribeOnDestroyB();
appRef.destroy();
expect(onDestroyA).not.toHaveBeenCalled();
expect(onDestroyB).not.toHaveBeenCalled();
}),
),
),
);
it(
'should correctly update the `destroyed` flag',
withModule(
{providers},
waitForAsync(
inject([EnvironmentInjector], (parentInjector: EnvironmentInjector) => {
createRootEl();
const appRef = createApplicationRef(parentInjector);
appRef.bootstrap(SomeComponent);
expect(appRef.destroyed).toBeFalse();
appRef.destroy();
expect(appRef.destroyed).toBeTrue();
}),
),
),
);
it(
'should also destroy underlying injector',
withModule(
{providers},
waitForAsync(
inject([EnvironmentInjector], (parentInjector: EnvironmentInjector) => {
// This is a temporary type to represent an instance of an R3Injector, which
// can be destroyed.
// The type will be replaced with a different one once destroyable injector
// type is available.
type DestroyableInjector = EnvironmentInjector & {destroyed?: boolean};
createRootEl();
const injector = createApplicationRefInjector(parentInjector) as DestroyableInjector;
const appRef = injector.get(ApplicationRef);
appRef.bootstrap(SomeComponent);
expect(appRef.destroyed).toBeFalse();
expect(injector.destroyed).toBeFalse();
appRef.destroy();
expect(appRef.destroyed).toBeTrue();
expect(injector.destroyed).toBeTrue();
}),
),
),
);
});
| {
"end_byte": 14428,
"start_byte": 8171,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/application_ref_spec.ts"
} |
angular/packages/core/test/application_ref_spec.ts_14432_23252 | escribe('bootstrapModule', () => {
let defaultPlatform: PlatformRef;
beforeEach(inject([PlatformRef], (_platform: PlatformRef) => {
createRootEl();
defaultPlatform = _platform;
}));
it('should wait for asynchronous app initializers', waitForAsync(async () => {
let resolve: (result: any) => void;
const promise: Promise<any> = new Promise((res) => {
resolve = res;
});
let initializerDone = false;
setTimeout(() => {
resolve(true);
initializerDone = true;
}, 1);
defaultPlatform
.bootstrapModule(
await createModule([{provide: APP_INITIALIZER, useValue: () => promise, multi: true}]),
)
.then((_) => {
expect(initializerDone).toBe(true);
});
}));
it('should rethrow sync errors even if the exceptionHandler is not rethrowing', waitForAsync(async () => {
defaultPlatform
.bootstrapModule(
await createModule([
{
provide: APP_INITIALIZER,
useValue: () => {
throw 'Test';
},
multi: true,
},
]),
)
.then(
() => expect(false).toBe(true),
(e) => {
expect(e).toBe('Test');
// Error rethrown will be seen by the exception handler since it's after
// construction.
expect(mockConsole.res[0].join('#')).toEqual('ERROR#Test');
},
);
}));
it('should rethrow promise errors even if the exceptionHandler is not rethrowing', waitForAsync(async () => {
defaultPlatform
.bootstrapModule(
await createModule([
{provide: APP_INITIALIZER, useValue: () => Promise.reject('Test'), multi: true},
]),
)
.then(
() => expect(false).toBe(true),
(e) => {
expect(e).toBe('Test');
expect(mockConsole.res[0].join('#')).toEqual('ERROR#Test');
},
);
}));
it('should throw useful error when ApplicationRef is not configured', waitForAsync(() => {
@NgModule()
class EmptyModule {}
return defaultPlatform.bootstrapModule(EmptyModule).then(
() => fail('expecting error'),
(error) => {
expect(error.message).toMatch(/NG0402/);
},
);
}));
it('should call the `ngDoBootstrap` method with `ApplicationRef` on the main module', waitForAsync(async () => {
const ngDoBootstrap = jasmine.createSpy('ngDoBootstrap');
defaultPlatform
.bootstrapModule(await createModule({ngDoBootstrap: ngDoBootstrap}))
.then((moduleRef) => {
const appRef = moduleRef.injector.get(ApplicationRef);
expect(ngDoBootstrap).toHaveBeenCalledWith(appRef);
});
}));
it('should auto bootstrap components listed in @NgModule.bootstrap', waitForAsync(async () => {
defaultPlatform
.bootstrapModule(await createModule({bootstrap: [SomeComponent]}))
.then((moduleRef) => {
const appRef: ApplicationRef = moduleRef.injector.get(ApplicationRef);
expect(appRef.componentTypes).toEqual([SomeComponent]);
});
}));
it('should error if neither `ngDoBootstrap` nor @NgModule.bootstrap was specified', waitForAsync(async () => {
defaultPlatform.bootstrapModule(await createModule({ngDoBootstrap: false})).then(
() => expect(false).toBe(true),
(e) => {
const expectedErrMsg =
`NG0403: The module MyModule was bootstrapped, ` +
`but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. ` +
`Please define one of these. ` +
`Find more at https://angular.dev/errors/NG0403`;
expect(e.message).toEqual(expectedErrMsg);
expect(mockConsole.res[0].join('#')).toEqual('ERROR#Error: ' + expectedErrMsg);
},
);
}));
it('should add bootstrapped module into platform modules list', waitForAsync(async () => {
defaultPlatform
.bootstrapModule(await createModule({bootstrap: [SomeComponent]}))
.then((module) => expect((<any>defaultPlatform)._modules).toContain(module));
}));
it('should bootstrap with NoopNgZone', waitForAsync(async () => {
defaultPlatform
.bootstrapModule(await createModule({bootstrap: [SomeComponent]}), {ngZone: 'noop'})
.then((module) => {
const ngZone = module.injector.get(NgZone);
expect(ngZone instanceof NoopNgZone).toBe(true);
});
}));
it('should resolve component resources when creating module factory', async () => {
@Component({
selector: 'with-templates-app',
templateUrl: '/test-template.html',
standalone: false,
})
class WithTemplateUrlComponent {}
const loadResourceSpy = jasmine.createSpy('load resource').and.returnValue('fakeContent');
const testModule = await createModule({component: WithTemplateUrlComponent});
await defaultPlatform.bootstrapModule(testModule, {
providers: [{provide: ResourceLoader, useValue: {get: loadResourceSpy}}],
});
expect(loadResourceSpy).toHaveBeenCalledTimes(1);
expect(loadResourceSpy).toHaveBeenCalledWith('/test-template.html');
});
it('should define `LOCALE_ID`', async () => {
@Component({
selector: 'i18n-app',
templateUrl: '',
standalone: false,
})
class I18nComponent {}
const testModule = await createModule({
component: I18nComponent,
providers: [{provide: LOCALE_ID, useValue: 'ro'}],
});
await defaultPlatform.bootstrapModule(testModule);
expect(getLocaleId()).toEqual('ro');
});
it('should wait for APP_INITIALIZER to set providers for `LOCALE_ID`', async () => {
let locale: string = '';
const testModule = await createModule({
providers: [
{provide: APP_INITIALIZER, useValue: () => (locale = 'fr-FR'), multi: true},
{provide: LOCALE_ID, useFactory: () => locale},
],
});
const app = await defaultPlatform.bootstrapModule(testModule);
expect(app.injector.get(LOCALE_ID)).toEqual('fr-FR');
});
});
describe('bootstrapModuleFactory', () => {
let defaultPlatform: PlatformRef;
beforeEach(inject([PlatformRef], (_platform: PlatformRef) => {
createRootEl();
defaultPlatform = _platform;
}));
it('should wait for asynchronous app initializers', waitForAsync(async () => {
let resolve: (result: any) => void;
const promise: Promise<any> = new Promise((res) => {
resolve = res;
});
let initializerDone = false;
setTimeout(() => {
resolve(true);
initializerDone = true;
}, 1);
const compilerFactory: CompilerFactory = defaultPlatform.injector.get(CompilerFactory, null)!;
const moduleFactory = compilerFactory
.createCompiler()
.compileModuleSync(
await createModule([{provide: APP_INITIALIZER, useValue: () => promise, multi: true}]),
);
defaultPlatform.bootstrapModuleFactory(moduleFactory).then((_) => {
expect(initializerDone).toBe(true);
});
}));
it('should rethrow sync errors even if the exceptionHandler is not rethrowing', waitForAsync(async () => {
const compilerFactory: CompilerFactory = defaultPlatform.injector.get(CompilerFactory, null)!;
const moduleFactory = compilerFactory.createCompiler().compileModuleSync(
await createModule([
{
provide: APP_INITIALIZER,
useValue: () => {
throw 'Test';
},
multi: true,
},
]),
);
expect(() => defaultPlatform.bootstrapModuleFactory(moduleFactory)).toThrow('Test');
// Error rethrown will be seen by the exception handler since it's after
// construction.
expect(mockConsole.res[0].join('#')).toEqual('ERROR#Test');
}));
it('should rethrow promise errors even if the exceptionHandler is not rethrowing', waitForAsync(async () => {
const compilerFactory: CompilerFactory = defaultPlatform.injector.get(CompilerFactory, null)!;
const moduleFactory = compilerFactory
.createCompiler()
.compileModuleSync(
await createModule([
{provide: APP_INITIALIZER, useValue: () => Promise.reject('Test'), multi: true},
]),
);
defaultPlatform.bootstrapModuleFactory(moduleFactory).then(
() => expect(false).toBe(true),
(e) => {
expect(e).toBe('Test');
expect(mockConsole.res[0].join('#')).toEqual('ERROR#Test');
},
);
}));
});
| {
"end_byte": 23252,
"start_byte": 14432,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/application_ref_spec.ts"
} |
angular/packages/core/test/application_ref_spec.ts_23256_27472 | escribe('attachView / detachView', () => {
@Component({
template: '{{name}}',
standalone: false,
})
class MyComp {
name = 'Initial';
}
@Component({
template: '<ng-container #vc></ng-container>',
standalone: false,
})
class ContainerComp {
@ViewChild('vc', {read: ViewContainerRef}) vc!: ViewContainerRef;
}
@Component({
template: '<ng-template #t>Dynamic content</ng-template>',
standalone: false,
})
class EmbeddedViewComp {
@ViewChild(TemplateRef, {static: true}) tplRef!: TemplateRef<Object>;
}
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MyComp, ContainerComp, EmbeddedViewComp],
providers: [{provide: ComponentFixtureNoNgZone, useValue: true}],
});
});
it('should dirty check attached views', () => {
const comp = TestBed.createComponent(MyComp);
const appRef: ApplicationRef = TestBed.inject(ApplicationRef);
expect(appRef.viewCount).toBe(0);
appRef.tick();
expect(comp.nativeElement).toHaveText('');
appRef.attachView(comp.componentRef.hostView);
appRef.tick();
expect(appRef.viewCount).toBe(1);
expect(comp.nativeElement).toHaveText('Initial');
});
it('should not dirty check detached views', () => {
const comp = TestBed.createComponent(MyComp);
const appRef: ApplicationRef = TestBed.inject(ApplicationRef);
appRef.attachView(comp.componentRef.hostView);
appRef.tick();
expect(comp.nativeElement).toHaveText('Initial');
appRef.detachView(comp.componentRef.hostView);
comp.componentInstance.name = 'New';
appRef.tick();
expect(appRef.viewCount).toBe(0);
expect(comp.nativeElement).toHaveText('Initial');
});
it('should not dirty host bindings of views not marked for check', () => {
@Component({
template: '',
host: {'[class]': 'clazz'},
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
})
class HostBindingComp {
clazz = 'initial';
}
const comp = TestBed.createComponent(HostBindingComp);
const appRef = TestBed.inject(ApplicationRef);
appRef.attachView(comp.componentRef.hostView);
appRef.tick();
expect(comp.nativeElement.outerHTML).toContain('initial');
comp.componentInstance.clazz = 'new';
appRef.tick();
expect(comp.nativeElement.outerHTML).toContain('initial');
comp.changeDetectorRef.markForCheck();
appRef.tick();
expect(comp.nativeElement.outerHTML).toContain('new');
});
it('should detach attached views if they are destroyed', () => {
const comp = TestBed.createComponent(MyComp);
const appRef: ApplicationRef = TestBed.inject(ApplicationRef);
appRef.attachView(comp.componentRef.hostView);
comp.destroy();
expect(appRef.viewCount).toBe(0);
});
it('should detach attached embedded views if they are destroyed', () => {
const comp = TestBed.createComponent(EmbeddedViewComp);
const appRef: ApplicationRef = TestBed.inject(ApplicationRef);
const embeddedViewRef = comp.componentInstance.tplRef.createEmbeddedView({});
appRef.attachView(embeddedViewRef);
embeddedViewRef.destroy();
expect(appRef.viewCount).toBe(0);
});
it('should not allow to attach a view to both, a view container and the ApplicationRef', () => {
const comp = TestBed.createComponent(MyComp);
let hostView = comp.componentRef.hostView;
const containerComp = TestBed.createComponent(ContainerComp);
containerComp.detectChanges();
const vc = containerComp.componentInstance.vc;
const appRef: ApplicationRef = TestBed.inject(ApplicationRef);
vc.insert(hostView);
expect(() => appRef.attachView(hostView)).toThrowError(
'NG0902: This view is already attached to a ViewContainer!',
);
hostView = vc.detach(0)!;
appRef.attachView(hostView);
expect(() => vc.insert(hostView)).toThrowError(
'NG0902: This view is already attached directly to the ApplicationRef!',
);
});
});
});
| {
"end_byte": 27472,
"start_byte": 23256,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/application_ref_spec.ts"
} |
angular/packages/core/test/application_ref_spec.ts_27474_33186 | escribe('AppRef', () => {
@Component({
selector: 'sync-comp',
template: `<span>{{text}}</span>`,
standalone: false,
})
class SyncComp {
text: string = '1';
}
@Component({
selector: 'click-comp',
template: `<span (click)="onClick()">{{text}}</span>`,
standalone: false,
})
class ClickComp {
text: string = '1';
onClick() {
this.text += '1';
}
}
@Component({
selector: 'micro-task-comp',
template: `<span>{{text}}</span>`,
standalone: false,
})
class MicroTaskComp {
text: string = '1';
ngOnInit() {
Promise.resolve(null).then((_) => {
this.text += '1';
});
}
}
@Component({
selector: 'macro-task-comp',
template: `<span>{{text}}</span>`,
standalone: false,
})
class MacroTaskComp {
text: string = '1';
ngOnInit() {
setTimeout(() => {
this.text += '1';
}, 10);
}
}
@Component({
selector: 'micro-macro-task-comp',
template: `<span>{{text}}</span>`,
standalone: false,
})
class MicroMacroTaskComp {
text: string = '1';
ngOnInit() {
Promise.resolve(null).then((_) => {
this.text += '1';
setTimeout(() => {
this.text += '1';
}, 10);
});
}
}
@Component({
selector: 'macro-micro-task-comp',
template: `<span>{{text}}</span>`,
standalone: false,
})
class MacroMicroTaskComp {
text: string = '1';
ngOnInit() {
setTimeout(() => {
this.text += '1';
Promise.resolve(null).then((_: any) => {
this.text += '1';
});
}, 10);
}
}
let stableCalled = false;
beforeEach(() => {
stableCalled = false;
TestBed.configureTestingModule({
providers: [provideZoneChangeDetection({ignoreChangesOutsideZone: true})],
declarations: [
SyncComp,
MicroTaskComp,
MacroTaskComp,
MicroMacroTaskComp,
MacroMicroTaskComp,
ClickComp,
],
});
});
afterEach(() => {
expect(stableCalled).toBe(true, 'isStable did not emit true on stable');
});
function expectStableTexts(component: Type<any>, expected: string[]) {
const fixture = TestBed.createComponent(component);
const appRef: ApplicationRef = TestBed.inject(ApplicationRef);
const zone: NgZone = TestBed.inject(NgZone);
appRef.attachView(fixture.componentRef.hostView);
zone.run(() => appRef.tick());
let i = 0;
appRef.isStable.subscribe({
next: (stable: boolean) => {
if (stable) {
expect(i).toBeLessThan(expected.length);
expect(fixture.nativeElement).toHaveText(expected[i++]);
stableCalled = true;
}
},
});
}
it('isStable should fire on synchronous component loading', waitForAsync(() => {
expectStableTexts(SyncComp, ['1']);
}));
it('isStable should fire after a microtask on init is completed', waitForAsync(() => {
expectStableTexts(MicroTaskComp, ['11']);
}));
it('isStable should fire after a macrotask on init is completed', waitForAsync(() => {
expectStableTexts(MacroTaskComp, ['11']);
}));
it('isStable should fire only after chain of micro and macrotasks on init are completed', waitForAsync(() => {
expectStableTexts(MicroMacroTaskComp, ['111']);
}));
it('isStable should fire only after chain of macro and microtasks on init are completed', waitForAsync(() => {
expectStableTexts(MacroMicroTaskComp, ['111']);
}));
it('isStable can be subscribed to many times', async () => {
const appRef: ApplicationRef = TestBed.inject(ApplicationRef);
// Create stable subscription but do not unsubscribe before the second subscription is made
appRef.isStable.subscribe();
await expectAsync(appRef.isStable.pipe(take(1)).toPromise()).toBeResolved();
stableCalled = true;
});
describe('unstable', () => {
let unstableCalled = false;
afterEach(() => {
expect(unstableCalled).toBe(true, 'isStable did not emit false on unstable');
});
function expectUnstable(appRef: ApplicationRef) {
appRef.isStable.subscribe({
next: (stable: boolean) => {
if (stable) {
stableCalled = true;
}
if (!stable) {
unstableCalled = true;
}
},
});
}
it('should be fired after app becomes unstable', waitForAsync(() => {
const fixture = TestBed.createComponent(ClickComp);
const appRef: ApplicationRef = TestBed.inject(ApplicationRef);
const zone: NgZone = TestBed.inject(NgZone);
appRef.attachView(fixture.componentRef.hostView);
zone.run(() => appRef.tick());
fixture.whenStable().then(() => {
expectUnstable(appRef);
const element = fixture.debugElement.children[0];
dispatchEvent(element.nativeElement, 'click');
});
}));
});
});
describe('injector', () => {
it('should expose an EnvironmentInjector', () => {
@Component({
standalone: false,
})
class TestCmp {
constructor(readonly envInjector: EnvironmentInjector) {}
}
const fixture = TestBed.createComponent(TestCmp);
const appRef = TestBed.inject(ApplicationRef);
expect(appRef.injector).toBe(fixture.componentInstance.envInjector);
});
});
class MockConsole {
res: any[][] = [];
log(...args: any[]): void {
// Logging from ErrorHandler should run outside of the Angular Zone.
NgZone.assertNotInAngularZone();
this.res.push(args);
}
error(...args: any[]): void {
// Logging from ErrorHandler should run outside of the Angular Zone.
NgZone.assertNotInAngularZone();
this.res.push(args);
}
}
| {
"end_byte": 33186,
"start_byte": 27474,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/application_ref_spec.ts"
} |
angular/packages/core/test/application_config_spec.ts_0_1705 | /**
* @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 {ApplicationConfig, InjectionToken, mergeApplicationConfig} from '@angular/core';
describe('ApplicationConfig', () => {
describe('mergeApplicationConfig', () => {
const FOO_TOKEN = new InjectionToken('foo');
const BAR_TOKEN = new InjectionToken('bar');
const BUZ_TOKEN = new InjectionToken('buz');
const BASE_CONFIG: ApplicationConfig = {
providers: [{provide: FOO_TOKEN, useValue: 'foo'}],
};
const APP_CONFIG_EXPECT: ApplicationConfig = {
providers: [
{provide: FOO_TOKEN, useValue: 'foo'},
{provide: BAR_TOKEN, useValue: 'bar'},
{provide: BUZ_TOKEN, useValue: 'buz'},
],
};
it('should merge 2 configs from left to right', () => {
const extraConfig: ApplicationConfig = {
providers: [
{provide: BAR_TOKEN, useValue: 'bar'},
{provide: BUZ_TOKEN, useValue: 'buz'},
],
};
const config = mergeApplicationConfig(BASE_CONFIG, extraConfig);
expect(config).toEqual(APP_CONFIG_EXPECT);
});
it('should merge more than 2 configs from left to right', () => {
const extraConfigOne: ApplicationConfig = {
providers: [{provide: BAR_TOKEN, useValue: 'bar'}],
};
const extraConfigTwo: ApplicationConfig = {
providers: [{provide: BUZ_TOKEN, useValue: 'buz'}],
};
const config = mergeApplicationConfig(BASE_CONFIG, extraConfigOne, extraConfigTwo);
expect(config).toEqual(APP_CONFIG_EXPECT);
});
});
});
| {
"end_byte": 1705,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/application_config_spec.ts"
} |
angular/packages/core/test/forward_ref_integration_spec.ts_0_1957 | /**
* @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 {
asNativeElements,
Component,
ContentChildren,
Directive,
forwardRef,
Inject,
NgModule,
NO_ERRORS_SCHEMA,
QueryList,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers';
class Frame {
name: string = 'frame';
}
class ModuleFrame {
name: string = 'moduleFram';
}
describe('forwardRef integration', function () {
beforeEach(() => {
TestBed.configureTestingModule({imports: [Module], declarations: [App]});
});
it('should instantiate components which are declared using forwardRef', () => {
const a = TestBed.configureTestingModule({schemas: [NO_ERRORS_SCHEMA]}).createComponent(App);
a.detectChanges();
expect(asNativeElements(a.debugElement.children)).toHaveText('frame(lock)');
expect(TestBed.inject(ModuleFrame)).toBeDefined();
});
});
@NgModule({
imports: [CommonModule],
providers: [forwardRef(() => ModuleFrame)],
declarations: [forwardRef(() => Door), forwardRef(() => Lock)],
exports: [forwardRef(() => Door), forwardRef(() => Lock)],
})
class Module {}
@Component({
selector: 'app',
viewProviders: [forwardRef(() => Frame)],
template: `<door><lock></lock></door>`,
standalone: false,
})
class App {}
@Component({
selector: 'door',
template: `{{frame.name}}(<span *ngFor="let lock of locks">{{lock.name}}</span>)`,
standalone: false,
})
class Door {
@ContentChildren(forwardRef(() => Lock)) locks!: QueryList<Lock>;
frame: Frame;
constructor(@Inject(forwardRef(() => Frame)) frame: Frame) {
this.frame = frame;
}
}
@Directive({
selector: 'lock',
standalone: false,
})
class Lock {
name: string = 'lock';
}
| {
"end_byte": 1957,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/forward_ref_integration_spec.ts"
} |
angular/packages/core/test/application_ref_integration_spec.ts_0_2825 | /**
* @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,
DoCheck,
NgModule,
OnInit,
TestabilityRegistry,
} from '@angular/core';
import {getTestBed} from '@angular/core/testing';
import {BrowserModule} from '@angular/platform-browser';
import {withBody} from '@angular/private/testing';
import {NgModuleFactory} from '../src/render3/ng_module_ref';
describe('ApplicationRef bootstrap', () => {
@Component({
selector: 'hello-world',
template: '<div>Hello {{ name }}</div>',
standalone: false,
})
class HelloWorldComponent implements OnInit, DoCheck {
log: string[] = [];
name = 'World';
ngOnInit(): void {
this.log.push('OnInit');
}
ngDoCheck(): void {
this.log.push('DoCheck');
}
}
@NgModule({
declarations: [HelloWorldComponent],
bootstrap: [HelloWorldComponent],
imports: [BrowserModule],
providers: [{provide: DOCUMENT, useFactory: () => document}],
})
class MyAppModule {}
it(
'should bootstrap hello world',
withBody('<hello-world></hello-world>', async () => {
const MyAppModuleFactory = new NgModuleFactory(MyAppModule);
const moduleRef = await getTestBed().platform.bootstrapModuleFactory(MyAppModuleFactory, {
ngZone: 'noop',
});
const appRef = moduleRef.injector.get(ApplicationRef);
const helloWorldComponent = appRef.components[0].instance as HelloWorldComponent;
expect(document.body.innerHTML).toEqual(
'<hello-world ng-version="0.0.0-PLACEHOLDER"><div>Hello World</div></hello-world>',
);
expect(helloWorldComponent.log).toEqual(['OnInit', 'DoCheck']);
helloWorldComponent.name = 'Mundo';
appRef.tick();
expect(document.body.innerHTML).toEqual(
'<hello-world ng-version="0.0.0-PLACEHOLDER"><div>Hello Mundo</div></hello-world>',
);
expect(helloWorldComponent.log).toEqual(['OnInit', 'DoCheck', 'DoCheck']);
// Cleanup TestabilityRegistry
const registry: TestabilityRegistry = getTestBed().get(TestabilityRegistry);
registry.unregisterAllApplications();
}),
);
it(
'should expose the `window.ng` global utilities',
withBody('<hello-world></hello-world>', async () => {
const MyAppModuleFactory = new NgModuleFactory(MyAppModule);
const moduleRef = await getTestBed().platform.bootstrapModuleFactory(MyAppModuleFactory, {
ngZone: 'noop',
});
const glob = typeof global !== 'undefined' ? global : window;
const ngUtils = (glob as any).ng;
expect(ngUtils.getComponent).toBeTruthy();
}),
);
});
| {
"end_byte": 2825,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/application_ref_integration_spec.ts"
} |
angular/packages/core/test/di/r3_injector_spec.ts_0_495 | /**
* @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 {
InjectFlags,
InjectionToken,
INJECTOR,
Injector,
Optional,
ɵɵdefineInjectable,
ɵɵdefineInjector,
ɵɵinject,
} from '@angular/core';
import {createInjector} from '@angular/core/src/di/create_injector';
import {R3Injector} from '@angular/core/src/di/r3_injector';
desc | {
"end_byte": 495,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/di/r3_injector_spec.ts"
} |
angular/packages/core/test/di/r3_injector_spec.ts_497_8625 | be('InjectorDef-based createInjector()', () => {
class CircularA {
static ɵprov = ɵɵdefineInjectable({
token: CircularA,
providedIn: null,
factory: () => ɵɵinject(CircularB),
});
}
class CircularB {
static ɵprov = ɵɵdefineInjectable({
token: CircularB,
providedIn: null,
factory: () => ɵɵinject(CircularA),
});
}
class Service {
static ɵprov = ɵɵdefineInjectable({
token: Service,
providedIn: null,
factory: () => new Service(),
});
}
class OptionalService {
static ɵprov = ɵɵdefineInjectable({
token: OptionalService,
providedIn: null,
factory: () => new OptionalService(),
});
}
class StaticService {
constructor(readonly dep: Service) {}
}
const SERVICE_TOKEN = new InjectionToken<Service>('SERVICE_TOKEN');
const STATIC_TOKEN = new InjectionToken<StaticService>('STATIC_TOKEN');
const LOCALE = new InjectionToken<string[]>('LOCALE');
const PRIMITIVE_VALUE = new InjectionToken<string>('PRIMITIVE_VALUE');
const UNDEFINED_VALUE = new InjectionToken<undefined>('UNDEFINED_VALUE');
class ServiceWithDep {
constructor(readonly service: Service) {}
static ɵprov = ɵɵdefineInjectable({
token: ServiceWithDep,
providedIn: null,
// ChildService is derived from ServiceWithDep, so the factory function here must do the right
// thing and create an instance of the requested type if one is given.
factory: (t?: any) => new (t || ServiceWithDep)(ɵɵinject(Service)),
});
}
class ServiceWithOptionalDep {
constructor(@Optional() readonly service: OptionalService | null) {}
static ɵprov = ɵɵdefineInjectable({
token: ServiceWithOptionalDep,
providedIn: null,
factory: () => new ServiceWithOptionalDep(ɵɵinject(OptionalService, InjectFlags.Optional)),
});
}
class ServiceWithMissingDep {
constructor(readonly service: Service) {}
static ɵprov = ɵɵdefineInjectable({
token: ServiceWithMissingDep,
providedIn: null,
factory: () => new ServiceWithMissingDep(ɵɵinject(Service)),
});
}
class ServiceWithMultiDep {
constructor(readonly locale: string[]) {}
static ɵprov = ɵɵdefineInjectable({
token: ServiceWithMultiDep,
providedIn: null,
factory: () => new ServiceWithMultiDep(ɵɵinject(LOCALE)),
});
}
class ServiceTwo {
static ɵprov = ɵɵdefineInjectable({
token: ServiceTwo,
providedIn: null,
factory: () => new ServiceTwo(),
});
}
let deepServiceDestroyed = false;
class DeepService {
static ɵprov = ɵɵdefineInjectable({
token: DeepService,
providedIn: null,
factory: () => new DeepService(),
});
ngOnDestroy(): void {
deepServiceDestroyed = true;
}
}
let eagerServiceCreated: boolean = false;
class EagerService {
static ɵprov = ɵɵdefineInjectable({
token: EagerService,
providedIn: undefined,
factory: () => new EagerService(),
});
constructor() {
eagerServiceCreated = true;
}
}
let deepModuleCreated: boolean = false;
class DeepModule {
constructor(eagerService: EagerService) {
deepModuleCreated = true;
}
static ɵfac = () => new DeepModule(ɵɵinject(EagerService));
static ɵinj = ɵɵdefineInjector({
imports: undefined,
providers: [
EagerService,
{
provide: DeepService,
useFactory: () => {
throw new Error('Not overridden!');
},
},
],
});
static safe() {
return {
ngModule: DeepModule,
providers: [{provide: DeepService}],
};
}
}
class IntermediateModule {
static ɵinj = ɵɵdefineInjector({
imports: [DeepModule.safe()],
providers: [],
});
}
class InjectorWithDep {
constructor(readonly service: Service) {}
static ɵfac = () => new InjectorWithDep(ɵɵinject(Service));
static ɵinj = ɵɵdefineInjector({});
}
class ChildService extends ServiceWithDep {}
abstract class AbstractService {
static ɵprov = ɵɵdefineInjectable({
token: AbstractService,
providedIn: null,
factory: () => new AbstractServiceImpl(),
});
}
class AbstractServiceImpl extends AbstractService {}
class Module {
static ɵinj = ɵɵdefineInjector({
imports: [IntermediateModule],
providers: [
ChildService,
ServiceWithDep,
ServiceWithOptionalDep,
ServiceWithMultiDep,
{provide: LOCALE, multi: true, useValue: 'en'},
{provide: LOCALE, multi: true, useValue: 'es'},
{provide: PRIMITIVE_VALUE, useValue: 'foo'},
{provide: UNDEFINED_VALUE, useValue: undefined},
Service,
{provide: SERVICE_TOKEN, useExisting: Service},
CircularA,
CircularB,
{provide: STATIC_TOKEN, useClass: StaticService, deps: [Service]},
InjectorWithDep,
AbstractService,
],
});
}
const ABSTRACT_SERVICE_TOKEN_WITH_FACTORY = new InjectionToken<AbstractService>(
'ABSTRACT_SERVICE_TOKEN',
{
providedIn: Module,
factory: () => ɵɵinject(AbstractService),
},
);
class OtherModule {
static ɵinj = ɵɵdefineInjector({
imports: undefined,
providers: [],
});
}
class ModuleWithMissingDep {
static ɵinj = ɵɵdefineInjector({
imports: undefined,
providers: [ServiceWithMissingDep],
});
}
class NotAModule {}
class ImportsNotAModule {
static ɵinj = ɵɵdefineInjector({
imports: [NotAModule],
providers: [],
});
}
let scopedServiceDestroyed = false;
class ScopedService {
static ɵprov = ɵɵdefineInjectable({
token: ScopedService,
providedIn: Module,
factory: () => new ScopedService(),
});
ngOnDestroy(): void {
scopedServiceDestroyed = true;
}
}
class WrongScopeService {
static ɵprov = ɵɵdefineInjectable({
token: WrongScopeService,
providedIn: OtherModule,
factory: () => new WrongScopeService(),
});
}
class MultiProviderA {
static ɵinj = ɵɵdefineInjector({
providers: [{provide: LOCALE, multi: true, useValue: 'A'}],
});
}
class MultiProviderB {
static ɵinj = ɵɵdefineInjector({
providers: [{provide: LOCALE, multi: true, useValue: 'B'}],
});
}
class WithProvidersTest {
static ɵinj = ɵɵdefineInjector({
imports: [
{ngModule: MultiProviderA, providers: [{provide: LOCALE, multi: true, useValue: 'C'}]},
MultiProviderB,
],
providers: [],
});
}
let injector: Injector;
beforeEach(() => {
deepModuleCreated = eagerServiceCreated = deepServiceDestroyed = false;
injector = createInjector(Module);
});
it('initializes imported modules before the module being declared', () => {
const moduleRegistrations: string[] = [];
class ChildModule {
static ɵinj = ɵɵdefineInjector({
imports: undefined,
providers: [],
});
constructor() {
moduleRegistrations.push('ChildModule');
}
}
class RootModule {
static ɵinj = ɵɵdefineInjector({
imports: [ChildModule],
providers: [],
});
constructor() {
moduleRegistrations.push('RootModule');
}
}
createInjector(RootModule);
expect(moduleRegistrations).toEqual(['ChildModule', 'RootModule']);
});
it('injects a simple class', () => {
const instance = injector.get(Service);
expect(instance instanceof Service).toBeTruthy();
expect(injector.get(Service)).toBe(instance);
});
it("returns the default value if a provider isn't present", () => {
expect(injector.get(ServiceTwo, null)).toBeNull();
});
it('should throw when no provider defined', () => {
expect(() => injector.get(ServiceTwo)).toThrowError(
`R3InjectorError(Module)[ServiceTwo]: \n` +
` NullInjectorError: No provider for ServiceTwo!`,
);
});
it('should throw without the module name when no module', () => {
const injector = createInjecto | {
"end_byte": 8625,
"start_byte": 497,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/di/r3_injector_spec.ts"
} |
angular/packages/core/test/di/r3_injector_spec.ts_8629_14687 | erviceTwo]);
expect(() => injector.get(ServiceTwo)).toThrowError(
`R3InjectorError[ServiceTwo]: \n` + ` NullInjectorError: No provider for ServiceTwo!`,
);
});
it('should throw with the full path when no provider', () => {
const injector = createInjector(ModuleWithMissingDep);
expect(() => injector.get(ServiceWithMissingDep)).toThrowError(
`R3InjectorError(ModuleWithMissingDep)[ServiceWithMissingDep -> Service]: \n` +
` NullInjectorError: No provider for Service!`,
);
});
it('injects a service with dependencies', () => {
const instance = injector.get(ServiceWithDep);
expect(instance instanceof ServiceWithDep).toBeTrue();
expect(instance.service).toBe(injector.get(Service));
});
it('injects a service with optional dependencies', () => {
const instance = injector.get(ServiceWithOptionalDep);
expect(instance instanceof ServiceWithOptionalDep).toBeTrue();
expect(instance.service).toBe(null);
});
it('injects a service with dependencies on multi-providers', () => {
const instance = injector.get(ServiceWithMultiDep);
expect(instance instanceof ServiceWithMultiDep).toBeTrue();
expect(instance.locale).toEqual(['en', 'es']);
});
it('should process "InjectionTypeWithProviders" providers after imports injection type', () => {
injector = createInjector(WithProvidersTest);
expect(injector.get(LOCALE)).toEqual(['A', 'B', 'C']);
});
it('injects an injector with dependencies', () => {
const instance = injector.get(InjectorWithDep);
expect(instance instanceof InjectorWithDep).toBeTrue();
expect(instance.service).toBe(injector.get(Service));
});
it('injects a token with useExisting', () => {
const instance = injector.get(SERVICE_TOKEN);
expect(instance).toBe(injector.get(Service));
});
it('injects a useValue token with a primitive value', () => {
const value = injector.get(PRIMITIVE_VALUE);
expect(value).toEqual('foo');
});
it('injects a useValue token with value undefined', () => {
const value = injector.get(UNDEFINED_VALUE);
expect(value).toBeUndefined();
});
it('instantiates a class with useClass and deps', () => {
const instance = injector.get(STATIC_TOKEN);
expect(instance instanceof StaticService).toBeTruthy();
expect(instance.dep).toBe(injector.get(Service));
});
it('allows injecting itself via INJECTOR', () => {
expect(injector.get(INJECTOR)).toBe(injector);
});
it('allows injecting itself via Injector', () => {
expect(injector.get(Injector)).toBe(injector);
});
it('allows injecting a deeply imported service', () => {
expect(injector.get(DeepService) instanceof DeepService).toBeTruthy();
});
it('allows injecting a scoped service', () => {
const instance = injector.get(ScopedService);
expect(instance instanceof ScopedService).toBeTruthy();
expect(instance).toBe(injector.get(ScopedService));
});
it('allows injecting an inherited service', () => {
const instance = injector.get(ChildService);
expect(instance instanceof ChildService).toBe(true);
});
it('does not create instances of a service not in scope', () => {
expect(injector.get(WrongScopeService, null)).toBeNull();
});
it('eagerly instantiates the injectordef types', () => {
expect(deepModuleCreated).toBe(true, 'DeepModule not instantiated');
expect(eagerServiceCreated).toBe(true, 'EagerSerivce not instantiated');
});
it('calls ngOnDestroy on services when destroyed', () => {
injector.get(DeepService);
expect(deepServiceDestroyed).toBe(false, 'DeepService already destroyed');
(injector as R3Injector).destroy();
expect(deepServiceDestroyed).toBe(true, 'DeepService not destroyed');
});
it('calls ngOnDestroy on scoped providers', () => {
injector.get(ScopedService);
expect(scopedServiceDestroyed).toBe(false, 'ScopedService already destroyed');
(injector as R3Injector).destroy();
expect(scopedServiceDestroyed).toBe(true, 'ScopedService not destroyed');
});
it('does not allow injection after destroy', () => {
(injector as R3Injector).destroy();
expect(() => injector.get(DeepService)).toThrowError(
'NG0205: Injector has already been destroyed.',
);
});
it('does not allow double destroy', () => {
(injector as R3Injector).destroy();
expect(() => (injector as R3Injector).destroy()).toThrowError(
'NG0205: Injector has already been destroyed.',
);
});
it('should not crash when importing something that has no ɵinj', () => {
injector = createInjector(ImportsNotAModule);
expect(injector.get(ImportsNotAModule)).toBeDefined();
});
it('injects an abstract class', () => {
const instance = injector.get(AbstractService);
expect(instance instanceof AbstractServiceImpl).toBeTruthy();
expect(injector.get(AbstractService)).toBe(instance);
});
it('injects an abstract class in an InjectionToken factory', () => {
const instance = injector.get(ABSTRACT_SERVICE_TOKEN_WITH_FACTORY);
expect(instance instanceof AbstractServiceImpl).toBeTruthy();
expect(injector.get(ABSTRACT_SERVICE_TOKEN_WITH_FACTORY)).toBe(instance);
});
describe('error handling', () => {
it('throws an error when a token is not found', () => {
expect(() => injector.get(ServiceTwo)).toThrow();
});
it('throws an error on circular deps', () => {
expect(() => injector.get(CircularA)).toThrow();
});
it("should throw when it can't resolve all arguments", () => {
class MissingArgumentType {
constructor(missingType: any) {}
}
class ErrorModule {
static ɵinj = ɵɵdefineInjector({providers: [MissingArgumentType]});
}
expect(() => createInjector(ErrorModule).get(MissingArgumentType)).toThrowError(
"NG0204: Can't resolve all parameters for MissingArgumentType: (?).",
);
});
});
});
| {
"end_byte": 14687,
"start_byte": 8629,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/di/r3_injector_spec.ts"
} |
angular/packages/core/test/di/injector_spec.ts_0_814 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Injector} from '@angular/core';
describe('Injector.NULL', () => {
it('should throw if no arg is given', () => {
expect(() => Injector.NULL.get('someToken')).toThrowError(
'NullInjectorError: No provider for someToken!',
);
});
it('should throw if THROW_IF_NOT_FOUND is given', () => {
expect(() => Injector.NULL.get('someToken', Injector.THROW_IF_NOT_FOUND)).toThrowError(
'NullInjectorError: No provider for someToken!',
);
});
it('should return the default value', () => {
expect(Injector.NULL.get('someToken', 'notFound')).toEqual('notFound');
});
});
| {
"end_byte": 814,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/di/injector_spec.ts"
} |
angular/packages/core/test/di/inject_flags_spec.ts_0_777 | /**
* @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 {InjectFlags, InternalInjectFlags} from '../../src/di/interface/injector';
describe('InjectFlags', () => {
it('should always match InternalInjectFlags', () => {
expect(InjectFlags.Default).toEqual(InternalInjectFlags.Default as number);
expect(InjectFlags.Host).toEqual(InternalInjectFlags.Host as number);
expect(InjectFlags.Self).toEqual(InternalInjectFlags.Self as number);
expect(InjectFlags.SkipSelf).toEqual(InternalInjectFlags.SkipSelf as number);
expect(InjectFlags.Optional).toEqual(InternalInjectFlags.Optional as number);
});
});
| {
"end_byte": 777,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/di/inject_flags_spec.ts"
} |
angular/packages/core/test/di/forward_ref_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 {Type} from '@angular/core';
import {forwardRef, resolveForwardRef} from '@angular/core/src/di';
describe('forwardRef', () => {
it('should wrap and unwrap the reference', () => {
const ref = forwardRef(() => String);
expect(ref instanceof Type).toBe(true);
expect(resolveForwardRef(ref)).toBe(String);
});
});
| {
"end_byte": 538,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/di/forward_ref_spec.ts"
} |
angular/packages/core/test/di/static_injector_spec.ts_0_7224 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {forwardRef, Inject, InjectFlags, Injector, Self, SkipSelf} from '@angular/core';
import {stringify} from '../../src/util/stringify';
class Engine {
static PROVIDER = {provide: Engine, useClass: Engine, deps: []};
}
class BrokenEngine {
static PROVIDER = {provide: Engine, useClass: BrokenEngine, deps: []};
constructor() {
throw new Error('Broken Engine');
}
}
class TurboEngine extends Engine {
static override PROVIDER = {provide: Engine, useClass: TurboEngine, deps: []};
}
class Car {
static PROVIDER = {provide: Car, useClass: Car, deps: [Engine]};
constructor(public engine: Engine) {}
}
class SportsCar extends Car {
static override PROVIDER = {provide: Car, useClass: SportsCar, deps: [Engine]};
}
describe('child', () => {
it('should load instances from parent injector', () => {
const parent = Injector.create({providers: [Engine.PROVIDER]});
const child = Injector.create({providers: [], parent});
const engineFromParent = parent.get(Engine);
const engineFromChild = child.get(Engine);
expect(engineFromChild).toBe(engineFromParent);
});
it('should not use the child providers when resolving the dependencies of a parent provider', () => {
const parent = Injector.create({providers: [Car.PROVIDER, Engine.PROVIDER]});
const child = Injector.create({providers: [TurboEngine.PROVIDER], parent});
const carFromChild = child.get<Car>(Car);
expect(carFromChild.engine).toBeInstanceOf(Engine);
});
it('should create new instance in a child injector', () => {
const parent = Injector.create({providers: [Engine.PROVIDER]});
const child = Injector.create({providers: [TurboEngine.PROVIDER], parent});
const engineFromParent = parent.get(Engine);
const engineFromChild = child.get(Engine);
expect(engineFromParent).not.toBe(engineFromChild);
expect(engineFromChild).toBeInstanceOf(TurboEngine);
});
it('should give access to parent', () => {
const parent = Injector.create({providers: []});
const child = Injector.create({providers: [], parent});
expect((child as any).parent).toBe(parent);
});
});
describe('instantiate', () => {
it('should instantiate an object in the context of the injector', () => {
const inj = Injector.create({providers: [Engine.PROVIDER]});
const childInj = Injector.create({providers: [Car.PROVIDER], parent: inj});
const car = childInj.get<Car>(Car);
expect(car).toBeInstanceOf(Car);
expect(car.engine).toBe(inj.get(Engine));
});
});
describe('dependency resolution', () => {
describe('@Self()', () => {
it('should return a dependency from self', () => {
const inj = Injector.create({
providers: [
Engine.PROVIDER,
{provide: Car, useFactory: (e: Engine) => new Car(e), deps: [[Engine, new Self()]]},
],
});
expect(inj.get(Car)).toBeInstanceOf(Car);
});
it('should throw when not requested provider on self', () => {
const parent = Injector.create({providers: [Engine.PROVIDER]});
const child = Injector.create({
providers: [
{provide: Car, useFactory: (e: Engine) => new Car(e), deps: [[Engine, new Self()]]},
],
parent,
});
expect(() => child.get(Car)).toThrowError(
`R3InjectorError[${stringify(Car)} -> ${stringify(Engine)}]: \n` +
' NullInjectorError: No provider for Engine!',
);
});
it('should return a default value when not requested provider on self', () => {
const car = new SportsCar(new Engine());
const injector = Injector.create({providers: []});
expect(injector.get<Car | null>(Car, null, InjectFlags.Self)).toBeNull();
expect(injector.get<Car>(Car, car, InjectFlags.Self)).toBe(car);
});
it('should return a default value when not requested provider on self and optional', () => {
const flags = InjectFlags.Self | InjectFlags.Optional;
const injector = Injector.create({providers: []});
expect(injector.get<Car | null>(Car, null, InjectFlags.Self)).toBeNull();
expect(injector.get<Car | number>(Car, 0, flags)).toBe(0);
});
it(`should return null when not requested provider on self and optional`, () => {
const flags = InjectFlags.Self | InjectFlags.Optional;
const injector = Injector.create({providers: []});
expect(injector.get<Car | null>(Car, undefined, flags)).toBeNull();
});
it('should throw error when not requested provider on self', () => {
const injector = Injector.create({providers: []});
expect(() => injector.get(Car, undefined, InjectFlags.Self)).toThrowError(
`R3InjectorError[${stringify(Car)}]: \n` +
` NullInjectorError: No provider for ${stringify(Car)}!`,
);
});
});
describe('default', () => {
it('should skip self', () => {
const parent = Injector.create({providers: [Engine.PROVIDER]});
const child = Injector.create({
providers: [
TurboEngine.PROVIDER,
{provide: Car, useFactory: (e: Engine) => new Car(e), deps: [[SkipSelf, Engine]]},
],
parent,
});
expect(child.get<Car>(Car).engine).toBeInstanceOf(Engine);
});
});
});
describe('resolve', () => {
it('should throw when mixing multi providers with regular providers', () => {
expect(() => {
Injector.create([
{provide: Engine, useClass: BrokenEngine, deps: [], multi: true},
Engine.PROVIDER,
]);
}).toThrowError(/Cannot mix multi providers and regular providers/);
expect(() => {
Injector.create([
Engine.PROVIDER,
{provide: Engine, useClass: BrokenEngine, deps: [], multi: true},
]);
}).toThrowError(/Cannot mix multi providers and regular providers/);
});
it('should resolve forward references', () => {
const injector = Injector.create({
providers: [
[{provide: forwardRef(() => BrokenEngine), useClass: forwardRef(() => Engine), deps: []}],
{
provide: forwardRef(() => String),
useFactory: (e: any) => e,
deps: [forwardRef(() => BrokenEngine)],
},
],
});
expect(injector.get(String)).toBeInstanceOf(Engine);
expect(injector.get(BrokenEngine)).toBeInstanceOf(Engine);
});
it('should support overriding factory dependencies with dependency annotations', () => {
const injector = Injector.create({
providers: [
Engine.PROVIDER,
{provide: 'token', useFactory: (e: any) => e, deps: [[new Inject(Engine)]]},
],
});
expect(injector.get('token')).toBeInstanceOf(Engine);
});
});
describe('displayName', () => {
it('should work', () => {
expect(
Injector.create({
providers: [Engine.PROVIDER, {provide: BrokenEngine, useValue: null}],
}).toString(),
).toEqual(
'R3Injector[Engine, BrokenEngine, InjectionToken INJECTOR, InjectionToken INJECTOR_DEF_TYPES, InjectionToken ENVIRONMENT_INITIALIZER]',
);
});
});
| {
"end_byte": 7224,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/di/static_injector_spec.ts"
} |
angular/packages/core/test/change_detection/util.ts_0_4109 | /**
* @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 {
IterableChangeRecord,
IterableChanges,
} from '@angular/core/src/change_detection/differs/iterable_differs';
import {
KeyValueChangeRecord,
KeyValueChanges,
} from '@angular/core/src/change_detection/differs/keyvalue_differs';
import {stringify} from '../../src/util/stringify';
export function iterableDifferToString<V>(iterableChanges: IterableChanges<V>) {
const collection: string[] = [];
iterableChanges.forEachItem((record: IterableChangeRecord<V>) =>
collection.push(icrAsString(record)),
);
const previous: string[] = [];
iterableChanges.forEachPreviousItem((record: IterableChangeRecord<V>) =>
previous.push(icrAsString(record)),
);
const additions: string[] = [];
iterableChanges.forEachAddedItem((record: IterableChangeRecord<V>) =>
additions.push(icrAsString(record)),
);
const moves: string[] = [];
iterableChanges.forEachMovedItem((record: IterableChangeRecord<V>) =>
moves.push(icrAsString(record)),
);
const removals: string[] = [];
iterableChanges.forEachRemovedItem((record: IterableChangeRecord<V>) =>
removals.push(icrAsString(record)),
);
const identityChanges: string[] = [];
iterableChanges.forEachIdentityChange((record: IterableChangeRecord<V>) =>
identityChanges.push(icrAsString(record)),
);
return iterableChangesAsString({
collection,
previous,
additions,
moves,
removals,
identityChanges,
});
}
function icrAsString<V>(icr: IterableChangeRecord<V>): string {
return icr.previousIndex === icr.currentIndex
? stringify(icr.item)
: stringify(icr.item) +
'[' +
stringify(icr.previousIndex) +
'->' +
stringify(icr.currentIndex) +
']';
}
export function iterableChangesAsString({
collection = [] as any,
previous = [] as any,
additions = [] as any,
moves = [] as any,
removals = [] as any,
identityChanges = [] as any,
}): string {
return (
'collection: ' +
collection.join(', ') +
'\n' +
'previous: ' +
previous.join(', ') +
'\n' +
'additions: ' +
additions.join(', ') +
'\n' +
'moves: ' +
moves.join(', ') +
'\n' +
'removals: ' +
removals.join(', ') +
'\n' +
'identityChanges: ' +
identityChanges.join(', ') +
'\n'
);
}
function kvcrAsString(kvcr: KeyValueChangeRecord<string, any>) {
return Object.is(kvcr.previousValue, kvcr.currentValue)
? stringify(kvcr.key)
: stringify(kvcr.key) +
'[' +
stringify(kvcr.previousValue) +
'->' +
stringify(kvcr.currentValue) +
']';
}
export function kvChangesAsString(kvChanges: KeyValueChanges<string, any>) {
const map: string[] = [];
const previous: string[] = [];
const changes: string[] = [];
const additions: string[] = [];
const removals: string[] = [];
kvChanges.forEachItem((r) => map.push(kvcrAsString(r)));
kvChanges.forEachPreviousItem((r) => previous.push(kvcrAsString(r)));
kvChanges.forEachChangedItem((r) => changes.push(kvcrAsString(r)));
kvChanges.forEachAddedItem((r) => additions.push(kvcrAsString(r)));
kvChanges.forEachRemovedItem((r) => removals.push(kvcrAsString(r)));
return testChangesAsString({map, previous, additions, changes, removals});
}
export function testChangesAsString({
map,
previous,
additions,
changes,
removals,
}: {
map?: any[];
previous?: any[];
additions?: any[];
changes?: any[];
removals?: any[];
}): string {
if (!map) map = [];
if (!previous) previous = [];
if (!additions) additions = [];
if (!changes) changes = [];
if (!removals) removals = [];
return (
'map: ' +
map.join(', ') +
'\n' +
'previous: ' +
previous.join(', ') +
'\n' +
'additions: ' +
additions.join(', ') +
'\n' +
'changes: ' +
changes.join(', ') +
'\n' +
'removals: ' +
removals.join(', ') +
'\n'
);
}
| {
"end_byte": 4109,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/change_detection/util.ts"
} |
angular/packages/core/test/change_detection/differs/keyvalue_differs_spec.ts_0_1196 | /**
* @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 {KeyValueDiffer, KeyValueDifferFactory, KeyValueDiffers, NgModule} from '@angular/core';
import {TestBed} from '@angular/core/testing';
describe('KeyValueDiffers', function () {
it('should support .extend in root NgModule', () => {
const DIFFER: KeyValueDiffer<any, any> = {} as any;
const log: string[] = [];
class MyKeyValueDifferFactory implements KeyValueDifferFactory {
supports(objects: any): boolean {
log.push('supports', objects);
return true;
}
create<K, V>(): KeyValueDiffer<K, V> {
log.push('create');
return DIFFER;
}
}
@NgModule({providers: [KeyValueDiffers.extend([new MyKeyValueDifferFactory()])]})
class MyModule {}
TestBed.configureTestingModule({imports: [MyModule]});
const differs = TestBed.inject(KeyValueDiffers);
const differ = differs.find('VALUE').create();
expect(differ).toEqual(DIFFER);
expect(log).toEqual(['supports', 'VALUE', 'create']);
});
});
| {
"end_byte": 1196,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/change_detection/differs/keyvalue_differs_spec.ts"
} |
angular/packages/core/test/change_detection/differs/iterable_differs_spec.ts_0_3372 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Injector,
IterableDiffer,
IterableDifferFactory,
IterableDiffers,
NgModule,
TrackByFunction,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
describe('IterableDiffers', function () {
let factory1: jasmine.SpyObj<IterableDifferFactory>;
let factory2: jasmine.SpyObj<IterableDifferFactory>;
let factory3: jasmine.SpyObj<IterableDifferFactory>;
beforeEach(() => {
const getFactory = () => jasmine.createSpyObj('IterableDifferFactory', ['supports']);
factory1 = getFactory();
factory2 = getFactory();
factory3 = getFactory();
});
it('should throw when no suitable implementation found', () => {
const differs = new IterableDiffers([]);
expect(() => differs.find('some object')).toThrowError(
/Cannot find a differ supporting object 'some object'/,
);
});
it('should return the first suitable implementation', () => {
factory1.supports.and.returnValue(false);
factory2.supports.and.returnValue(true);
factory3.supports.and.returnValue(true);
const differs = IterableDiffers.create([factory1, factory2, factory3]);
expect(differs.find('some object')).toBe(factory2);
});
it('should copy over differs from the parent repo', () => {
factory1.supports.and.returnValue(true);
factory2.supports.and.returnValue(false);
const parent = IterableDiffers.create([factory1]);
const child = IterableDiffers.create([factory2], parent);
// @ts-expect-error private member
expect(child.factories).toEqual([factory2, factory1]);
});
describe('.extend()', () => {
it('should extend di-inherited differs', () => {
const differ = new IterableDiffers([factory1]);
const injector = Injector.create({providers: [{provide: IterableDiffers, useValue: differ}]});
const childInjector = Injector.create({
providers: [IterableDiffers.extend([factory2])],
parent: injector,
});
// @ts-expect-error factories is a private member
expect(injector.get<IterableDiffers>(IterableDiffers).factories).toEqual([factory1]);
// @ts-expect-error factories is a private member
expect(childInjector.get<IterableDiffers>(IterableDiffers).factories).toEqual([
factory2,
factory1,
]);
});
it('should support .extend in root NgModule', () => {
const DIFFER: IterableDiffer<any> = {} as any;
const log: string[] = [];
class MyIterableDifferFactory implements IterableDifferFactory {
supports(objects: any): boolean {
log.push('supports', objects);
return true;
}
create<V>(trackByFn?: TrackByFunction<V>): IterableDiffer<V> {
log.push('create');
return DIFFER;
}
}
@NgModule({providers: [IterableDiffers.extend([new MyIterableDifferFactory()])]})
class MyModule {}
TestBed.configureTestingModule({imports: [MyModule]});
const differs = TestBed.inject(IterableDiffers);
const differ = differs.find('VALUE').create(null!);
expect(differ).toEqual(DIFFER);
expect(log).toEqual(['supports', 'VALUE', 'create']);
});
});
});
| {
"end_byte": 3372,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/change_detection/differs/iterable_differs_spec.ts"
} |
angular/packages/core/test/change_detection/differs/default_iterable_differ_spec.ts_0_819 | /**
* @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 {
DefaultIterableDiffer,
DefaultIterableDifferFactory,
} from '@angular/core/src/change_detection/differs/default_iterable_differ';
import {TestIterable} from '../../util/iterable';
import {iterableChangesAsString, iterableDifferToString} from '../util';
class ItemWithId {
constructor(private id: string) {}
toString() {
return `{id: ${this.id}}`;
}
}
class ComplexItem {
constructor(
private id: string,
private color: string,
) {}
toString() {
return `{id: ${this.id}, color: ${this.color}}`;
}
}
// TODO(vicb): UnmodifiableListView / frozen object when implemented | {
"end_byte": 819,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/change_detection/differs/default_iterable_differ_spec.ts"
} |
angular/packages/core/test/change_detection/differs/default_iterable_differ_spec.ts_820_7755 | describe('iterable differ', function () {
describe('DefaultIterableDiffer', function () {
let differ: DefaultIterableDiffer<any>;
beforeEach(() => {
differ = new DefaultIterableDiffer();
});
it('should support list and iterables', () => {
const f = new DefaultIterableDifferFactory();
expect(f.supports([])).toBeTruthy();
expect(f.supports(new TestIterable())).toBeTruthy();
expect(f.supports(new Map())).toBeFalsy();
expect(f.supports(null)).toBeFalsy();
});
it('should support iterables', () => {
const l: any = new TestIterable();
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({collection: []}));
l.list = [1];
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({collection: ['1[null->0]'], additions: ['1[null->0]']}),
);
l.list = [2, 1];
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['2[null->0]', '1[0->1]'],
previous: ['1[0->1]'],
additions: ['2[null->0]'],
moves: ['1[0->1]'],
}),
);
});
it('should detect additions', () => {
const l: any[] = [];
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(iterableChangesAsString({collection: []}));
l.push('a');
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({collection: ['a[null->0]'], additions: ['a[null->0]']}),
);
l.push('b');
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['a', 'b[null->1]'],
previous: ['a'],
additions: ['b[null->1]'],
}),
);
});
it('should support changing the reference', () => {
let l = [0];
differ.check(l);
l = [1, 0];
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['1[null->0]', '0[0->1]'],
previous: ['0[0->1]'],
additions: ['1[null->0]'],
moves: ['0[0->1]'],
}),
);
l = [2, 1, 0];
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['2[null->0]', '1[0->1]', '0[1->2]'],
previous: ['1[0->1]', '0[1->2]'],
additions: ['2[null->0]'],
moves: ['1[0->1]', '0[1->2]'],
}),
);
});
it('should handle swapping element', () => {
const l = [1, 2];
differ.check(l);
l.length = 0;
l.push(2);
l.push(1);
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['2[1->0]', '1[0->1]'],
previous: ['1[0->1]', '2[1->0]'],
moves: ['2[1->0]', '1[0->1]'],
}),
);
});
it('should handle incremental swapping element', () => {
const l = ['a', 'b', 'c'];
differ.check(l);
l.splice(1, 1);
l.splice(0, 0, 'b');
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['b[1->0]', 'a[0->1]', 'c'],
previous: ['a[0->1]', 'b[1->0]', 'c'],
moves: ['b[1->0]', 'a[0->1]'],
}),
);
l.splice(1, 1);
l.push('a');
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['b', 'c[2->1]', 'a[1->2]'],
previous: ['b', 'a[1->2]', 'c[2->1]'],
moves: ['c[2->1]', 'a[1->2]'],
}),
);
});
it('should detect changes in list', () => {
const l: any[] = [];
differ.check(l);
l.push('a');
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({collection: ['a[null->0]'], additions: ['a[null->0]']}),
);
l.push('b');
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['a', 'b[null->1]'],
previous: ['a'],
additions: ['b[null->1]'],
}),
);
l.push('c');
l.push('d');
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['a', 'b', 'c[null->2]', 'd[null->3]'],
previous: ['a', 'b'],
additions: ['c[null->2]', 'd[null->3]'],
}),
);
l.splice(2, 1);
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['a', 'b', 'd[3->2]'],
previous: ['a', 'b', 'c[2->null]', 'd[3->2]'],
moves: ['d[3->2]'],
removals: ['c[2->null]'],
}),
);
l.length = 0;
l.push('d');
l.push('c');
l.push('b');
l.push('a');
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['d[2->0]', 'c[null->1]', 'b[1->2]', 'a[0->3]'],
previous: ['a[0->3]', 'b[1->2]', 'd[2->0]'],
additions: ['c[null->1]'],
moves: ['d[2->0]', 'b[1->2]', 'a[0->3]'],
}),
);
});
it('should ignore [NaN] != [NaN]', () => {
const l = [NaN];
differ.check(l);
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({collection: [NaN], previous: [NaN]}),
);
});
it('should detect [NaN] moves', () => {
const l: any[] = [NaN, NaN];
differ.check(l);
l.unshift('foo');
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['foo[null->0]', 'NaN[0->1]', 'NaN[1->2]'],
previous: ['NaN[0->1]', 'NaN[1->2]'],
additions: ['foo[null->0]'],
moves: ['NaN[0->1]', 'NaN[1->2]'],
}),
);
});
it('should remove and add same item', () => {
const l = ['a', 'b', 'c'];
differ.check(l);
l.splice(1, 1);
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['a', 'c[2->1]'],
previous: ['a', 'b[1->null]', 'c[2->1]'],
moves: ['c[2->1]'],
removals: ['b[1->null]'],
}),
);
l.splice(1, 0, 'b');
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['a', 'b[null->1]', 'c[1->2]'],
previous: ['a', 'c[1->2]'],
additions: ['b[null->1]'],
moves: ['c[1->2]'],
}),
);
}); | {
"end_byte": 7755,
"start_byte": 820,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/change_detection/differs/default_iterable_differ_spec.ts"
} |
angular/packages/core/test/change_detection/differs/default_iterable_differ_spec.ts_7761_9885 | it('should support duplicates', () => {
const l = ['a', 'a', 'a', 'b', 'b'];
differ.check(l);
l.splice(0, 1);
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['a', 'a', 'b[3->2]', 'b[4->3]'],
previous: ['a', 'a', 'a[2->null]', 'b[3->2]', 'b[4->3]'],
moves: ['b[3->2]', 'b[4->3]'],
removals: ['a[2->null]'],
}),
);
});
it('should support insertions/moves', () => {
const l = ['a', 'a', 'b', 'b'];
differ.check(l);
l.splice(0, 0, 'b');
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['b[2->0]', 'a[0->1]', 'a[1->2]', 'b', 'b[null->4]'],
previous: ['a[0->1]', 'a[1->2]', 'b[2->0]', 'b'],
additions: ['b[null->4]'],
moves: ['b[2->0]', 'a[0->1]', 'a[1->2]'],
}),
);
});
it('should not report unnecessary moves', () => {
const l = ['a', 'b', 'c'];
differ.check(l);
l.length = 0;
l.push('b');
l.push('a');
l.push('c');
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['b[1->0]', 'a[0->1]', 'c'],
previous: ['a[0->1]', 'b[1->0]', 'c'],
moves: ['b[1->0]', 'a[0->1]'],
}),
);
});
// https://github.com/angular/angular/issues/17852
it('support re-insertion', () => {
const l = ['a', '*', '*', 'd', '-', '-', '-', 'e'];
differ.check(l);
l[1] = 'b';
l[5] = 'c';
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['a', 'b[null->1]', '*[1->2]', 'd', '-', 'c[null->5]', '-[5->6]', 'e'],
previous: ['a', '*[1->2]', '*[2->null]', 'd', '-', '-[5->6]', '-[6->null]', 'e'],
additions: ['b[null->1]', 'c[null->5]'],
moves: ['*[1->2]', '-[5->6]'],
removals: ['*[2->null]', '-[6->null]'],
}),
);
}); | {
"end_byte": 9885,
"start_byte": 7761,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/change_detection/differs/default_iterable_differ_spec.ts"
} |
angular/packages/core/test/change_detection/differs/default_iterable_differ_spec.ts_9891_16366 | describe('forEachOperation', () => {
function stringifyItemChange(
record: any,
p: number | null,
c: number | null,
originalIndex: number,
) {
const suffix = originalIndex == null ? '' : ' [o=' + originalIndex + ']';
const value = record.item;
if (record.currentIndex == null) {
return `REMOVE ${value} (${p} -> VOID)${suffix}`;
} else if (record.previousIndex == null) {
return `INSERT ${value} (VOID -> ${c})${suffix}`;
} else {
return `MOVE ${value} (${p} -> ${c})${suffix}`;
}
}
function modifyArrayUsingOperation(
arr: number[],
endData: any[],
prev: number | null,
next: number | null,
) {
let value: number = null!;
if (prev == null) {
// "next" index is guaranteed to be set since the previous index is
// not defined and therefore a new entry is added.
value = endData[next!];
arr.splice(next!, 0, value);
} else if (next == null) {
value = arr[prev];
arr.splice(prev, 1);
} else {
value = arr[prev];
arr.splice(prev, 1);
arr.splice(next, 0, value);
}
return value;
}
it('should trigger a series of insert/move/remove changes for inputs that have been diffed', () => {
const startData = [0, 1, 2, 3, 4, 5];
const endData = [6, 2, 7, 0, 4, 8];
differ = differ.diff(startData)!;
differ = differ.diff(endData)!;
const operations: string[] = [];
differ.forEachOperation((item: any, prev: number | null, next: number | null) => {
const value = modifyArrayUsingOperation(startData, endData, prev, next);
operations.push(stringifyItemChange(item, prev, next, item.previousIndex));
});
expect(operations).toEqual([
'INSERT 6 (VOID -> 0)',
'MOVE 2 (3 -> 1) [o=2]',
'INSERT 7 (VOID -> 2)',
'REMOVE 1 (4 -> VOID) [o=1]',
'REMOVE 3 (4 -> VOID) [o=3]',
'REMOVE 5 (5 -> VOID) [o=5]',
'INSERT 8 (VOID -> 5)',
]);
expect(startData).toEqual(endData);
});
it('should consider inserting/removing/moving items with respect to items that have not moved at all', () => {
const startData = [0, 1, 2, 3];
const endData = [2, 1];
differ = differ.diff(startData)!;
differ = differ.diff(endData)!;
const operations: string[] = [];
differ.forEachOperation((item: any, prev: number | null, next: number | null) => {
modifyArrayUsingOperation(startData, endData, prev, next);
operations.push(stringifyItemChange(item, prev, next, item.previousIndex));
});
expect(operations).toEqual([
'REMOVE 0 (0 -> VOID) [o=0]',
'MOVE 2 (1 -> 0) [o=2]',
'REMOVE 3 (2 -> VOID) [o=3]',
]);
expect(startData).toEqual(endData);
});
it('should be able to manage operations within a criss/cross of move operations', () => {
const startData = [1, 2, 3, 4, 5, 6];
const endData = [3, 6, 4, 9, 1, 2];
differ = differ.diff(startData)!;
differ = differ.diff(endData)!;
const operations: string[] = [];
differ.forEachOperation((item: any, prev: number | null, next: number | null) => {
modifyArrayUsingOperation(startData, endData, prev, next);
operations.push(stringifyItemChange(item, prev, next, item.previousIndex));
});
expect(operations).toEqual([
'MOVE 3 (2 -> 0) [o=2]',
'MOVE 6 (5 -> 1) [o=5]',
'MOVE 4 (4 -> 2) [o=3]',
'INSERT 9 (VOID -> 3)',
'REMOVE 5 (6 -> VOID) [o=4]',
]);
expect(startData).toEqual(endData);
});
it('should skip moves for multiple nodes that have not moved', () => {
const startData = [0, 1, 2, 3, 4];
const endData = [4, 1, 2, 3, 0, 5];
differ = differ.diff(startData)!;
differ = differ.diff(endData)!;
const operations: string[] = [];
differ.forEachOperation((item: any, prev: number | null, next: number | null) => {
modifyArrayUsingOperation(startData, endData, prev, next);
operations.push(stringifyItemChange(item, prev, next, item.previousIndex));
});
expect(operations).toEqual([
'MOVE 4 (4 -> 0) [o=4]',
'MOVE 1 (2 -> 1) [o=1]',
'MOVE 2 (3 -> 2) [o=2]',
'MOVE 3 (4 -> 3) [o=3]',
'INSERT 5 (VOID -> 5)',
]);
expect(startData).toEqual(endData);
});
it('should not fail', () => {
const startData = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
const endData = [10, 11, 1, 5, 7, 8, 0, 5, 3, 6];
differ = differ.diff(startData)!;
differ = differ.diff(endData)!;
const operations: string[] = [];
differ.forEachOperation((item: any, prev: number | null, next: number | null) => {
modifyArrayUsingOperation(startData, endData, prev, next);
operations.push(stringifyItemChange(item, prev, next, item.previousIndex));
});
expect(operations).toEqual([
'MOVE 10 (10 -> 0) [o=10]',
'MOVE 11 (11 -> 1) [o=11]',
'MOVE 1 (3 -> 2) [o=1]',
'MOVE 5 (7 -> 3) [o=5]',
'MOVE 7 (9 -> 4) [o=7]',
'MOVE 8 (10 -> 5) [o=8]',
'REMOVE 2 (7 -> VOID) [o=2]',
'INSERT 5 (VOID -> 7)',
'REMOVE 4 (9 -> VOID) [o=4]',
'REMOVE 9 (10 -> VOID) [o=9]',
]);
expect(startData).toEqual(endData);
});
it('should trigger nothing when the list is completely full of replaced items that are tracked by the index', () => {
differ = new DefaultIterableDiffer((index: number) => index);
const startData = [1, 2, 3, 4];
const endData = [5, 6, 7, 8];
differ = differ.diff(startData)!;
differ = differ.diff(endData)!;
const operations: string[] = [];
differ.forEachOperation((item: any, prev: number | null, next: number | null) => {
const value = modifyArrayUsingOperation(startData, endData, prev, next);
operations.push(stringifyItemChange(item, prev, next, item.previousIndex));
});
expect(operations).toEqual([]);
});
}); | {
"end_byte": 16366,
"start_byte": 9891,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/change_detection/differs/default_iterable_differ_spec.ts"
} |
angular/packages/core/test/change_detection/differs/default_iterable_differ_spec.ts_16372_22894 | describe('diff', () => {
it('should return self when there is a change', () => {
expect(differ.diff(['a', 'b'])).toBe(differ);
});
it('should return null when there is no change', () => {
differ.diff(['a', 'b']);
expect(differ.diff(['a', 'b'])).toEqual(null);
});
it('should treat null as an empty list', () => {
differ.diff(['a', 'b']);
expect(iterableDifferToString(differ.diff(null!)!)).toEqual(
iterableChangesAsString({
previous: ['a[0->null]', 'b[1->null]'],
removals: ['a[0->null]', 'b[1->null]'],
}),
);
});
it('should throw when given an invalid collection', () => {
expect(() => differ.diff('invalid')).toThrowError(/Error trying to diff 'invalid'/);
});
});
});
describe('trackBy function by id', function () {
let differ: any;
const trackByItemId = (index: number, item: any): any => item.id;
const buildItemList = (list: string[]) => list.map((val) => new ItemWithId(val));
beforeEach(() => {
differ = new DefaultIterableDiffer(trackByItemId);
});
it('should treat the collection as dirty if identity changes', () => {
differ.diff(buildItemList(['a']));
expect(differ.diff(buildItemList(['a']))).toBe(differ);
});
it('should treat seen records as identity changes, not additions', () => {
let l = buildItemList(['a', 'b', 'c']);
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: [`{id: a}[null->0]`, `{id: b}[null->1]`, `{id: c}[null->2]`],
additions: [`{id: a}[null->0]`, `{id: b}[null->1]`, `{id: c}[null->2]`],
}),
);
l = buildItemList(['a', 'b', 'c']);
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: [`{id: a}`, `{id: b}`, `{id: c}`],
identityChanges: [`{id: a}`, `{id: b}`, `{id: c}`],
previous: [`{id: a}`, `{id: b}`, `{id: c}`],
}),
);
});
it('should have updated properties in identity change collection', () => {
let l = [new ComplexItem('a', 'blue'), new ComplexItem('b', 'yellow')];
differ.check(l);
l = [new ComplexItem('a', 'orange'), new ComplexItem('b', 'red')];
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: [`{id: a, color: orange}`, `{id: b, color: red}`],
identityChanges: [`{id: a, color: orange}`, `{id: b, color: red}`],
previous: [`{id: a, color: orange}`, `{id: b, color: red}`],
}),
);
});
it('should track moves normally', () => {
let l = buildItemList(['a', 'b', 'c']);
differ.check(l);
l = buildItemList(['b', 'a', 'c']);
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['{id: b}[1->0]', '{id: a}[0->1]', '{id: c}'],
identityChanges: ['{id: b}[1->0]', '{id: a}[0->1]', '{id: c}'],
previous: ['{id: a}[0->1]', '{id: b}[1->0]', '{id: c}'],
moves: ['{id: b}[1->0]', '{id: a}[0->1]'],
}),
);
});
it('should track duplicate reinsertion normally', () => {
let l = buildItemList(['a', 'a']);
differ.check(l);
l = buildItemList(['b', 'a', 'a']);
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['{id: b}[null->0]', '{id: a}[0->1]', '{id: a}[1->2]'],
identityChanges: ['{id: a}[0->1]', '{id: a}[1->2]'],
previous: ['{id: a}[0->1]', '{id: a}[1->2]'],
moves: ['{id: a}[0->1]', '{id: a}[1->2]'],
additions: ['{id: b}[null->0]'],
}),
);
});
it('should keep the order of duplicates', () => {
const l1 = [
new ComplexItem('a', 'blue'),
new ComplexItem('b', 'yellow'),
new ComplexItem('c', 'orange'),
new ComplexItem('a', 'red'),
];
differ.check(l1);
const l2 = [
new ComplexItem('b', 'yellow'),
new ComplexItem('a', 'blue'),
new ComplexItem('c', 'orange'),
new ComplexItem('a', 'red'),
];
differ.check(l2);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: [
'{id: b, color: yellow}[1->0]',
'{id: a, color: blue}[0->1]',
'{id: c, color: orange}',
'{id: a, color: red}',
],
identityChanges: [
'{id: b, color: yellow}[1->0]',
'{id: a, color: blue}[0->1]',
'{id: c, color: orange}',
'{id: a, color: red}',
],
previous: [
'{id: a, color: blue}[0->1]',
'{id: b, color: yellow}[1->0]',
'{id: c, color: orange}',
'{id: a, color: red}',
],
moves: ['{id: b, color: yellow}[1->0]', '{id: a, color: blue}[0->1]'],
}),
);
});
it('should not have identity changed', () => {
const l1 = [
new ComplexItem('a', 'blue'),
new ComplexItem('b', 'yellow'),
new ComplexItem('c', 'orange'),
new ComplexItem('a', 'red'),
];
differ.check(l1);
const l2 = [l1[1], l1[0], l1[2], l1[3]];
differ.check(l2);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: [
'{id: b, color: yellow}[1->0]',
'{id: a, color: blue}[0->1]',
'{id: c, color: orange}',
'{id: a, color: red}',
],
previous: [
'{id: a, color: blue}[0->1]',
'{id: b, color: yellow}[1->0]',
'{id: c, color: orange}',
'{id: a, color: red}',
],
moves: ['{id: b, color: yellow}[1->0]', '{id: a, color: blue}[0->1]'],
}),
);
});
it('should track removals normally', () => {
const l = buildItemList(['a', 'b', 'c']);
differ.check(l);
l.splice(2, 1);
differ.check(l);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['{id: a}', '{id: b}'],
previous: ['{id: a}', '{id: b}', '{id: c}[2->null]'],
removals: ['{id: c}[2->null]'],
}),
);
});
}); | {
"end_byte": 22894,
"start_byte": 16372,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/change_detection/differs/default_iterable_differ_spec.ts"
} |
angular/packages/core/test/change_detection/differs/default_iterable_differ_spec.ts_22898_23614 | describe('trackBy function by index', function () {
let differ: DefaultIterableDiffer<string>;
const trackByIndex = (index: number, item: any): number => index;
beforeEach(() => {
differ = new DefaultIterableDiffer(trackByIndex);
});
it('should track removals normally', () => {
differ.check(['a', 'b', 'c', 'd']);
differ.check(['e', 'f', 'g', 'h']);
differ.check(['e', 'f', 'h']);
expect(iterableDifferToString(differ)).toEqual(
iterableChangesAsString({
collection: ['e', 'f', 'h'],
previous: ['e', 'f', 'h', 'h[3->null]'],
removals: ['h[3->null]'],
identityChanges: ['h'],
}),
);
});
});
}); | {
"end_byte": 23614,
"start_byte": 22898,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/change_detection/differs/default_iterable_differ_spec.ts"
} |
angular/packages/core/test/change_detection/differs/default_keyvalue_differ_spec.ts_0_471 | /**
* @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 {
DefaultKeyValueDiffer,
DefaultKeyValueDifferFactory,
} from '@angular/core/src/change_detection/differs/default_keyvalue_differ';
import {kvChangesAsString, testChangesAsString} from '../util';
// TODO(vicb): Update the code & tests for object equality | {
"end_byte": 471,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/change_detection/differs/default_keyvalue_differ_spec.ts"
} |
angular/packages/core/test/change_detection/differs/default_keyvalue_differ_spec.ts_472_7924 | describe('keyvalue differ', function () {
describe('DefaultKeyValueDiffer', function () {
let differ: DefaultKeyValueDiffer<any, any>;
let m: Map<any, any>;
beforeEach(() => {
differ = new DefaultKeyValueDiffer<string, any>();
m = new Map();
});
afterEach(() => {
differ = null!;
});
it('should detect additions', () => {
differ.check(m);
m.set('a', 1);
differ.check(m);
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({map: ['a[null->1]'], additions: ['a[null->1]']}),
);
m.set('b', 2);
differ.check(m);
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({map: ['a', 'b[null->2]'], previous: ['a'], additions: ['b[null->2]']}),
);
});
it('should handle changing key/values correctly', () => {
m.set(1, 10);
m.set(2, 20);
differ.check(m);
m.set(2, 10);
m.set(1, 20);
differ.check(m);
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({
map: ['1[10->20]', '2[20->10]'],
previous: ['1[10->20]', '2[20->10]'],
changes: ['1[10->20]', '2[20->10]'],
}),
);
});
it('should expose previous and current value', () => {
m.set(1, 10);
differ.check(m);
m.set(1, 20);
differ.check(m);
differ.forEachChangedItem((record: any) => {
expect(record.previousValue).toEqual(10);
expect(record.currentValue).toEqual(20);
});
});
it('should do basic map watching', () => {
differ.check(m);
m.set('a', 'A');
differ.check(m);
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({map: ['a[null->A]'], additions: ['a[null->A]']}),
);
m.set('b', 'B');
differ.check(m);
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({map: ['a', 'b[null->B]'], previous: ['a'], additions: ['b[null->B]']}),
);
m.set('b', 'BB');
m.set('d', 'D');
differ.check(m);
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({
map: ['a', 'b[B->BB]', 'd[null->D]'],
previous: ['a', 'b[B->BB]'],
additions: ['d[null->D]'],
changes: ['b[B->BB]'],
}),
);
m.delete('b');
differ.check(m);
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({
map: ['a', 'd'],
previous: ['a', 'b[BB->null]', 'd'],
removals: ['b[BB->null]'],
}),
);
m.clear();
differ.check(m);
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({
previous: ['a[A->null]', 'd[D->null]'],
removals: ['a[A->null]', 'd[D->null]'],
}),
);
});
it('should not see a NaN value as a change', () => {
m.set('foo', Number.NaN);
differ.check(m);
differ.check(m);
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({map: ['foo'], previous: ['foo']}),
);
});
it('should work regardless key order', () => {
m.set('a', 0);
m.set('b', 0);
differ.check(m);
m = new Map();
m.set('b', 1);
m.set('a', 1);
differ.check(m);
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({
map: ['b[0->1]', 'a[0->1]'],
previous: ['a[0->1]', 'b[0->1]'],
changes: ['b[0->1]', 'a[0->1]'],
}),
);
});
describe('JsObject changes', () => {
it('should support JS Object', () => {
const f = new DefaultKeyValueDifferFactory();
expect(f.supports({})).toBeTruthy();
expect(f.supports('not supported')).toBeFalsy();
expect(f.supports(0)).toBeFalsy();
expect(f.supports(null)).toBeFalsy();
});
it('should do basic object watching', () => {
let m: {[k: string]: string} = {};
differ.check(m);
m['a'] = 'A';
differ.check(m);
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({map: ['a[null->A]'], additions: ['a[null->A]']}),
);
m['b'] = 'B';
differ.check(m);
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({
map: ['a', 'b[null->B]'],
previous: ['a'],
additions: ['b[null->B]'],
}),
);
m['b'] = 'BB';
m['d'] = 'D';
differ.check(m);
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({
map: ['a', 'b[B->BB]', 'd[null->D]'],
previous: ['a', 'b[B->BB]'],
additions: ['d[null->D]'],
changes: ['b[B->BB]'],
}),
);
m = {};
m['a'] = 'A';
m['d'] = 'D';
differ.check(m);
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({
map: ['a', 'd'],
previous: ['a', 'b[BB->null]', 'd'],
removals: ['b[BB->null]'],
}),
);
m = {};
differ.check(m);
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({
previous: ['a[A->null]', 'd[D->null]'],
removals: ['a[A->null]', 'd[D->null]'],
}),
);
});
it('should work regardless key order', () => {
differ.check({a: 0, b: 0});
differ.check({b: 1, a: 1});
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({
map: ['b[0->1]', 'a[0->1]'],
previous: ['a[0->1]', 'b[0->1]'],
changes: ['b[0->1]', 'a[0->1]'],
}),
);
});
// https://github.com/angular/angular/issues/14997
it('should work regardless key order', () => {
differ.check({a: 1, b: 2});
differ.check({b: 3, a: 2});
differ.check({a: 1, b: 2});
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({
map: ['a[2->1]', 'b[3->2]'],
previous: ['b[3->2]', 'a[2->1]'],
changes: ['a[2->1]', 'b[3->2]'],
}),
);
});
it('should when the first item is moved', () => {
differ.check({a: 'a', b: 'b'});
differ.check({c: 'c', a: 'a'});
expect(kvChangesAsString(differ)).toEqual(
testChangesAsString({
map: ['c[null->c]', 'a'],
previous: ['a', 'b[b->null]'],
additions: ['c[null->c]'],
removals: ['b[b->null]'],
}),
);
});
});
describe('diff', () => {
it('should return self when there is a change', () => {
m.set('a', 'A');
expect(differ.diff(m)).toBe(differ);
});
it('should return null when there is no change', () => {
m.set('a', 'A');
differ.diff(m);
expect(differ.diff(m)).toEqual(null);
});
it('should treat null as an empty list', () => {
m.set('a', 'A');
differ.diff(m);
expect(kvChangesAsString(differ.diff(null))).toEqual(
testChangesAsString({previous: ['a[A->null]'], removals: ['a[A->null]']}),
);
});
it('should throw when given an invalid collection', () => {
expect(() => differ.diff(<any>'invalid')).toThrowError(/Error trying to diff 'invalid'/);
});
});
});
}); | {
"end_byte": 7924,
"start_byte": 472,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/change_detection/differs/default_keyvalue_differ_spec.ts"
} |
angular/packages/core/test/hydration/compression_spec.ts_0_1686 | /**
* @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 {compressNodeLocation, decompressNodeLocation} from '../../src/hydration/compression';
import {
NodeNavigationStep,
REFERENCE_NODE_BODY,
REFERENCE_NODE_HOST,
} from '../../src/hydration/interfaces';
describe('compression of node location', () => {
it('should handle basic cases', () => {
const fc = NodeNavigationStep.FirstChild;
const ns = NodeNavigationStep.NextSibling;
const cases = [
[[REFERENCE_NODE_HOST, fc, 1], 'hf'],
[[REFERENCE_NODE_BODY, fc, 1], 'bf'],
[[0, fc, 1], '0f'],
[[15, fc, 1], '15f'],
[[15, fc, 4], '15f4'],
[[5, fc, 4, ns, 1, fc, 1], '5f4nf'],
[[7, ns, 4, fc, 1, ns, 1], '7n4fn'],
];
cases.forEach((_case) => {
const [origSteps, path] = _case as [(string | number)[], string];
const refNode = origSteps.shift()!;
// Transform the short version of instructions (e.g. [fc, 4, ns, 2])
// to a long version (e.g. [fc, fc, fc, fc, ns, ns]).
const steps = [];
let i = 0;
while (i < origSteps.length) {
const step = origSteps[i++];
const repeat = origSteps[i++] as number;
for (let r = 0; r < repeat; r++) {
steps.push(step);
}
}
// Check that one type can be converted to another and vice versa.
expect(compressNodeLocation(String(refNode), steps as NodeNavigationStep[])).toEqual(path);
expect(decompressNodeLocation(path)).toEqual([refNode, ...origSteps]);
});
});
});
| {
"end_byte": 1686,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/hydration/compression_spec.ts"
} |
angular/packages/core/test/playground/zone-signal-input/index.html_0_407 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Test App</title>
</head>
<body>
<my-app />
</body>
<script src="/angular/packages/zone.js/bundles/zone.umd.js"></script>
<script src="/app_bundle.debug.js"></script>
</html>
| {
"end_byte": 407,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/playground/zone-signal-input/index.html"
} |
angular/packages/core/test/playground/zone-signal-input/BUILD.bazel_0_660 | load("//tools:defaults.bzl", "app_bundle", "http_server", "ng_module")
ng_module(
name = "test_lib",
srcs = ["index.ts"],
strict_templates = True,
tags = ["no-cache"],
deps = [
"//packages/core",
"//packages/platform-browser",
"//packages/zone.js/lib",
],
)
filegroup(
name = "test",
srcs = [":test_lib"],
output_group = "es5_sources",
)
app_bundle(
name = "app_bundle",
entry_point = ":index.ts",
deps = [":test_lib"],
)
http_server(
name = "server",
srcs = ["index.html"],
deps = [
":app_bundle.debug",
"//packages/zone.js/bundles:zone.umd.js",
],
)
| {
"end_byte": 660,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/playground/zone-signal-input/BUILD.bazel"
} |
angular/packages/core/test/playground/zone-signal-input/index.ts_0_1986 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component, EventEmitter, Input, input, Output, signal} from '@angular/core';
import {bootstrapApplication} from '@angular/platform-browser';
@Component({
selector: 'greet',
standalone: true,
template: `
{{ counter() }} -- {{label()}}
<p>Two way: {{twoWay()}}</p>
<button (click)="twoWayChange.emit(!twoWay())">
Two Way output from child
</button>
`,
})
export class Greet<T> {
counter = input(0);
bla = input(); // TODO: should be a diagnostic. no type & no value
bla2 = input<string>();
bla3 = input.required<string>();
bla4 = input(0, {alias: 'bla4Public'});
gen = input.required<string>();
gen2 = input.required<T>();
label = input<string>();
twoWay = input(false);
@Output() twoWayChange = new EventEmitter();
works(): T {
return this.gen2();
}
// Eventually in signal components, a mix not allowed. For now, this is
// supported though.
@Input() oldInput: string | undefined;
}
@Component({
standalone: true,
selector: 'my-app',
template: `
Hello <greet [counter]="3" [bla4Public]="10" #ok
[bla3]="someStringVar" gen='this is required' [gen2]="{yes: true}"
label="Hello {{name()}}"
[(twoWay)]="twoWay"
/>
<p>Two way outside: {{twoWay}}</p>
<button (click)="ok.works().yes">Click</button>
<button (click)="updateName()">Change name</button>
<button (click)="twoWay = !twoWay">Change Two way (outside)</button>
`,
imports: [Greet],
})
export class MyApp {
name = signal('Angular');
someVar = -10;
someStringVar = 'works';
twoWay = false;
protected updateName() {
this.name.update((n) => `${n}-`);
}
onClickFromChild() {
console.info('Click from child');
}
}
bootstrapApplication(MyApp).catch((e) => console.error(e));
| {
"end_byte": 1986,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/playground/zone-signal-input/index.ts"
} |
angular/packages/core/test/util/array_utils_spec.ts_0_4909 | /**
* @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 {
arrayIndexOfSorted,
arrayInsert,
arrayInsert2,
arraySplice,
flatten,
KeyValueArray,
keyValueArrayDelete,
keyValueArrayGet,
keyValueArrayIndexOf,
keyValueArraySet,
} from '../../src/util/array_utils';
describe('array_utils', () => {
describe('flatten', () => {
it('should flatten an empty array', () => {
expect(flatten([])).toEqual([]);
});
it('should flatten a flat array', () => {
expect(flatten([1, 2, 3])).toEqual([1, 2, 3]);
});
it('should flatten a nested array depth-first', () => {
expect(flatten([1, [2], 3])).toEqual([1, 2, 3]);
expect(flatten([[1], 2, [3]])).toEqual([1, 2, 3]);
expect(flatten([1, [2, [3]], 4])).toEqual([1, 2, 3, 4]);
expect(flatten([1, [2, [3]], [4]])).toEqual([1, 2, 3, 4]);
expect(flatten([1, [2, [3]], [[[4]]]])).toEqual([1, 2, 3, 4]);
expect(flatten([1, [], 2])).toEqual([1, 2]);
});
});
describe('fast arraySplice', () => {
function expectArraySplice(array: any[], index: number) {
arraySplice(array, index, 1);
return expect(array);
}
it('should remove items', () => {
expectArraySplice([0, 1, 2], 0).toEqual([1, 2]);
expectArraySplice([0, 1, 2], 1).toEqual([0, 2]);
expectArraySplice([0, 1, 2], 2).toEqual([0, 1]);
});
});
describe('arrayInsertSorted', () => {
function expectArrayInsert(array: any[], index: number, value: any) {
arrayInsert(array, index, value);
return expect(array);
}
function expectArrayInsert2(array: any[], index: number, value1: any, value2: any) {
arrayInsert2(array, index, value1, value2);
return expect(array);
}
it('should insert items', () => {
expectArrayInsert([], 0, 'A').toEqual(['A']);
expectArrayInsert([0], 0, 'A').toEqual(['A', 0]);
expectArrayInsert([0], 1, 'A').toEqual([0, 'A']);
expectArrayInsert([0, 1, 2], 0, 'A').toEqual(['A', 0, 1, 2]);
expectArrayInsert([0, 1, 2], 1, 'A').toEqual([0, 'A', 1, 2]);
expectArrayInsert([0, 1, 2], 2, 'A').toEqual([0, 1, 'A', 2]);
expectArrayInsert([0, 1, 2], 3, 'A').toEqual([0, 1, 2, 'A']);
});
it('should insert items', () => {
expectArrayInsert2([], 0, 'A', 'B').toEqual(['A', 'B']);
expectArrayInsert2([0], 0, 'A', 'B').toEqual(['A', 'B', 0]);
expectArrayInsert2([0], 1, 'A', 'B').toEqual([0, 'A', 'B']);
expectArrayInsert2([0, 1, 2], 0, 'A', 'B').toEqual(['A', 'B', 0, 1, 2]);
expectArrayInsert2([0, 1, 2], 1, 'A', 'B').toEqual([0, 'A', 'B', 1, 2]);
expectArrayInsert2([0, 1, 2], 2, 'A', 'B').toEqual([0, 1, 'A', 'B', 2]);
expectArrayInsert2([0, 1, 2], 3, 'A', 'B').toEqual([0, 1, 2, 'A', 'B']);
expectArrayInsert2(['height', '1px', 'width', '2000px'], 0, 'color', 'red').toEqual([
'color',
'red',
'height',
'1px',
'width',
'2000px',
]);
});
});
describe('arrayIndexOfSorted', () => {
it('should get index of', () => {
const a = ['a', 'b', 'c', 'd', 'e'];
expect(arrayIndexOfSorted(a, 'a')).toEqual(0);
expect(arrayIndexOfSorted(a, 'b')).toEqual(1);
expect(arrayIndexOfSorted(a, 'c')).toEqual(2);
expect(arrayIndexOfSorted(a, 'd')).toEqual(3);
expect(arrayIndexOfSorted(a, 'e')).toEqual(4);
});
});
describe('KeyValueArray', () => {
it('should support basic operations', () => {
const map: KeyValueArray<number> = [] as any;
expect(keyValueArrayIndexOf(map, 'A')).toEqual(~0);
expect(keyValueArraySet(map, 'B', 1)).toEqual(0);
expect(map).toEqual(['B', 1]);
expect(keyValueArrayIndexOf(map, 'B')).toEqual(0);
expect(keyValueArraySet(map, 'A', 0)).toEqual(0);
expect(map).toEqual(['A', 0, 'B', 1]);
expect(keyValueArrayIndexOf(map, 'B')).toEqual(2);
expect(keyValueArrayIndexOf(map, 'AA')).toEqual(~2);
expect(keyValueArraySet(map, 'C', 2)).toEqual(4);
expect(map).toEqual(['A', 0, 'B', 1, 'C', 2]);
expect(keyValueArrayGet(map, 'A')).toEqual(0);
expect(keyValueArrayGet(map, 'B')).toEqual(1);
expect(keyValueArrayGet(map, 'C')).toEqual(2);
expect(keyValueArrayGet(map, 'AA')).toEqual(undefined);
expect(keyValueArraySet(map, 'B', -1)).toEqual(2);
expect(map).toEqual(['A', 0, 'B', -1, 'C', 2]);
expect(keyValueArrayDelete(map, 'AA')).toEqual(~2);
expect(keyValueArrayDelete(map, 'B')).toEqual(2);
expect(map).toEqual(['A', 0, 'C', 2]);
expect(keyValueArrayDelete(map, 'A')).toEqual(0);
expect(map).toEqual(['C', 2]);
expect(keyValueArrayDelete(map, 'C')).toEqual(0);
expect(map).toEqual([]);
});
});
});
| {
"end_byte": 4909,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/util/array_utils_spec.ts"
} |
angular/packages/core/test/util/coercion_spec.ts_0_4288 | /**
* @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 {booleanAttribute, numberAttribute} from '@angular/core';
describe('coercion functions', () => {
describe('booleanAttribute', () => {
it('should coerce undefined to false', () => {
expect(booleanAttribute(undefined)).toBe(false);
});
it('should coerce null to false', () => {
expect(booleanAttribute(null)).toBe(false);
});
it('should coerce the empty string to true', () => {
expect(booleanAttribute('')).toBe(true);
});
it('should coerce zero to true', () => {
expect(booleanAttribute(0)).toBe(true);
});
it('should coerce the string "false" to false', () => {
expect(booleanAttribute('false')).toBe(false);
});
it('should coerce the boolean false to false', () => {
expect(booleanAttribute(false)).toBe(false);
});
it('should coerce the boolean true to true', () => {
expect(booleanAttribute(true)).toBe(true);
});
it('should coerce the string "true" to true', () => {
expect(booleanAttribute('true')).toBe(true);
});
it('should coerce an arbitrary string to true', () => {
expect(booleanAttribute('pink')).toBe(true);
});
it('should coerce an object to true', () => {
expect(booleanAttribute({})).toBe(true);
});
it('should coerce an array to true', () => {
expect(booleanAttribute([])).toBe(true);
});
});
describe('numberAttribute', () => {
it('should coerce undefined to the default value', () => {
expect(numberAttribute(undefined)).toBeNaN();
expect(numberAttribute(undefined, 111)).toBe(111);
});
it('should coerce null to the default value', () => {
expect(numberAttribute(null)).toBeNaN();
expect(numberAttribute(null, 111)).toBe(111);
});
it('should coerce true to the default value', () => {
expect(numberAttribute(true)).toBeNaN();
expect(numberAttribute(true, 111)).toBe(111);
});
it('should coerce false to the default value', () => {
expect(numberAttribute(false)).toBeNaN();
expect(numberAttribute(false, 111)).toBe(111);
});
it('should coerce the empty string to the default value', () => {
expect(numberAttribute('')).toBeNaN();
expect(numberAttribute('', 111)).toBe(111);
});
it('should coerce the string "1" to 1', () => {
expect(numberAttribute('1')).toBe(1);
expect(numberAttribute('1', 111)).toBe(1);
});
it('should coerce the string "123.456" to 123.456', () => {
expect(numberAttribute('123.456')).toBe(123.456);
expect(numberAttribute('123.456', 111)).toBe(123.456);
});
it('should coerce the string "-123.456" to -123.456', () => {
expect(numberAttribute('-123.456')).toBe(-123.456);
expect(numberAttribute('-123.456', 111)).toBe(-123.456);
});
it('should coerce an arbitrary string to the default value', () => {
expect(numberAttribute('pink')).toBeNaN();
expect(numberAttribute('pink', 111)).toBe(111);
});
it('should coerce an arbitrary string prefixed with a number to the default value', () => {
expect(numberAttribute('123pink')).toBeNaN();
expect(numberAttribute('123pink', 111)).toBe(111);
});
it('should coerce the number 1 to 1', () => {
expect(numberAttribute(1)).toBe(1);
expect(numberAttribute(1, 111)).toBe(1);
});
it('should coerce the number 123.456 to 123.456', () => {
expect(numberAttribute(123.456)).toBe(123.456);
expect(numberAttribute(123.456, 111)).toBe(123.456);
});
it('should coerce the number -123.456 to -123.456', () => {
expect(numberAttribute(-123.456)).toBe(-123.456);
expect(numberAttribute(-123.456, 111)).toBe(-123.456);
});
it('should coerce an object to the default value', () => {
expect(numberAttribute({})).toBeNaN();
expect(numberAttribute({}, 111)).toBe(111);
});
it('should coerce an array to the default value', () => {
expect(numberAttribute([])).toBeNaN();
expect(numberAttribute([], 111)).toBe(111);
});
});
});
| {
"end_byte": 4288,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/util/coercion_spec.ts"
} |
angular/packages/core/test/util/dom_spec.ts_0_1890 | /**
* @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 {escapeCommentText} from '@angular/core/src/util/dom';
describe('comment node text escaping', () => {
describe('escapeCommentText', () => {
it('should not change anything on basic text', () => {
expect(escapeCommentText('text')).toEqual('text');
});
it('should escape "<" or ">"', () => {
expect(escapeCommentText('<!--')).toEqual('\u200b<\u200b!--');
expect(escapeCommentText('<!--<!--')).toEqual('\u200b<\u200b!--\u200b<\u200b!--');
expect(escapeCommentText('>')).toEqual('\u200b>\u200b');
expect(escapeCommentText('>-->')).toEqual('\u200b>\u200b--\u200b>\u200b');
});
it('should escape end marker', () => {
expect(escapeCommentText('before-->after')).toEqual('before--\u200b>\u200bafter');
});
it('should escape multiple markers', () => {
expect(escapeCommentText('before-->inline-->after')).toEqual(
'before--\u200b>\u200binline--\u200b>\u200bafter',
);
});
it('should caver the spec', () => {
// https://html.spec.whatwg.org/multipage/syntax.html#comments
expect(escapeCommentText('>')).toEqual('\u200b>\u200b');
expect(escapeCommentText('->')).toEqual('-\u200b>\u200b');
expect(escapeCommentText('<!--')).toEqual('\u200b<\u200b!--');
expect(escapeCommentText('-->')).toEqual('--\u200b>\u200b');
expect(escapeCommentText('--!>')).toEqual('--!\u200b>\u200b');
expect(escapeCommentText('<!-')).toEqual('\u200b<\u200b!-');
// Things which are OK
expect(escapeCommentText('.>')).toEqual('.>');
expect(escapeCommentText('.->')).toEqual('.->');
expect(escapeCommentText('<!-.')).toEqual('<!-.');
});
});
});
| {
"end_byte": 1890,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/util/dom_spec.ts"
} |
angular/packages/core/test/util/stringify_spec.ts_0_965 | /**
* @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 {concatStringsWithSpace} from '@angular/core/src/util/stringify';
describe('stringify', () => {
describe('concatStringsWithSpace', () => {
it('should concat with null', () => {
expect(concatStringsWithSpace(null, null)).toEqual('');
expect(concatStringsWithSpace('a', null)).toEqual('a');
expect(concatStringsWithSpace(null, 'b')).toEqual('b');
});
it('should concat when empty', () => {
expect(concatStringsWithSpace('', '')).toEqual('');
expect(concatStringsWithSpace('a', '')).toEqual('a');
expect(concatStringsWithSpace('', 'b')).toEqual('b');
});
it('should concat when not empty', () => {
expect(concatStringsWithSpace('before', 'after')).toEqual('before after');
});
});
});
| {
"end_byte": 965,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/util/stringify_spec.ts"
} |
angular/packages/core/test/util/global_spec.ts_0_572 | /**
* @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 {global} from '../../src/util/global';
describe('global', () => {
it('should be global this value', () => {
const _global = new Function('return this')();
expect(global).toBe(_global);
});
if (typeof globalThis !== 'undefined') {
it('should use globalThis as global reference', () => {
expect(global).toBe(globalThis);
});
}
});
| {
"end_byte": 572,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/util/global_spec.ts"
} |
angular/packages/core/test/util/comparison.ts_0_1965 | /**
* @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 {devModeEqual} from '@angular/core/src/util/comparison';
describe('Comparison util', () => {
describe('devModeEqual', () => {
it('should do the deep comparison of iterables', () => {
expect(devModeEqual([['one']], [['one']])).toBe(true);
expect(devModeEqual(['one'], ['one', 'two'])).toBe(false);
expect(devModeEqual(['one', 'two'], ['one'])).toBe(false);
expect(devModeEqual(['one'], 'one')).toBe(false);
expect(devModeEqual(['one'], {})).toBe(false);
expect(devModeEqual('one', ['one'])).toBe(false);
expect(devModeEqual({}, ['one'])).toBe(false);
});
it('should compare primitive numbers', () => {
expect(devModeEqual(1, 1)).toBe(true);
expect(devModeEqual(1, 2)).toBe(false);
expect(devModeEqual({}, 2)).toBe(false);
expect(devModeEqual(1, {})).toBe(false);
});
it('should compare primitive strings', () => {
expect(devModeEqual('one', 'one')).toBe(true);
expect(devModeEqual('one', 'two')).toBe(false);
expect(devModeEqual({}, 'one')).toBe(false);
expect(devModeEqual('one', {})).toBe(false);
});
it('should compare primitive booleans', () => {
expect(devModeEqual(true, true)).toBe(true);
expect(devModeEqual(true, false)).toBe(false);
expect(devModeEqual({}, true)).toBe(false);
expect(devModeEqual(true, {})).toBe(false);
});
it('should compare null', () => {
expect(devModeEqual(null, null)).toBe(true);
expect(devModeEqual(null, 1)).toBe(false);
expect(devModeEqual({}, null)).toBe(false);
expect(devModeEqual(null, {})).toBe(false);
});
it('should return true for other objects', () => {
expect(devModeEqual({}, {})).toBe(true);
});
});
});
| {
"end_byte": 1965,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/util/comparison.ts"
} |
angular/packages/core/test/util/iterable.ts_0_364 | /**
* @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 class TestIterable {
list: number[];
constructor() {
this.list = [];
}
[Symbol.iterator]() {
return this.list[Symbol.iterator]();
}
}
| {
"end_byte": 364,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/util/iterable.ts"
} |
angular/packages/core/test/util/lang_spec.ts_0_1013 | /**
* @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 {isSubscribable} from '@angular/core/src/util/lang';
import {of} from 'rxjs';
describe('isSubscribable', () => {
it('should be true for an Observable', () => expect(isSubscribable(of(true))).toEqual(true));
it('should be true if the argument is the object with subscribe function', () =>
expect(isSubscribable({subscribe: () => {}})).toEqual(true));
it('should be false if the argument is undefined', () =>
expect(isSubscribable(undefined)).toEqual(false));
it('should be false if the argument is null', () => expect(isSubscribable(null)).toEqual(false));
it('should be false if the argument is an object', () =>
expect(isSubscribable({})).toEqual(false));
it('should be false if the argument is a function', () =>
expect(isSubscribable(() => {})).toEqual(false));
});
| {
"end_byte": 1013,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/util/lang_spec.ts"
} |
angular/packages/core/test/util/decorators_spec.ts_0_2412 | /**
* @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 {getReflect} from '../../src/di/jit/util';
import {ANNOTATIONS, makeDecorator, makePropDecorator} from '../../src/util/decorators';
class DecoratedParent {}
class DecoratedChild extends DecoratedParent {}
const TerminalDecorator = makeDecorator('TerminalDecorator', (data: any) => ({
terminal: true,
...data,
}));
const TestDecorator = makeDecorator(
'TestDecorator',
(data: any) => data,
Object,
(fn: any) => (fn.Terminal = TerminalDecorator),
);
describe('Property decorators', () => {
// https://github.com/angular/angular/issues/12224
it('should work on the "watch" property', () => {
const Prop = makePropDecorator('Prop', (value: any) => ({value}));
class TestClass {
@Prop('firefox!') watch: any;
}
const p = getReflect().propMetadata(TestClass);
expect(p['watch']).toEqual([new Prop('firefox!')]);
});
it('should work with any default plain values', () => {
const Default = makePropDecorator('Default', (data: any) => ({value: data != null ? data : 5}));
expect(new Default(0)['value']).toEqual(0);
});
it('should work with any object values', () => {
// make sure we don't walk up the prototype chain
const Default = makePropDecorator('Default', (data: any) => ({value: 5, ...data}));
const value = Object.create({value: 10});
expect(new Default(value)['value']).toEqual(5);
});
});
describe('decorators', () => {
it('should invoke as decorator', () => {
function Type() {}
TestDecorator({marker: 'WORKS'})(Type);
const annotations = (Type as any)[ANNOTATIONS];
expect(annotations[0].marker).toEqual('WORKS');
});
it('should invoke as new', () => {
const annotation = new (<any>TestDecorator)({marker: 'WORKS'});
expect(annotation instanceof TestDecorator).toEqual(true);
expect(annotation.marker).toEqual('WORKS');
});
it('should not apply decorators from the prototype chain', function () {
TestDecorator({marker: 'parent'})(DecoratedParent);
TestDecorator({marker: 'child'})(DecoratedChild);
const annotations = (DecoratedChild as any)[ANNOTATIONS];
expect(annotations.length).toBe(1);
expect(annotations[0].marker).toEqual('child');
});
});
| {
"end_byte": 2412,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/util/decorators_spec.ts"
} |
angular/packages/core/test/linker/integration_spec.ts_0_1791 | /**
* @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, DOCUMENT, ɵgetDOM as getDOM} from '@angular/common';
import {
Attribute,
Compiler,
Component,
ComponentFactory,
ComponentRef,
ContentChildren,
createComponent,
Directive,
EnvironmentInjector,
EventEmitter,
Host,
HostBinding,
HostListener,
Inject,
Injectable,
InjectionToken,
Injector,
Input,
NgModule,
NgModuleRef,
NO_ERRORS_SCHEMA,
OnDestroy,
Output,
Pipe,
reflectComponentType,
SkipSelf,
ViewChild,
ViewRef,
ɵsetClassDebugInfo,
} from '@angular/core';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
PipeTransform,
} from '@angular/core/src/change_detection/change_detection';
import {ComponentFactoryResolver} from '@angular/core/src/linker/component_factory_resolver';
import {ElementRef} from '@angular/core/src/linker/element_ref';
import {QueryList} from '@angular/core/src/linker/query_list';
import {TemplateRef} from '@angular/core/src/linker/template_ref';
import {ViewContainerRef} from '@angular/core/src/linker/view_container_ref';
import {EmbeddedViewRef} from '@angular/core/src/linker/view_ref';
import {fakeAsync, getTestBed, TestBed, tick, waitForAsync} from '@angular/core/testing';
import {TestBedCompiler} from '@angular/core/testing/src/test_bed_compiler';
import {
createMouseEvent,
dispatchEvent,
el,
isCommentNode,
} from '@angular/platform-browser/testing/src/browser_util';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {stringify} from '../../src/util/stringify';
const ANCHOR_ELEMENT = new InjectionToken('AnchorElement');
| {
"end_byte": 1791,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/linker/integration_spec.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.