_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/core/testing/BUILD.bazel_0_844 | load("//tools:defaults.bzl", "generate_api_docs", "ng_module")
package(default_visibility = ["//visibility:public"])
exports_files(["package.json"])
ng_module(
name = "testing",
srcs = glob(
["**/*.ts"],
),
deps = [
"//packages:types",
"//packages/compiler",
"//packages/core",
"//packages/localize",
"//packages/zone.js/lib:zone_d_ts",
"@npm//@types/jasmine",
],
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
visibility = ["//visibility:public"],
)
generate_api_docs(
name = "core_testing_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
],
entry_point = ":index.ts",
module_name = "@angular/core/testing",
)
| {
"end_byte": 844,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/BUILD.bazel"
} |
angular/packages/core/testing/index.ts_0_481 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// This file is not used to build this module. It is only used during editing
// by the TypeScript language service and during build for verification. `ngc`
// replaces this file with production index.ts when it rewrites private symbol
// names.
export * from './public_api';
| {
"end_byte": 481,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/index.ts"
} |
angular/packages/core/testing/public_api.ts_0_433 | /**
* @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
*/
/// <reference types="jasmine" />
/**
* @module
* @description
* Entry point for all public APIs of this package.
*/
export * from './src/testing';
// This file only reexports content of the `src` folder. Keep it that way.
| {
"end_byte": 433,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/public_api.ts"
} |
angular/packages/core/testing/src/test_bed_compiler.ts_0_3740 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ResourceLoader} from '@angular/compiler';
import {
ApplicationInitStatus,
ɵINTERNAL_APPLICATION_ERROR_HANDLER as INTERNAL_APPLICATION_ERROR_HANDLER,
ɵChangeDetectionScheduler as ChangeDetectionScheduler,
ɵChangeDetectionSchedulerImpl as ChangeDetectionSchedulerImpl,
Compiler,
COMPILER_OPTIONS,
Component,
Directive,
Injector,
inject,
InjectorType,
LOCALE_ID,
ModuleWithComponentFactories,
ModuleWithProviders,
NgModule,
NgModuleFactory,
Pipe,
PlatformRef,
Provider,
resolveForwardRef,
StaticProvider,
Type,
ɵclearResolutionOfComponentResourcesQueue,
ɵcompileComponent as compileComponent,
ɵcompileDirective as compileDirective,
ɵcompileNgModuleDefs as compileNgModuleDefs,
ɵcompilePipe as compilePipe,
ɵDEFAULT_LOCALE_ID as DEFAULT_LOCALE_ID,
ɵDEFER_BLOCK_CONFIG as DEFER_BLOCK_CONFIG,
ɵdepsTracker as depsTracker,
ɵDirectiveDef as DirectiveDef,
ɵgenerateStandaloneInDeclarationsError,
ɵgetAsyncClassMetadataFn as getAsyncClassMetadataFn,
ɵgetInjectableDef as getInjectableDef,
ɵInternalEnvironmentProviders as InternalEnvironmentProviders,
ɵinternalProvideZoneChangeDetection as internalProvideZoneChangeDetection,
ɵisComponentDefPendingResolution,
ɵisEnvironmentProviders as isEnvironmentProviders,
ɵNG_COMP_DEF as NG_COMP_DEF,
ɵNG_DIR_DEF as NG_DIR_DEF,
ɵNG_INJ_DEF as NG_INJ_DEF,
ɵNG_MOD_DEF as NG_MOD_DEF,
ɵNG_PIPE_DEF as NG_PIPE_DEF,
ɵNgModuleFactory as R3NgModuleFactory,
ɵNgModuleTransitiveScopes as NgModuleTransitiveScopes,
ɵNgModuleType as NgModuleType,
ɵpatchComponentDefWithScope as patchComponentDefWithScope,
ɵRender3ComponentFactory as ComponentFactory,
ɵRender3NgModuleRef as NgModuleRef,
ɵresolveComponentResources,
ɵrestoreComponentResolutionQueue,
ɵsetLocaleId as setLocaleId,
ɵtransitiveScopesFor as transitiveScopesFor,
ɵUSE_RUNTIME_DEPS_TRACKER_FOR_JIT as USE_RUNTIME_DEPS_TRACKER_FOR_JIT,
ɵɵInjectableDeclaration as InjectableDeclaration,
NgZone,
ErrorHandler,
ɵNG_STANDALONE_DEFAULT_VALUE as NG_STANDALONE_DEFAULT_VALUE,
} from '@angular/core';
import {ComponentDef, ComponentType} from '../../src/render3';
import {MetadataOverride} from './metadata_override';
import {
ComponentResolver,
DirectiveResolver,
NgModuleResolver,
PipeResolver,
Resolver,
} from './resolvers';
import {DEFER_BLOCK_DEFAULT_BEHAVIOR, TestModuleMetadata} from './test_bed_common';
import {
RETHROW_APPLICATION_ERRORS_DEFAULT,
TestBedApplicationErrorHandler,
} from './application_error_handler';
enum TestingModuleOverride {
DECLARATION,
OVERRIDE_TEMPLATE,
}
function isTestingModuleOverride(value: unknown): value is TestingModuleOverride {
return (
value === TestingModuleOverride.DECLARATION || value === TestingModuleOverride.OVERRIDE_TEMPLATE
);
}
function assertNoStandaloneComponents(
types: Type<any>[],
resolver: Resolver<any>,
location: string,
) {
types.forEach((type) => {
if (!getAsyncClassMetadataFn(type)) {
const component = resolver.resolve(type);
if (component && (component.standalone ?? NG_STANDALONE_DEFAULT_VALUE)) {
throw new Error(ɵgenerateStandaloneInDeclarationsError(type, location));
}
}
});
}
// Resolvers for Angular decorators
type Resolvers = {
module: Resolver<NgModule>;
component: Resolver<Directive>;
directive: Resolver<Component>;
pipe: Resolver<Pipe>;
};
interface CleanupOperation {
fieldName: string;
object: any;
originalValue: unknown;
}
export class TestBedCompiler {
priv | {
"end_byte": 3740,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/test_bed_compiler.ts"
} |
angular/packages/core/testing/src/test_bed_compiler.ts_3742_12264 | e originalComponentResolutionQueue: Map<Type<any>, Component> | null = null;
// Testing module configuration
private declarations: Type<any>[] = [];
private imports: Type<any>[] = [];
private providers: Provider[] = [];
private schemas: any[] = [];
// Queues of components/directives/pipes that should be recompiled.
private pendingComponents = new Set<Type<any>>();
private pendingDirectives = new Set<Type<any>>();
private pendingPipes = new Set<Type<any>>();
// Set of components with async metadata, i.e. components with `@defer` blocks
// in their templates.
private componentsWithAsyncMetadata = new Set<Type<unknown>>();
// Keep track of all components and directives, so we can patch Providers onto defs later.
private seenComponents = new Set<Type<any>>();
private seenDirectives = new Set<Type<any>>();
// Keep track of overridden modules, so that we can collect all affected ones in the module tree.
private overriddenModules = new Set<NgModuleType<any>>();
// Store resolved styles for Components that have template overrides present and `styleUrls`
// defined at the same time.
private existingComponentStyles = new Map<Type<any>, string[]>();
private resolvers: Resolvers = initResolvers();
// Map of component type to an NgModule that declares it.
//
// There are a couple special cases:
// - for standalone components, the module scope value is `null`
// - when a component is declared in `TestBed.configureTestingModule()` call or
// a component's template is overridden via `TestBed.overrideTemplateUsingTestingModule()`.
// we use a special value from the `TestingModuleOverride` enum.
private componentToModuleScope = new Map<Type<any>, Type<any> | TestingModuleOverride | null>();
// Map that keeps initial version of component/directive/pipe defs in case
// we compile a Type again, thus overriding respective static fields. This is
// required to make sure we restore defs to their initial states between test runs.
// Note: one class may have multiple defs (for example: ɵmod and ɵinj in case of an
// NgModule), store all of them in a map.
private initialNgDefs = new Map<Type<any>, Map<string, PropertyDescriptor | undefined>>();
// Array that keeps cleanup operations for initial versions of component/directive/pipe/module
// defs in case TestBed makes changes to the originals.
private defCleanupOps: CleanupOperation[] = [];
private _injector: Injector | null = null;
private compilerProviders: Provider[] | null = null;
private providerOverrides: Provider[] = [];
private rootProviderOverrides: Provider[] = [];
// Overrides for injectables with `{providedIn: SomeModule}` need to be tracked and added to that
// module's provider list.
private providerOverridesByModule = new Map<InjectorType<any>, Provider[]>();
private providerOverridesByToken = new Map<any, Provider>();
private scopesWithOverriddenProviders = new Set<Type<any>>();
private testModuleType: NgModuleType<any>;
private testModuleRef: NgModuleRef<any> | null = null;
private deferBlockBehavior = DEFER_BLOCK_DEFAULT_BEHAVIOR;
private rethrowApplicationTickErrors = RETHROW_APPLICATION_ERRORS_DEFAULT;
constructor(
private platform: PlatformRef,
private additionalModuleTypes: Type<any> | Type<any>[],
) {
class DynamicTestModule {}
this.testModuleType = DynamicTestModule as any;
}
setCompilerProviders(providers: Provider[] | null): void {
this.compilerProviders = providers;
this._injector = null;
}
configureTestingModule(moduleDef: TestModuleMetadata): void {
// Enqueue any compilation tasks for the directly declared component.
if (moduleDef.declarations !== undefined) {
// Verify that there are no standalone components
assertNoStandaloneComponents(
moduleDef.declarations,
this.resolvers.component,
'"TestBed.configureTestingModule" call',
);
this.queueTypeArray(moduleDef.declarations, TestingModuleOverride.DECLARATION);
this.declarations.push(...moduleDef.declarations);
}
// Enqueue any compilation tasks for imported modules.
if (moduleDef.imports !== undefined) {
this.queueTypesFromModulesArray(moduleDef.imports);
this.imports.push(...moduleDef.imports);
}
if (moduleDef.providers !== undefined) {
this.providers.push(...moduleDef.providers);
}
if (moduleDef.schemas !== undefined) {
this.schemas.push(...moduleDef.schemas);
}
this.deferBlockBehavior = moduleDef.deferBlockBehavior ?? DEFER_BLOCK_DEFAULT_BEHAVIOR;
this.rethrowApplicationTickErrors =
moduleDef.rethrowApplicationErrors ?? RETHROW_APPLICATION_ERRORS_DEFAULT;
}
overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): void {
if (USE_RUNTIME_DEPS_TRACKER_FOR_JIT) {
depsTracker.clearScopeCacheFor(ngModule);
}
this.overriddenModules.add(ngModule as NgModuleType<any>);
// Compile the module right away.
this.resolvers.module.addOverride(ngModule, override);
const metadata = this.resolvers.module.resolve(ngModule);
if (metadata === null) {
throw invalidTypeError(ngModule.name, 'NgModule');
}
this.recompileNgModule(ngModule, metadata);
// At this point, the module has a valid module def (ɵmod), but the override may have introduced
// new declarations or imported modules. Ingest any possible new types and add them to the
// current queue.
this.queueTypesFromModulesArray([ngModule]);
}
overrideComponent(component: Type<any>, override: MetadataOverride<Component>): void {
this.verifyNoStandaloneFlagOverrides(component, override);
this.resolvers.component.addOverride(component, override);
this.pendingComponents.add(component);
// If this is a component with async metadata (i.e. a component with a `@defer` block
// in a template) - store it for future processing.
this.maybeRegisterComponentWithAsyncMetadata(component);
}
overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): void {
this.verifyNoStandaloneFlagOverrides(directive, override);
this.resolvers.directive.addOverride(directive, override);
this.pendingDirectives.add(directive);
}
overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): void {
this.verifyNoStandaloneFlagOverrides(pipe, override);
this.resolvers.pipe.addOverride(pipe, override);
this.pendingPipes.add(pipe);
}
private verifyNoStandaloneFlagOverrides(
type: Type<any>,
override: MetadataOverride<Component | Directive | Pipe>,
) {
if (
override.add?.hasOwnProperty('standalone') ||
override.set?.hasOwnProperty('standalone') ||
override.remove?.hasOwnProperty('standalone')
) {
throw new Error(
`An override for the ${type.name} class has the \`standalone\` flag. ` +
`Changing the \`standalone\` flag via TestBed overrides is not supported.`,
);
}
}
overrideProvider(
token: any,
provider: {useFactory?: Function; useValue?: any; deps?: any[]; multi?: boolean},
): void {
let providerDef: Provider;
if (provider.useFactory !== undefined) {
providerDef = {
provide: token,
useFactory: provider.useFactory,
deps: provider.deps || [],
multi: provider.multi,
};
} else if (provider.useValue !== undefined) {
providerDef = {provide: token, useValue: provider.useValue, multi: provider.multi};
} else {
providerDef = {provide: token};
}
const injectableDef: InjectableDeclaration<any> | null =
typeof token !== 'string' ? getInjectableDef(token) : null;
const providedIn = injectableDef === null ? null : resolveForwardRef(injectableDef.providedIn);
const overridesBucket =
providedIn === 'root' ? this.rootProviderOverrides : this.providerOverrides;
overridesBucket.push(providerDef);
// Keep overrides grouped by token as well for fast lookups using token
this.providerOverridesByToken.set(token, providerDef);
if (injectableDef !== null && providedIn !== null && typeof providedIn !== 'string') {
const existingOverrides = this.providerOverridesByModule.get(providedIn);
if (existingOverrides !== undefined) {
existingOverrides.push(providerDef);
} else {
this.providerOverridesByModule.set(providedIn, [providerDef]);
}
}
}
overrideTemplateUsingTestingModule(typ | {
"end_byte": 12264,
"start_byte": 3742,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/test_bed_compiler.ts"
} |
angular/packages/core/testing/src/test_bed_compiler.ts_12268_20074 | ype<any>, template: string): void {
const def = (type as any)[NG_COMP_DEF];
const hasStyleUrls = (): boolean => {
const metadata = this.resolvers.component.resolve(type)! as Component;
return !!metadata.styleUrl || !!metadata.styleUrls?.length;
};
const overrideStyleUrls = !!def && !ɵisComponentDefPendingResolution(type) && hasStyleUrls();
// In Ivy, compiling a component does not require knowing the module providing the
// component's scope, so overrideTemplateUsingTestingModule can be implemented purely via
// overrideComponent. Important: overriding template requires full Component re-compilation,
// which may fail in case styleUrls are also present (thus Component is considered as required
// resolution). In order to avoid this, we preemptively set styleUrls to an empty array,
// preserve current styles available on Component def and restore styles back once compilation
// is complete.
const override = overrideStyleUrls
? {template, styles: [], styleUrls: [], styleUrl: undefined}
: {template};
this.overrideComponent(type, {set: override});
if (overrideStyleUrls && def.styles && def.styles.length > 0) {
this.existingComponentStyles.set(type, def.styles);
}
// Set the component's scope to be the testing module.
this.componentToModuleScope.set(type, TestingModuleOverride.OVERRIDE_TEMPLATE);
}
private async resolvePendingComponentsWithAsyncMetadata() {
if (this.componentsWithAsyncMetadata.size === 0) return;
const promises = [];
for (const component of this.componentsWithAsyncMetadata) {
const asyncMetadataFn = getAsyncClassMetadataFn(component);
if (asyncMetadataFn) {
promises.push(asyncMetadataFn());
}
}
this.componentsWithAsyncMetadata.clear();
const resolvedDeps = await Promise.all(promises);
const flatResolvedDeps = resolvedDeps.flat(2);
this.queueTypesFromModulesArray(flatResolvedDeps);
// Loaded standalone components might contain imports of NgModules
// with providers, make sure we override providers there too.
for (const component of flatResolvedDeps) {
this.applyProviderOverridesInScope(component);
}
}
async compileComponents(): Promise<void> {
this.clearComponentResolutionQueue();
// Wait for all async metadata for components that were
// overridden, we need resolved metadata to perform an override
// and re-compile a component.
await this.resolvePendingComponentsWithAsyncMetadata();
// Verify that there were no standalone components present in the `declarations` field
// during the `TestBed.configureTestingModule` call. We perform this check here in addition
// to the logic in the `configureTestingModule` function, since at this point we have
// all async metadata resolved.
assertNoStandaloneComponents(
this.declarations,
this.resolvers.component,
'"TestBed.configureTestingModule" call',
);
// Run compilers for all queued types.
let needsAsyncResources = this.compileTypesSync();
// compileComponents() should not be async unless it needs to be.
if (needsAsyncResources) {
let resourceLoader: ResourceLoader;
let resolver = (url: string): Promise<string> => {
if (!resourceLoader) {
resourceLoader = this.injector.get(ResourceLoader);
}
return Promise.resolve(resourceLoader.get(url));
};
await ɵresolveComponentResources(resolver);
}
}
finalize(): NgModuleRef<any> {
// One last compile
this.compileTypesSync();
// Create the testing module itself.
this.compileTestModule();
this.applyTransitiveScopes();
this.applyProviderOverrides();
// Patch previously stored `styles` Component values (taken from ɵcmp), in case these
// Components have `styleUrls` fields defined and template override was requested.
this.patchComponentsWithExistingStyles();
// Clear the componentToModuleScope map, so that future compilations don't reset the scope of
// every component.
this.componentToModuleScope.clear();
const parentInjector = this.platform.injector;
this.testModuleRef = new NgModuleRef(this.testModuleType, parentInjector, []);
// ApplicationInitStatus.runInitializers() is marked @internal to core.
// Cast it to any before accessing it.
(this.testModuleRef.injector.get(ApplicationInitStatus) as any).runInitializers();
// Set locale ID after running app initializers, since locale information might be updated while
// running initializers. This is also consistent with the execution order while bootstrapping an
// app (see `packages/core/src/application_ref.ts` file).
const localeId = this.testModuleRef.injector.get(LOCALE_ID, DEFAULT_LOCALE_ID);
setLocaleId(localeId);
return this.testModuleRef;
}
/**
* @internal
*/
_compileNgModuleSync(moduleType: Type<any>): void {
this.queueTypesFromModulesArray([moduleType]);
this.compileTypesSync();
this.applyProviderOverrides();
this.applyProviderOverridesInScope(moduleType);
this.applyTransitiveScopes();
}
/**
* @internal
*/
async _compileNgModuleAsync(moduleType: Type<any>): Promise<void> {
this.queueTypesFromModulesArray([moduleType]);
await this.compileComponents();
this.applyProviderOverrides();
this.applyProviderOverridesInScope(moduleType);
this.applyTransitiveScopes();
}
/**
* @internal
*/
_getModuleResolver(): Resolver<NgModule> {
return this.resolvers.module;
}
/**
* @internal
*/
_getComponentFactories(moduleType: NgModuleType): ComponentFactory<any>[] {
return maybeUnwrapFn(moduleType.ɵmod.declarations).reduce((factories, declaration) => {
const componentDef = (declaration as any).ɵcmp;
componentDef && factories.push(new ComponentFactory(componentDef, this.testModuleRef!));
return factories;
}, [] as ComponentFactory<any>[]);
}
private compileTypesSync(): boolean {
// Compile all queued components, directives, pipes.
let needsAsyncResources = false;
this.pendingComponents.forEach((declaration) => {
if (getAsyncClassMetadataFn(declaration)) {
throw new Error(
`Component '${declaration.name}' has unresolved metadata. ` +
`Please call \`await TestBed.compileComponents()\` before running this test.`,
);
}
needsAsyncResources = needsAsyncResources || ɵisComponentDefPendingResolution(declaration);
const metadata = this.resolvers.component.resolve(declaration);
if (metadata === null) {
throw invalidTypeError(declaration.name, 'Component');
}
this.maybeStoreNgDef(NG_COMP_DEF, declaration);
if (USE_RUNTIME_DEPS_TRACKER_FOR_JIT) {
depsTracker.clearScopeCacheFor(declaration);
}
compileComponent(declaration, metadata);
});
this.pendingComponents.clear();
this.pendingDirectives.forEach((declaration) => {
const metadata = this.resolvers.directive.resolve(declaration);
if (metadata === null) {
throw invalidTypeError(declaration.name, 'Directive');
}
this.maybeStoreNgDef(NG_DIR_DEF, declaration);
compileDirective(declaration, metadata);
});
this.pendingDirectives.clear();
this.pendingPipes.forEach((declaration) => {
const metadata = this.resolvers.pipe.resolve(declaration);
if (metadata === null) {
throw invalidTypeError(declaration.name, 'Pipe');
}
this.maybeStoreNgDef(NG_PIPE_DEF, declaration);
compilePipe(declaration, metadata);
});
this.pendingPipes.clear();
return needsAsyncResources;
}
private applyTransitiveScopes(): void {
| {
"end_byte": 20074,
"start_byte": 12268,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/test_bed_compiler.ts"
} |
angular/packages/core/testing/src/test_bed_compiler.ts_20078_27325 | this.overriddenModules.size > 0) {
// Module overrides (via `TestBed.overrideModule`) might affect scopes that were previously
// calculated and stored in `transitiveCompileScopes`. If module overrides are present,
// collect all affected modules and reset scopes to force their re-calculation.
const testingModuleDef = (this.testModuleType as any)[NG_MOD_DEF];
const affectedModules = this.collectModulesAffectedByOverrides(testingModuleDef.imports);
if (affectedModules.size > 0) {
affectedModules.forEach((moduleType) => {
if (!USE_RUNTIME_DEPS_TRACKER_FOR_JIT) {
this.storeFieldOfDefOnType(moduleType as any, NG_MOD_DEF, 'transitiveCompileScopes');
(moduleType as any)[NG_MOD_DEF].transitiveCompileScopes = null;
} else {
depsTracker.clearScopeCacheFor(moduleType);
}
});
}
}
const moduleToScope = new Map<Type<any> | TestingModuleOverride, NgModuleTransitiveScopes>();
const getScopeOfModule = (
moduleType: Type<any> | TestingModuleOverride,
): NgModuleTransitiveScopes => {
if (!moduleToScope.has(moduleType)) {
const isTestingModule = isTestingModuleOverride(moduleType);
const realType = isTestingModule ? this.testModuleType : (moduleType as Type<any>);
moduleToScope.set(moduleType, transitiveScopesFor(realType));
}
return moduleToScope.get(moduleType)!;
};
this.componentToModuleScope.forEach((moduleType, componentType) => {
if (moduleType !== null) {
const moduleScope = getScopeOfModule(moduleType);
this.storeFieldOfDefOnType(componentType, NG_COMP_DEF, 'directiveDefs');
this.storeFieldOfDefOnType(componentType, NG_COMP_DEF, 'pipeDefs');
patchComponentDefWithScope(getComponentDef(componentType)!, moduleScope);
}
// `tView` that is stored on component def contains information about directives and pipes
// that are in the scope of this component. Patching component scope will cause `tView` to be
// changed. Store original `tView` before patching scope, so the `tView` (including scope
// information) is restored back to its previous/original state before running next test.
// Resetting `tView` is also needed for cases when we apply provider overrides and those
// providers are defined on component's level, in which case they may end up included into
// `tView.blueprint`.
this.storeFieldOfDefOnType(componentType, NG_COMP_DEF, 'tView');
});
this.componentToModuleScope.clear();
}
private applyProviderOverrides(): void {
const maybeApplyOverrides = (field: string) => (type: Type<any>) => {
const resolver = field === NG_COMP_DEF ? this.resolvers.component : this.resolvers.directive;
const metadata = resolver.resolve(type)!;
if (this.hasProviderOverrides(metadata.providers)) {
this.patchDefWithProviderOverrides(type, field);
}
};
this.seenComponents.forEach(maybeApplyOverrides(NG_COMP_DEF));
this.seenDirectives.forEach(maybeApplyOverrides(NG_DIR_DEF));
this.seenComponents.clear();
this.seenDirectives.clear();
}
/**
* Applies provider overrides to a given type (either an NgModule or a standalone component)
* and all imported NgModules and standalone components recursively.
*/
private applyProviderOverridesInScope(type: Type<any>): void {
const hasScope = isStandaloneComponent(type) || isNgModule(type);
// The function can be re-entered recursively while inspecting dependencies
// of an NgModule or a standalone component. Exit early if we come across a
// type that can not have a scope (directive or pipe) or the type is already
// processed earlier.
if (!hasScope || this.scopesWithOverriddenProviders.has(type)) {
return;
}
this.scopesWithOverriddenProviders.add(type);
// NOTE: the line below triggers JIT compilation of the module injector,
// which also invokes verification of the NgModule semantics, which produces
// detailed error messages. The fact that the code relies on this line being
// present here is suspicious and should be refactored in a way that the line
// below can be moved (for ex. after an early exit check below).
const injectorDef: any = (type as any)[NG_INJ_DEF];
// No provider overrides, exit early.
if (this.providerOverridesByToken.size === 0) return;
if (isStandaloneComponent(type)) {
// Visit all component dependencies and override providers there.
const def = getComponentDef(type);
const dependencies = maybeUnwrapFn(def.dependencies ?? []);
for (const dependency of dependencies) {
this.applyProviderOverridesInScope(dependency);
}
} else {
const providers: Array<Provider | InternalEnvironmentProviders> = [
...injectorDef.providers,
...(this.providerOverridesByModule.get(type as InjectorType<any>) || []),
];
if (this.hasProviderOverrides(providers)) {
this.maybeStoreNgDef(NG_INJ_DEF, type);
this.storeFieldOfDefOnType(type, NG_INJ_DEF, 'providers');
injectorDef.providers = this.getOverriddenProviders(providers);
}
// Apply provider overrides to imported modules recursively
const moduleDef = (type as any)[NG_MOD_DEF];
const imports = maybeUnwrapFn(moduleDef.imports);
for (const importedModule of imports) {
this.applyProviderOverridesInScope(importedModule);
}
// Also override the providers on any ModuleWithProviders imports since those don't appear in
// the moduleDef.
for (const importedModule of flatten(injectorDef.imports)) {
if (isModuleWithProviders(importedModule)) {
this.defCleanupOps.push({
object: importedModule,
fieldName: 'providers',
originalValue: importedModule.providers,
});
importedModule.providers = this.getOverriddenProviders(
importedModule.providers as Array<Provider | InternalEnvironmentProviders>,
);
}
}
}
}
private patchComponentsWithExistingStyles(): void {
this.existingComponentStyles.forEach(
(styles, type) => ((type as any)[NG_COMP_DEF].styles = styles),
);
this.existingComponentStyles.clear();
}
private queueTypeArray(arr: any[], moduleType: Type<any> | TestingModuleOverride): void {
for (const value of arr) {
if (Array.isArray(value)) {
this.queueTypeArray(value, moduleType);
} else {
this.queueType(value, moduleType);
}
}
}
private recompileNgModule(ngModule: Type<any>, metadata: NgModule): void {
// Cache the initial ngModuleDef as it will be overwritten.
this.maybeStoreNgDef(NG_MOD_DEF, ngModule);
this.maybeStoreNgDef(NG_INJ_DEF, ngModule);
compileNgModuleDefs(ngModule as NgModuleType<any>, metadata);
}
private maybeRegisterComponentWithAsyncMetadata(type: Type<unknown>) {
const asyncMetadataFn = getAsyncClassMetadataFn(type);
if (asyncMetadataFn) {
this.componentsWithAsyncMetadata.add(type);
}
}
private queueType(type: Type<any>, moduleTyp | {
"end_byte": 27325,
"start_byte": 20078,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/test_bed_compiler.ts"
} |
angular/packages/core/testing/src/test_bed_compiler.ts_27329_36325 | ype<any> | TestingModuleOverride | null): void {
// If this is a component with async metadata (i.e. a component with a `@defer` block
// in a template) - store it for future processing.
this.maybeRegisterComponentWithAsyncMetadata(type);
const component = this.resolvers.component.resolve(type);
if (component) {
// Check whether a give Type has respective NG def (ɵcmp) and compile if def is
// missing. That might happen in case a class without any Angular decorators extends another
// class where Component/Directive/Pipe decorator is defined.
if (ɵisComponentDefPendingResolution(type) || !type.hasOwnProperty(NG_COMP_DEF)) {
this.pendingComponents.add(type);
}
this.seenComponents.add(type);
// Keep track of the module which declares this component, so later the component's scope
// can be set correctly. If the component has already been recorded here, then one of several
// cases is true:
// * the module containing the component was imported multiple times (common).
// * the component is declared in multiple modules (which is an error).
// * the component was in 'declarations' of the testing module, and also in an imported module
// in which case the module scope will be TestingModuleOverride.DECLARATION.
// * overrideTemplateUsingTestingModule was called for the component in which case the module
// scope will be TestingModuleOverride.OVERRIDE_TEMPLATE.
//
// If the component was previously in the testing module's 'declarations' (meaning the
// current value is TestingModuleOverride.DECLARATION), then `moduleType` is the component's
// real module, which was imported. This pattern is understood to mean that the component
// should use its original scope, but that the testing module should also contain the
// component in its scope.
if (
!this.componentToModuleScope.has(type) ||
this.componentToModuleScope.get(type) === TestingModuleOverride.DECLARATION
) {
this.componentToModuleScope.set(type, moduleType);
}
return;
}
const directive = this.resolvers.directive.resolve(type);
if (directive) {
if (!type.hasOwnProperty(NG_DIR_DEF)) {
this.pendingDirectives.add(type);
}
this.seenDirectives.add(type);
return;
}
const pipe = this.resolvers.pipe.resolve(type);
if (pipe && !type.hasOwnProperty(NG_PIPE_DEF)) {
this.pendingPipes.add(type);
return;
}
}
private queueTypesFromModulesArray(arr: any[]): void {
// Because we may encounter the same NgModule or a standalone Component while processing
// the dependencies of an NgModule or a standalone Component, we cache them in this set so we
// can skip ones that have already been seen encountered. In some test setups, this caching
// resulted in 10X runtime improvement.
const processedDefs = new Set();
const queueTypesFromModulesArrayRecur = (arr: any[]): void => {
for (const value of arr) {
if (Array.isArray(value)) {
queueTypesFromModulesArrayRecur(value);
} else if (hasNgModuleDef(value)) {
const def = value.ɵmod;
if (processedDefs.has(def)) {
continue;
}
processedDefs.add(def);
// Look through declarations, imports, and exports, and queue
// everything found there.
this.queueTypeArray(maybeUnwrapFn(def.declarations), value);
queueTypesFromModulesArrayRecur(maybeUnwrapFn(def.imports));
queueTypesFromModulesArrayRecur(maybeUnwrapFn(def.exports));
} else if (isModuleWithProviders(value)) {
queueTypesFromModulesArrayRecur([value.ngModule]);
} else if (isStandaloneComponent(value)) {
this.queueType(value, null);
const def = getComponentDef(value);
if (processedDefs.has(def)) {
continue;
}
processedDefs.add(def);
const dependencies = maybeUnwrapFn(def.dependencies ?? []);
dependencies.forEach((dependency) => {
// Note: in AOT, the `dependencies` might also contain regular
// (NgModule-based) Component, Directive and Pipes, so we handle
// them separately and proceed with recursive process for standalone
// Components and NgModules only.
if (isStandaloneComponent(dependency) || hasNgModuleDef(dependency)) {
queueTypesFromModulesArrayRecur([dependency]);
} else {
this.queueType(dependency, null);
}
});
}
}
};
queueTypesFromModulesArrayRecur(arr);
}
// When module overrides (via `TestBed.overrideModule`) are present, it might affect all modules
// that import (even transitively) an overridden one. For all affected modules we need to
// recalculate their scopes for a given test run and restore original scopes at the end. The goal
// of this function is to collect all affected modules in a set for further processing. Example:
// if we have the following module hierarchy: A -> B -> C (where `->` means `imports`) and module
// `C` is overridden, we consider `A` and `B` as affected, since their scopes might become
// invalidated with the override.
private collectModulesAffectedByOverrides(arr: any[]): Set<NgModuleType<any>> {
const seenModules = new Set<NgModuleType<any>>();
const affectedModules = new Set<NgModuleType<any>>();
const calcAffectedModulesRecur = (arr: any[], path: NgModuleType<any>[]): void => {
for (const value of arr) {
if (Array.isArray(value)) {
// If the value is an array, just flatten it (by invoking this function recursively),
// keeping "path" the same.
calcAffectedModulesRecur(value, path);
} else if (hasNgModuleDef(value)) {
if (seenModules.has(value)) {
// If we've seen this module before and it's included into "affected modules" list, mark
// the whole path that leads to that module as affected, but do not descend into its
// imports, since we already examined them before.
if (affectedModules.has(value)) {
path.forEach((item) => affectedModules.add(item));
}
continue;
}
seenModules.add(value);
if (this.overriddenModules.has(value)) {
path.forEach((item) => affectedModules.add(item));
}
// Examine module imports recursively to look for overridden modules.
const moduleDef = (value as any)[NG_MOD_DEF];
calcAffectedModulesRecur(maybeUnwrapFn(moduleDef.imports), path.concat(value));
}
}
};
calcAffectedModulesRecur(arr, []);
return affectedModules;
}
/**
* Preserve an original def (such as ɵmod, ɵinj, etc) before applying an override.
* Note: one class may have multiple defs (for example: ɵmod and ɵinj in case of
* an NgModule). If there is a def in a set already, don't override it, since
* an original one should be restored at the end of a test.
*/
private maybeStoreNgDef(prop: string, type: Type<any>) {
if (!this.initialNgDefs.has(type)) {
this.initialNgDefs.set(type, new Map());
}
const currentDefs = this.initialNgDefs.get(type)!;
if (!currentDefs.has(prop)) {
const currentDef = Object.getOwnPropertyDescriptor(type, prop);
currentDefs.set(prop, currentDef);
}
}
private storeFieldOfDefOnType(type: Type<any>, defField: string, fieldName: string): void {
const def: any = (type as any)[defField];
const originalValue: any = def[fieldName];
this.defCleanupOps.push({object: def, fieldName, originalValue});
}
/**
* Clears current components resolution queue, but stores the state of the queue, so we can
* restore it later. Clearing the queue is required before we try to compile components (via
* `TestBed.compileComponents`), so that component defs are in sync with the resolution queue.
*/
private clearComponentResolutionQueue() {
if (this.originalComponentResolutionQueue === null) {
this.originalComponentResolutionQueue = new Map();
}
ɵclearResolutionOfComponentResourcesQueue().forEach((value, key) =>
this.originalComponentResolutionQueue!.set(key, value),
);
}
/*
* Restores component resolution queue to the previously saved state. This operation is performed
* as a part of restoring the state after completion of the current set of tests (that might
* potentially mutate the state).
*/
private restoreComponentResolutionQueue() {
if (this.originalComponentResolutionQueue !== null) {
ɵrestoreComponentResolutionQueue(this.originalComponentResolutionQueue);
this.originalComponentResolutionQueue = null;
}
}
restoreOriginalState(): void {
// Process cleanup | {
"end_byte": 36325,
"start_byte": 27329,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/test_bed_compiler.ts"
} |
angular/packages/core/testing/src/test_bed_compiler.ts_36329_45565 | in reverse order so the field's original value is restored correctly (in
// case there were multiple overrides for the same field).
forEachRight(this.defCleanupOps, (op: CleanupOperation) => {
op.object[op.fieldName] = op.originalValue;
});
// Restore initial component/directive/pipe defs
this.initialNgDefs.forEach(
(defs: Map<string, PropertyDescriptor | undefined>, type: Type<any>) => {
if (USE_RUNTIME_DEPS_TRACKER_FOR_JIT) {
depsTracker.clearScopeCacheFor(type);
}
defs.forEach((descriptor, prop) => {
if (!descriptor) {
// Delete operations are generally undesirable since they have performance
// implications on objects they were applied to. In this particular case, situations
// where this code is invoked should be quite rare to cause any noticeable impact,
// since it's applied only to some test cases (for example when class with no
// annotations extends some @Component) when we need to clear 'ɵcmp' field on a given
// class to restore its original state (before applying overrides and running tests).
delete (type as any)[prop];
} else {
Object.defineProperty(type, prop, descriptor);
}
});
},
);
this.initialNgDefs.clear();
this.scopesWithOverriddenProviders.clear();
this.restoreComponentResolutionQueue();
// Restore the locale ID to the default value, this shouldn't be necessary but we never know
setLocaleId(DEFAULT_LOCALE_ID);
}
private compileTestModule(): void {
class RootScopeModule {}
compileNgModuleDefs(RootScopeModule as NgModuleType<any>, {
providers: [
...this.rootProviderOverrides,
internalProvideZoneChangeDetection({}),
TestBedApplicationErrorHandler,
{provide: ChangeDetectionScheduler, useExisting: ChangeDetectionSchedulerImpl},
],
});
const providers = [
{provide: Compiler, useFactory: () => new R3TestCompiler(this)},
{provide: DEFER_BLOCK_CONFIG, useValue: {behavior: this.deferBlockBehavior}},
{
provide: INTERNAL_APPLICATION_ERROR_HANDLER,
useFactory: () => {
if (this.rethrowApplicationTickErrors) {
const handler = inject(TestBedApplicationErrorHandler);
return (e: unknown) => {
handler.handleError(e);
};
} else {
const userErrorHandler = inject(ErrorHandler);
const ngZone = inject(NgZone);
return (e: unknown) => ngZone.runOutsideAngular(() => userErrorHandler.handleError(e));
}
},
},
...this.providers,
...this.providerOverrides,
];
const imports = [RootScopeModule, this.additionalModuleTypes, this.imports || []];
compileNgModuleDefs(
this.testModuleType,
{
declarations: this.declarations,
imports,
schemas: this.schemas,
providers,
},
/* allowDuplicateDeclarationsInRoot */ true,
);
this.applyProviderOverridesInScope(this.testModuleType);
}
get injector(): Injector {
if (this._injector !== null) {
return this._injector;
}
const providers: StaticProvider[] = [];
const compilerOptions = this.platform.injector.get(COMPILER_OPTIONS);
compilerOptions.forEach((opts) => {
if (opts.providers) {
providers.push(opts.providers);
}
});
if (this.compilerProviders !== null) {
providers.push(...(this.compilerProviders as StaticProvider[]));
}
this._injector = Injector.create({providers, parent: this.platform.injector});
return this._injector;
}
// get overrides for a specific provider (if any)
private getSingleProviderOverrides(provider: Provider): Provider | null {
const token = getProviderToken(provider);
return this.providerOverridesByToken.get(token) || null;
}
private getProviderOverrides(
providers?: Array<Provider | InternalEnvironmentProviders>,
): Provider[] {
if (!providers || !providers.length || this.providerOverridesByToken.size === 0) return [];
// There are two flattening operations here. The inner flattenProviders() operates on the
// metadata's providers and applies a mapping function which retrieves overrides for each
// incoming provider. The outer flatten() then flattens the produced overrides array. If this is
// not done, the array can contain other empty arrays (e.g. `[[], []]`) which leak into the
// providers array and contaminate any error messages that might be generated.
return flatten(
flattenProviders(
providers,
(provider: Provider) => this.getSingleProviderOverrides(provider) || [],
),
);
}
private getOverriddenProviders(
providers?: Array<Provider | InternalEnvironmentProviders>,
): Provider[] {
if (!providers || !providers.length || this.providerOverridesByToken.size === 0) return [];
const flattenedProviders = flattenProviders(providers);
const overrides = this.getProviderOverrides(flattenedProviders);
const overriddenProviders = [...flattenedProviders, ...overrides];
const final: Provider[] = [];
const seenOverriddenProviders = new Set<Provider>();
// We iterate through the list of providers in reverse order to make sure provider overrides
// take precedence over the values defined in provider list. We also filter out all providers
// that have overrides, keeping overridden values only. This is needed, since presence of a
// provider with `ngOnDestroy` hook will cause this hook to be registered and invoked later.
forEachRight(overriddenProviders, (provider: any) => {
const token: any = getProviderToken(provider);
if (this.providerOverridesByToken.has(token)) {
if (!seenOverriddenProviders.has(token)) {
seenOverriddenProviders.add(token);
// Treat all overridden providers as `{multi: false}` (even if it's a multi-provider) to
// make sure that provided override takes highest precedence and is not combined with
// other instances of the same multi provider.
final.unshift({...provider, multi: false});
}
} else {
final.unshift(provider);
}
});
return final;
}
private hasProviderOverrides(
providers?: Array<Provider | InternalEnvironmentProviders>,
): boolean {
return this.getProviderOverrides(providers).length > 0;
}
private patchDefWithProviderOverrides(declaration: Type<any>, field: string): void {
const def = (declaration as any)[field];
if (def && def.providersResolver) {
this.maybeStoreNgDef(field, declaration);
const resolver = def.providersResolver;
const processProvidersFn = (providers: Provider[]) => this.getOverriddenProviders(providers);
this.storeFieldOfDefOnType(declaration, field, 'providersResolver');
def.providersResolver = (ngDef: DirectiveDef<any>) => resolver(ngDef, processProvidersFn);
}
}
}
function initResolvers(): Resolvers {
return {
module: new NgModuleResolver(),
component: new ComponentResolver(),
directive: new DirectiveResolver(),
pipe: new PipeResolver(),
};
}
function isStandaloneComponent<T>(value: Type<T>): value is ComponentType<T> {
const def = getComponentDef(value);
return !!def?.standalone;
}
function getComponentDef(value: ComponentType<unknown>): ComponentDef<unknown>;
function getComponentDef(value: Type<unknown>): ComponentDef<unknown> | null;
function getComponentDef(value: Type<unknown>): ComponentDef<unknown> | null {
return (value as any).ɵcmp ?? null;
}
function hasNgModuleDef<T>(value: Type<T>): value is NgModuleType<T> {
return value.hasOwnProperty('ɵmod');
}
function isNgModule<T>(value: Type<T>): boolean {
return hasNgModuleDef(value);
}
function maybeUnwrapFn<T>(maybeFn: (() => T) | T): T {
return maybeFn instanceof Function ? maybeFn() : maybeFn;
}
function flatten<T>(values: any[]): T[] {
const out: T[] = [];
values.forEach((value) => {
if (Array.isArray(value)) {
out.push(...flatten<T>(value));
} else {
out.push(value);
}
});
return out;
}
function identityFn<T>(value: T): T {
return value;
}
function flattenProviders<T>(
providers: Array<Provider | InternalEnvironmentProviders>,
mapFn: (provider: Provider) => T,
): T[];
function flattenProviders(providers: Array<Provider | InternalEnvironmentProviders>): Provider[];
function flattenProviders(
providers: Array<Provider | InternalEnvironmentProviders>,
mapFn: (provider: Provider) => any = identityFn,
): any[] {
const out: any[] = [];
for (let provider of providers) {
if (isEnvironmentProviders(provider)) {
provider = provider.ɵproviders;
}
if (Array.isArray(provider)) {
out.push(...flattenProviders(provider, mapFn));
} else {
out.push(mapFn(provider));
}
}
return out;
}
function getProviderField(provider: Provider, field: string) {
return provider && typeof provider === 'object' && (provider as any)[field];
}
function getProviderToken(provider: Provider) {
return ge | {
"end_byte": 45565,
"start_byte": 36329,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/test_bed_compiler.ts"
} |
angular/packages/core/testing/src/test_bed_compiler.ts_45567_47573 | roviderField(provider, 'provide') || provider;
}
function isModuleWithProviders(value: any): value is ModuleWithProviders<any> {
return value.hasOwnProperty('ngModule');
}
function forEachRight<T>(values: T[], fn: (value: T, idx: number) => void): void {
for (let idx = values.length - 1; idx >= 0; idx--) {
fn(values[idx], idx);
}
}
function invalidTypeError(name: string, expectedType: string): Error {
return new Error(`${name} class doesn't have @${expectedType} decorator or is missing metadata.`);
}
class R3TestCompiler implements Compiler {
constructor(private testBed: TestBedCompiler) {}
compileModuleSync<T>(moduleType: Type<T>): NgModuleFactory<T> {
this.testBed._compileNgModuleSync(moduleType);
return new R3NgModuleFactory(moduleType);
}
async compileModuleAsync<T>(moduleType: Type<T>): Promise<NgModuleFactory<T>> {
await this.testBed._compileNgModuleAsync(moduleType);
return new R3NgModuleFactory(moduleType);
}
compileModuleAndAllComponentsSync<T>(moduleType: Type<T>): ModuleWithComponentFactories<T> {
const ngModuleFactory = this.compileModuleSync(moduleType);
const componentFactories = this.testBed._getComponentFactories(moduleType as NgModuleType<T>);
return new ModuleWithComponentFactories(ngModuleFactory, componentFactories);
}
async compileModuleAndAllComponentsAsync<T>(
moduleType: Type<T>,
): Promise<ModuleWithComponentFactories<T>> {
const ngModuleFactory = await this.compileModuleAsync(moduleType);
const componentFactories = this.testBed._getComponentFactories(moduleType as NgModuleType<T>);
return new ModuleWithComponentFactories(ngModuleFactory, componentFactories);
}
clearCache(): void {}
clearCacheFor(type: Type<any>): void {}
getModuleId(moduleType: Type<any>): string | undefined {
const meta = this.testBed._getModuleResolver().resolve(moduleType);
return (meta && meta.id) || undefined;
}
}
| {
"end_byte": 47573,
"start_byte": 45567,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/test_bed_compiler.ts"
} |
angular/packages/core/testing/src/testing.ts_0_1129 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the core/testing package.
*/
export * from './async';
export {ComponentFixture} from './component_fixture';
export {
resetFakeAsyncZone,
discardPeriodicTasks,
fakeAsync,
flush,
flushMicrotasks,
tick,
} from './fake_async';
export {
TestBed,
getTestBed,
TestBedStatic,
inject,
InjectSetupWrapper,
withModule,
} from './test_bed';
export {
TestComponentRenderer,
ComponentFixtureAutoDetect,
ComponentFixtureNoNgZone,
TestModuleMetadata,
TestEnvironmentOptions,
ModuleTeardownOptions,
} from './test_bed_common';
export * from './test_hooks';
export * from './metadata_override';
export {MetadataOverrider as ɵMetadataOverrider} from './metadata_overrider';
export {
ɵDeferBlockBehavior as DeferBlockBehavior,
ɵDeferBlockState as DeferBlockState,
} from '@angular/core';
export {DeferBlockFixture} from './defer';
| {
"end_byte": 1129,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/testing.ts"
} |
angular/packages/core/testing/src/testing_internal.ts_0_266 | /**
* @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 {inject} from './test_bed';
export * from './logger';
| {
"end_byte": 266,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/testing_internal.ts"
} |
angular/packages/core/testing/src/metadata_override.ts_0_374 | /**
* @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
*/
/**
* Type used for modifications to metadata
*
* @publicApi
*/
export type MetadataOverride<T> = {
add?: Partial<T>;
remove?: Partial<T>;
set?: Partial<T>;
};
| {
"end_byte": 374,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/metadata_override.ts"
} |
angular/packages/core/testing/src/async.ts_0_1329 | /**
* @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
*/
/**
* Wraps a test function in an asynchronous test zone. The test will automatically
* complete when all asynchronous calls within this zone are done. Can be used
* to wrap an {@link inject} call.
*
* Example:
*
* ```
* it('...', waitForAsync(inject([AClass], (object) => {
* object.doSomething.then(() => {
* expect(...);
* })
* })));
* ```
*
* @publicApi
*/
export function waitForAsync(fn: Function): (done: any) => any {
const _Zone: any = typeof Zone !== 'undefined' ? Zone : null;
if (!_Zone) {
return function () {
return Promise.reject(
'Zone is needed for the waitForAsync() test helper but could not be found. ' +
'Please make sure that your environment includes zone.js',
);
};
}
const asyncTest = _Zone && _Zone[_Zone.__symbol__('asyncTest')];
if (typeof asyncTest === 'function') {
return asyncTest(fn);
}
return function () {
return Promise.reject(
'zone-testing.js is needed for the async() test helper but could not be found. ' +
'Please make sure that your environment includes zone.js/testing',
);
};
}
| {
"end_byte": 1329,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/async.ts"
} |
angular/packages/core/testing/src/application_error_handler.ts_0_1205 | /**
* @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, inject, NgZone, Injectable} from '@angular/core';
export const RETHROW_APPLICATION_ERRORS_DEFAULT = true;
@Injectable()
export class TestBedApplicationErrorHandler {
private readonly zone = inject(NgZone);
private readonly userErrorHandler = inject(ErrorHandler);
readonly whenStableRejectFunctions: Set<(e: unknown) => void> = new Set();
handleError(e: unknown) {
try {
this.zone.runOutsideAngular(() => this.userErrorHandler.handleError(e));
} catch (userError: unknown) {
e = userError;
}
// Instead of throwing the error when there are outstanding `fixture.whenStable` promises,
// reject those promises with the error. This allows developers to write
// expectAsync(fix.whenStable()).toBeRejected();
if (this.whenStableRejectFunctions.size > 0) {
for (const fn of this.whenStableRejectFunctions.values()) {
fn(e);
}
this.whenStableRejectFunctions.clear();
} else {
throw e;
}
}
}
| {
"end_byte": 1205,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/application_error_handler.ts"
} |
angular/packages/core/testing/src/defer.ts_0_3378 | /**
* @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 {
ɵCONTAINER_HEADER_OFFSET as CONTAINER_HEADER_OFFSET,
ɵDeferBlockDetails as DeferBlockDetails,
ɵDeferBlockState as DeferBlockState,
ɵgetDeferBlocks as getDeferBlocks,
ɵrenderDeferBlockState as renderDeferBlockState,
ɵtriggerResourceLoading as triggerResourceLoading,
} from '@angular/core';
import type {ComponentFixture} from './component_fixture';
/**
* Represents an individual defer block for testing purposes.
*
* @publicApi
*/
export class DeferBlockFixture {
/** @nodoc */
constructor(
private block: DeferBlockDetails,
private componentFixture: ComponentFixture<unknown>,
) {}
/**
* Renders the specified state of the defer fixture.
* @param state the defer state to render
*/
async render(state: DeferBlockState): Promise<void> {
if (!hasStateTemplate(state, this.block)) {
const stateAsString = getDeferBlockStateNameFromEnum(state);
throw new Error(
`Tried to render this defer block in the \`${stateAsString}\` state, ` +
`but there was no @${stateAsString.toLowerCase()} block defined in a template.`,
);
}
if (state === DeferBlockState.Complete) {
await triggerResourceLoading(this.block.tDetails, this.block.lView, this.block.tNode);
}
// If the `render` method is used explicitly - skip timer-based scheduling for
// `@placeholder` and `@loading` blocks and render them immediately.
const skipTimerScheduling = true;
renderDeferBlockState(state, this.block.tNode, this.block.lContainer, skipTimerScheduling);
this.componentFixture.detectChanges();
}
/**
* Retrieves all nested child defer block fixtures
* in a given defer block.
*/
getDeferBlocks(): Promise<DeferBlockFixture[]> {
const deferBlocks: DeferBlockDetails[] = [];
// An LContainer that represents a defer block has at most 1 view, which is
// located right after an LContainer header. Get a hold of that view and inspect
// it for nested defer blocks.
const deferBlockFixtures = [];
if (this.block.lContainer.length >= CONTAINER_HEADER_OFFSET) {
const lView = this.block.lContainer[CONTAINER_HEADER_OFFSET];
getDeferBlocks(lView, deferBlocks);
for (const block of deferBlocks) {
deferBlockFixtures.push(new DeferBlockFixture(block, this.componentFixture));
}
}
return Promise.resolve(deferBlockFixtures);
}
}
function hasStateTemplate(state: DeferBlockState, block: DeferBlockDetails) {
switch (state) {
case DeferBlockState.Placeholder:
return block.tDetails.placeholderTmplIndex !== null;
case DeferBlockState.Loading:
return block.tDetails.loadingTmplIndex !== null;
case DeferBlockState.Error:
return block.tDetails.errorTmplIndex !== null;
case DeferBlockState.Complete:
return true;
default:
return false;
}
}
function getDeferBlockStateNameFromEnum(state: DeferBlockState) {
switch (state) {
case DeferBlockState.Placeholder:
return 'Placeholder';
case DeferBlockState.Loading:
return 'Loading';
case DeferBlockState.Error:
return 'Error';
default:
return 'Main';
}
}
| {
"end_byte": 3378,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/defer.ts"
} |
angular/packages/core/testing/src/metadata_overrider.ts_0_4230 | /**
* @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 as stringify} from '@angular/core';
import {MetadataOverride} from './metadata_override';
type StringMap = {
[key: string]: any;
};
let _nextReferenceId = 0;
export class MetadataOverrider {
private _references = new Map<any, string>();
/**
* Creates a new instance for the given metadata class
* based on an old instance and overrides.
*/
overrideMetadata<C extends T, T>(
metadataClass: {new (options: T): C},
oldMetadata: C,
override: MetadataOverride<T>,
): C {
const props: StringMap = {};
if (oldMetadata) {
_valueProps(oldMetadata).forEach((prop) => (props[prop] = (<any>oldMetadata)[prop]));
}
if (override.set) {
if (override.remove || override.add) {
throw new Error(`Cannot set and add/remove ${stringify(metadataClass)} at the same time!`);
}
setMetadata(props, override.set);
}
if (override.remove) {
removeMetadata(props, override.remove, this._references);
}
if (override.add) {
addMetadata(props, override.add);
}
return new metadataClass(<any>props);
}
}
function removeMetadata(metadata: StringMap, remove: any, references: Map<any, string>) {
const removeObjects = new Set<string>();
for (const prop in remove) {
const removeValue = remove[prop];
if (Array.isArray(removeValue)) {
removeValue.forEach((value: any) => {
removeObjects.add(_propHashKey(prop, value, references));
});
} else {
removeObjects.add(_propHashKey(prop, removeValue, references));
}
}
for (const prop in metadata) {
const propValue = metadata[prop];
if (Array.isArray(propValue)) {
metadata[prop] = propValue.filter(
(value: any) => !removeObjects.has(_propHashKey(prop, value, references)),
);
} else {
if (removeObjects.has(_propHashKey(prop, propValue, references))) {
metadata[prop] = undefined;
}
}
}
}
function addMetadata(metadata: StringMap, add: any) {
for (const prop in add) {
const addValue = add[prop];
const propValue = metadata[prop];
if (propValue != null && Array.isArray(propValue)) {
metadata[prop] = propValue.concat(addValue);
} else {
metadata[prop] = addValue;
}
}
}
function setMetadata(metadata: StringMap, set: any) {
for (const prop in set) {
metadata[prop] = set[prop];
}
}
function _propHashKey(propName: any, propValue: any, references: Map<any, string>): string {
let nextObjectId = 0;
const objectIds = new Map<object, string>();
const replacer = (key: any, value: any) => {
if (value !== null && typeof value === 'object') {
if (objectIds.has(value)) {
return objectIds.get(value);
}
// Record an id for this object such that any later references use the object's id instead
// of the object itself, in order to break cyclic pointers in objects.
objectIds.set(value, `ɵobj#${nextObjectId++}`);
// The first time an object is seen the object itself is serialized.
return value;
} else if (typeof value === 'function') {
value = _serializeReference(value, references);
}
return value;
};
return `${propName}:${JSON.stringify(propValue, replacer)}`;
}
function _serializeReference(ref: any, references: Map<any, string>): string {
let id = references.get(ref);
if (!id) {
id = `${stringify(ref)}${_nextReferenceId++}`;
references.set(ref, id);
}
return id;
}
function _valueProps(obj: any): string[] {
const props: string[] = [];
// regular public props
Object.keys(obj).forEach((prop) => {
if (!prop.startsWith('_')) {
props.push(prop);
}
});
// getters
let proto = obj;
while ((proto = Object.getPrototypeOf(proto))) {
Object.keys(proto).forEach((protoProp) => {
const desc = Object.getOwnPropertyDescriptor(proto, protoProp);
if (!protoProp.startsWith('_') && desc && 'get' in desc) {
props.push(protoProp);
}
});
}
return props;
}
| {
"end_byte": 4230,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/metadata_overrider.ts"
} |
angular/packages/core/testing/src/fake_async.ts_0_5631 | /**
* @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
*/
const _Zone: any = typeof Zone !== 'undefined' ? Zone : null;
const fakeAsyncTestModule = _Zone && _Zone[_Zone.__symbol__('fakeAsyncTest')];
const fakeAsyncTestModuleNotLoadedErrorMessage = `zone-testing.js is needed for the fakeAsync() test helper but could not be found.
Please make sure that your environment includes zone.js/testing`;
/**
* Clears out the shared fake async zone for a test.
* To be called in a global `beforeEach`.
*
* @publicApi
*/
export function resetFakeAsyncZone(): void {
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.resetFakeAsyncZone();
}
throw new Error(fakeAsyncTestModuleNotLoadedErrorMessage);
}
export function resetFakeAsyncZoneIfExists(): void {
if (fakeAsyncTestModule) {
fakeAsyncTestModule.resetFakeAsyncZone();
}
}
/**
* Wraps a function to be executed in the `fakeAsync` zone:
* - Microtasks are manually executed by calling `flushMicrotasks()`.
* - Timers are synchronous; `tick()` simulates the asynchronous passage of time.
*
* Can be used to wrap `inject()` calls.
*
* @param fn The function that you want to wrap in the `fakeAsync` zone.
* @param options
* - flush: When true, will drain the macrotask queue after the test function completes.
* When false, will throw an exception at the end of the function if there are pending timers.
*
* @usageNotes
* ### Example
*
* {@example core/testing/ts/fake_async.ts region='basic'}
*
*
* @returns The function wrapped to be executed in the `fakeAsync` zone.
* Any arguments passed when calling this returned function will be passed through to the `fn`
* function in the parameters when it is called.
*
* @publicApi
*/
export function fakeAsync(fn: Function, options?: {flush?: boolean}): (...args: any[]) => any {
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.fakeAsync(fn, options);
}
throw new Error(fakeAsyncTestModuleNotLoadedErrorMessage);
}
/**
* Simulates the asynchronous passage of time for the timers in the `fakeAsync` zone.
*
* The microtasks queue is drained at the very start of this function and after any timer callback
* has been executed.
*
* @param millis The number of milliseconds to advance the virtual timer.
* @param tickOptions The options to pass to the `tick()` function.
*
* @usageNotes
*
* The `tick()` option is a flag called `processNewMacroTasksSynchronously`,
* which determines whether or not to invoke new macroTasks.
*
* If you provide a `tickOptions` object, but do not specify a
* `processNewMacroTasksSynchronously` property (`tick(100, {})`),
* then `processNewMacroTasksSynchronously` defaults to true.
*
* If you omit the `tickOptions` parameter (`tick(100))`), then
* `tickOptions` defaults to `{processNewMacroTasksSynchronously: true}`.
*
* ### Example
*
* {@example core/testing/ts/fake_async.ts region='basic'}
*
* The following example includes a nested timeout (new macroTask), and
* the `tickOptions` parameter is allowed to default. In this case,
* `processNewMacroTasksSynchronously` defaults to true, and the nested
* function is executed on each tick.
*
* ```
* it ('test with nested setTimeout', fakeAsync(() => {
* let nestedTimeoutInvoked = false;
* function funcWithNestedTimeout() {
* setTimeout(() => {
* nestedTimeoutInvoked = true;
* });
* };
* setTimeout(funcWithNestedTimeout);
* tick();
* expect(nestedTimeoutInvoked).toBe(true);
* }));
* ```
*
* In the following case, `processNewMacroTasksSynchronously` is explicitly
* set to false, so the nested timeout function is not invoked.
*
* ```
* it ('test with nested setTimeout', fakeAsync(() => {
* let nestedTimeoutInvoked = false;
* function funcWithNestedTimeout() {
* setTimeout(() => {
* nestedTimeoutInvoked = true;
* });
* };
* setTimeout(funcWithNestedTimeout);
* tick(0, {processNewMacroTasksSynchronously: false});
* expect(nestedTimeoutInvoked).toBe(false);
* }));
* ```
*
*
* @publicApi
*/
export function tick(
millis: number = 0,
tickOptions: {processNewMacroTasksSynchronously: boolean} = {
processNewMacroTasksSynchronously: true,
},
): void {
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.tick(millis, tickOptions);
}
throw new Error(fakeAsyncTestModuleNotLoadedErrorMessage);
}
/**
* Flushes any pending microtasks and simulates the asynchronous passage of time for the timers in
* the `fakeAsync` zone by
* draining the macrotask queue until it is empty.
*
* @param maxTurns The maximum number of times the scheduler attempts to clear its queue before
* throwing an error.
* @returns The simulated time elapsed, in milliseconds.
*
* @publicApi
*/
export function flush(maxTurns?: number): number {
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.flush(maxTurns);
}
throw new Error(fakeAsyncTestModuleNotLoadedErrorMessage);
}
/**
* Discard all remaining periodic tasks.
*
* @publicApi
*/
export function discardPeriodicTasks(): void {
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.discardPeriodicTasks();
}
throw new Error(fakeAsyncTestModuleNotLoadedErrorMessage);
}
/**
* Flush any pending microtasks.
*
* @publicApi
*/
export function flushMicrotasks(): void {
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.flushMicrotasks();
}
throw new Error(fakeAsyncTestModuleNotLoadedErrorMessage);
}
| {
"end_byte": 5631,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/fake_async.ts"
} |
angular/packages/core/testing/src/test_hooks.ts_0_1850 | /**
* @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
*/
/**
* Public Test Library for unit testing Angular applications. Assumes that you are running
* with Jasmine, Mocha, or a similar framework which exports a beforeEach function and
* allows tests to be asynchronous by either returning a promise or using a 'done' parameter.
*/
import {resetFakeAsyncZoneIfExists} from './fake_async';
import {TestBedImpl} from './test_bed';
// Reset the test providers and the fake async zone before each test.
// We keep a guard because somehow this file can make it into a bundle and be executed
// beforeEach is only defined when executing the tests
globalThis.beforeEach?.(getCleanupHook(false));
// We provide both a `beforeEach` and `afterEach`, because the updated behavior for
// tearing down the module is supposed to run after the test so that we can associate
// teardown errors with the correct test.
// We keep a guard because somehow this file can make it into a bundle and be executed
// afterEach is only defined when executing the tests
globalThis.afterEach?.(getCleanupHook(true));
function getCleanupHook(expectedTeardownValue: boolean) {
return () => {
const testBed = TestBedImpl.INSTANCE;
if (testBed.shouldTearDownTestingModule() === expectedTeardownValue) {
testBed.resetTestingModule();
resetFakeAsyncZoneIfExists();
}
};
}
/**
* This API should be removed. But doing so seems to break `google3` and so it requires a bit of
* investigation.
*
* A work around is to mark it as `@codeGenApi` for now and investigate later.
*
* @codeGenApi
*/
// TODO(iminar): Remove this code in a safe way.
export const __core_private_testing_placeholder__ = '';
| {
"end_byte": 1850,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/test_hooks.ts"
} |
angular/packages/core/testing/src/test_bed.ts_0_5908 | /**
* @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
*/
// The formatter and CI disagree on how this import statement should be formatted. Both try to keep
// it on one line, too, which has gotten very hard to read & manage. So disable the formatter for
// this statement only.
import {
Component,
ComponentRef,
Directive,
EnvironmentInjector,
InjectFlags,
InjectOptions,
Injector,
NgModule,
NgZone,
Pipe,
PlatformRef,
ProviderToken,
runInInjectionContext,
Type,
ɵconvertToBitFlags as convertToBitFlags,
ɵDeferBlockBehavior as DeferBlockBehavior,
ɵEffectScheduler as EffectScheduler,
ɵflushModuleScopingQueueAsMuchAsPossible as flushModuleScopingQueueAsMuchAsPossible,
ɵgetAsyncClassMetadataFn as getAsyncClassMetadataFn,
ɵgetUnknownElementStrictMode as getUnknownElementStrictMode,
ɵgetUnknownPropertyStrictMode as getUnknownPropertyStrictMode,
ɵRender3ComponentFactory as ComponentFactory,
ɵRender3NgModuleRef as NgModuleRef,
ɵresetCompiledComponents as resetCompiledComponents,
ɵsetAllowDuplicateNgModuleIdsForTest as setAllowDuplicateNgModuleIdsForTest,
ɵsetUnknownElementStrictMode as setUnknownElementStrictMode,
ɵsetUnknownPropertyStrictMode as setUnknownPropertyStrictMode,
ɵstringify as stringify,
ɵMicrotaskEffectScheduler as MicrotaskEffectScheduler,
} from '@angular/core';
import {ComponentFixture} from './component_fixture';
import {MetadataOverride} from './metadata_override';
import {
ComponentFixtureNoNgZone,
DEFER_BLOCK_DEFAULT_BEHAVIOR,
ModuleTeardownOptions,
TEARDOWN_TESTING_MODULE_ON_DESTROY_DEFAULT,
TestComponentRenderer,
TestEnvironmentOptions,
TestModuleMetadata,
THROW_ON_UNKNOWN_ELEMENTS_DEFAULT,
THROW_ON_UNKNOWN_PROPERTIES_DEFAULT,
} from './test_bed_common';
import {TestBedCompiler} from './test_bed_compiler';
/**
* Static methods implemented by the `TestBed`.
*
* @publicApi
*/
export interface TestBedStatic extends TestBed {
new (...args: any[]): TestBed;
}
/**
* @publicApi
*/
export interface TestBed {
get platform(): PlatformRef;
get ngModule(): Type<any> | Type<any>[];
/**
* Initialize the environment for testing with a compiler factory, a PlatformRef, and an
* angular module. These are common to every test in the suite.
*
* This may only be called once, to set up the common providers for the current test
* suite on the current platform. If you absolutely need to change the providers,
* first use `resetTestEnvironment`.
*
* Test modules and platforms for individual platforms are available from
* '@angular/<platform_name>/testing'.
*/
initTestEnvironment(
ngModule: Type<any> | Type<any>[],
platform: PlatformRef,
options?: TestEnvironmentOptions,
): void;
/**
* Reset the providers for the test injector.
*/
resetTestEnvironment(): void;
resetTestingModule(): TestBed;
configureCompiler(config: {providers?: any[]; useJit?: boolean}): void;
configureTestingModule(moduleDef: TestModuleMetadata): TestBed;
compileComponents(): Promise<any>;
inject<T>(
token: ProviderToken<T>,
notFoundValue: undefined,
options: InjectOptions & {
optional?: false;
},
): T;
inject<T>(
token: ProviderToken<T>,
notFoundValue: null | undefined,
options: InjectOptions,
): T | null;
inject<T>(token: ProviderToken<T>, notFoundValue?: T, options?: InjectOptions): T;
/** @deprecated use object-based flags (`InjectOptions`) instead. */
inject<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): T;
/** @deprecated use object-based flags (`InjectOptions`) instead. */
inject<T>(token: ProviderToken<T>, notFoundValue: null, flags?: InjectFlags): T | null;
/** @deprecated from v9.0.0 use TestBed.inject */
get<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): any;
/** @deprecated from v9.0.0 use TestBed.inject */
get(token: any, notFoundValue?: any): any;
/**
* Runs the given function in the `EnvironmentInjector` context of `TestBed`.
*
* @see {@link EnvironmentInjector#runInContext}
*/
runInInjectionContext<T>(fn: () => T): T;
execute(tokens: any[], fn: Function, context?: any): any;
overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): TestBed;
overrideComponent(component: Type<any>, override: MetadataOverride<Component>): TestBed;
overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): TestBed;
overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): TestBed;
overrideTemplate(component: Type<any>, template: string): TestBed;
/**
* Overwrites all providers for the given token with the given provider definition.
*/
overrideProvider(
token: any,
provider: {useFactory: Function; deps: any[]; multi?: boolean},
): TestBed;
overrideProvider(token: any, provider: {useValue: any; multi?: boolean}): TestBed;
overrideProvider(
token: any,
provider: {useFactory?: Function; useValue?: any; deps?: any[]; multi?: boolean},
): TestBed;
overrideTemplateUsingTestingModule(component: Type<any>, template: string): TestBed;
createComponent<T>(component: Type<T>): ComponentFixture<T>;
/**
* Execute any pending effects.
*
* @developerPreview
*/
flushEffects(): void;
}
let _nextRootElementId = 0;
/**
* Returns a singleton of the `TestBed` class.
*
* @publicApi
*/
export function getTestBed(): TestBed {
return TestBedImpl.INSTANCE;
}
/**
* @description
* Configures and initializes environment for unit testing and provides methods for
* creating components and services in unit tests.
*
* TestBed is the primary api for writing unit tests for Angular applications and libraries.
*/
export class T | {
"end_byte": 5908,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/test_bed.ts"
} |
angular/packages/core/testing/src/test_bed.ts_5909_14354 | stBedImpl implements TestBed {
private static _INSTANCE: TestBedImpl | null = null;
static get INSTANCE(): TestBedImpl {
return (TestBedImpl._INSTANCE = TestBedImpl._INSTANCE || new TestBedImpl());
}
/**
* Teardown options that have been configured at the environment level.
* Used as a fallback if no instance-level options have been provided.
*/
private static _environmentTeardownOptions: ModuleTeardownOptions | undefined;
/**
* "Error on unknown elements" option that has been configured at the environment level.
* Used as a fallback if no instance-level option has been provided.
*/
private static _environmentErrorOnUnknownElementsOption: boolean | undefined;
/**
* "Error on unknown properties" option that has been configured at the environment level.
* Used as a fallback if no instance-level option has been provided.
*/
private static _environmentErrorOnUnknownPropertiesOption: boolean | undefined;
/**
* Teardown options that have been configured at the `TestBed` instance level.
* These options take precedence over the environment-level ones.
*/
private _instanceTeardownOptions: ModuleTeardownOptions | undefined;
/**
* Defer block behavior option that specifies whether defer blocks will be triggered manually
* or set to play through.
*/
private _instanceDeferBlockBehavior = DEFER_BLOCK_DEFAULT_BEHAVIOR;
/**
* "Error on unknown elements" option that has been configured at the `TestBed` instance level.
* This option takes precedence over the environment-level one.
*/
private _instanceErrorOnUnknownElementsOption: boolean | undefined;
/**
* "Error on unknown properties" option that has been configured at the `TestBed` instance level.
* This option takes precedence over the environment-level one.
*/
private _instanceErrorOnUnknownPropertiesOption: boolean | undefined;
/**
* Stores the previous "Error on unknown elements" option value,
* allowing to restore it in the reset testing module logic.
*/
private _previousErrorOnUnknownElementsOption: boolean | undefined;
/**
* Stores the previous "Error on unknown properties" option value,
* allowing to restore it in the reset testing module logic.
*/
private _previousErrorOnUnknownPropertiesOption: boolean | undefined;
/**
* Initialize the environment for testing with a compiler factory, a PlatformRef, and an
* angular module. These are common to every test in the suite.
*
* This may only be called once, to set up the common providers for the current test
* suite on the current platform. If you absolutely need to change the providers,
* first use `resetTestEnvironment`.
*
* Test modules and platforms for individual platforms are available from
* '@angular/<platform_name>/testing'.
*
* @publicApi
*/
static initTestEnvironment(
ngModule: Type<any> | Type<any>[],
platform: PlatformRef,
options?: TestEnvironmentOptions,
): TestBed {
const testBed = TestBedImpl.INSTANCE;
testBed.initTestEnvironment(ngModule, platform, options);
return testBed;
}
/**
* Reset the providers for the test injector.
*
* @publicApi
*/
static resetTestEnvironment(): void {
TestBedImpl.INSTANCE.resetTestEnvironment();
}
static configureCompiler(config: {providers?: any[]; useJit?: boolean}): TestBed {
return TestBedImpl.INSTANCE.configureCompiler(config);
}
/**
* Allows overriding default providers, directives, pipes, modules of the test injector,
* which are defined in test_injector.js
*/
static configureTestingModule(moduleDef: TestModuleMetadata): TestBed {
return TestBedImpl.INSTANCE.configureTestingModule(moduleDef);
}
/**
* Compile components with a `templateUrl` for the test's NgModule.
* It is necessary to call this function
* as fetching urls is asynchronous.
*/
static compileComponents(): Promise<any> {
return TestBedImpl.INSTANCE.compileComponents();
}
static overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): TestBed {
return TestBedImpl.INSTANCE.overrideModule(ngModule, override);
}
static overrideComponent(component: Type<any>, override: MetadataOverride<Component>): TestBed {
return TestBedImpl.INSTANCE.overrideComponent(component, override);
}
static overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): TestBed {
return TestBedImpl.INSTANCE.overrideDirective(directive, override);
}
static overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): TestBed {
return TestBedImpl.INSTANCE.overridePipe(pipe, override);
}
static overrideTemplate(component: Type<any>, template: string): TestBed {
return TestBedImpl.INSTANCE.overrideTemplate(component, template);
}
/**
* Overrides the template of the given component, compiling the template
* in the context of the TestingModule.
*
* Note: This works for JIT and AOTed components as well.
*/
static overrideTemplateUsingTestingModule(component: Type<any>, template: string): TestBed {
return TestBedImpl.INSTANCE.overrideTemplateUsingTestingModule(component, template);
}
static overrideProvider(
token: any,
provider: {
useFactory: Function;
deps: any[];
},
): TestBed;
static overrideProvider(token: any, provider: {useValue: any}): TestBed;
static overrideProvider(
token: any,
provider: {
useFactory?: Function;
useValue?: any;
deps?: any[];
},
): TestBed {
return TestBedImpl.INSTANCE.overrideProvider(token, provider);
}
static inject<T>(
token: ProviderToken<T>,
notFoundValue: undefined,
options: InjectOptions & {
optional?: false;
},
): T;
static inject<T>(
token: ProviderToken<T>,
notFoundValue: null | undefined,
options: InjectOptions,
): T | null;
static inject<T>(token: ProviderToken<T>, notFoundValue?: T, options?: InjectOptions): T;
/** @deprecated use object-based flags (`InjectOptions`) instead. */
static inject<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): T;
/** @deprecated use object-based flags (`InjectOptions`) instead. */
static inject<T>(token: ProviderToken<T>, notFoundValue: null, flags?: InjectFlags): T | null;
static inject<T>(
token: ProviderToken<T>,
notFoundValue?: T | null,
flags?: InjectFlags | InjectOptions,
): T | null {
return TestBedImpl.INSTANCE.inject(token, notFoundValue, convertToBitFlags(flags));
}
/** @deprecated from v9.0.0 use TestBed.inject */
static get<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): any;
/** @deprecated from v9.0.0 use TestBed.inject */
static get(token: any, notFoundValue?: any): any;
/** @deprecated from v9.0.0 use TestBed.inject */
static get(
token: any,
notFoundValue: any = Injector.THROW_IF_NOT_FOUND,
flags: InjectFlags = InjectFlags.Default,
): any {
return TestBedImpl.INSTANCE.inject(token, notFoundValue, flags);
}
/**
* Runs the given function in the `EnvironmentInjector` context of `TestBed`.
*
* @see {@link EnvironmentInjector#runInContext}
*/
static runInInjectionContext<T>(fn: () => T): T {
return TestBedImpl.INSTANCE.runInInjectionContext(fn);
}
static createComponent<T>(component: Type<T>): ComponentFixture<T> {
return TestBedImpl.INSTANCE.createComponent(component);
}
static resetTestingModule(): TestBed {
return TestBedImpl.INSTANCE.resetTestingModule();
}
static execute(tokens: any[], fn: Function, context?: any): any {
return TestBedImpl.INSTANCE.execute(tokens, fn, context);
}
static get platform(): PlatformRef {
return TestBedImpl.INSTANCE.platform;
}
static get ngModule(): Type<any> | Type<any>[] {
return TestBedImpl.INSTANCE.ngModule;
}
static flushEffects(): void {
return TestBedImpl.INSTANCE.flushEffects();
}
// Properties
platform: PlatformRef = null!;
ngModule: Type<any> | Type<any>[] = null!;
private _compiler: TestBedCompiler | null = null;
private _testModuleRef: NgModuleRef<any> | null = null;
private _activeFixtures: ComponentFixture<any>[] = [];
/**
* Internal-only flag to indicate whether a module
* scoping queue has been checked and flushed already.
* @nodoc
*/
globalCompilationChecked = false;
/**
* In | {
"end_byte": 14354,
"start_byte": 5909,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/test_bed.ts"
} |
angular/packages/core/testing/src/test_bed.ts_14358_23221 | lize the environment for testing with a compiler factory, a PlatformRef, and an
* angular module. These are common to every test in the suite.
*
* This may only be called once, to set up the common providers for the current test
* suite on the current platform. If you absolutely need to change the providers,
* first use `resetTestEnvironment`.
*
* Test modules and platforms for individual platforms are available from
* '@angular/<platform_name>/testing'.
*
* @publicApi
*/
initTestEnvironment(
ngModule: Type<any> | Type<any>[],
platform: PlatformRef,
options?: TestEnvironmentOptions,
): void {
if (this.platform || this.ngModule) {
throw new Error('Cannot set base providers because it has already been called');
}
TestBedImpl._environmentTeardownOptions = options?.teardown;
TestBedImpl._environmentErrorOnUnknownElementsOption = options?.errorOnUnknownElements;
TestBedImpl._environmentErrorOnUnknownPropertiesOption = options?.errorOnUnknownProperties;
this.platform = platform;
this.ngModule = ngModule;
this._compiler = new TestBedCompiler(this.platform, this.ngModule);
// TestBed does not have an API which can reliably detect the start of a test, and thus could be
// used to track the state of the NgModule registry and reset it correctly. Instead, when we
// know we're in a testing scenario, we disable the check for duplicate NgModule registration
// completely.
setAllowDuplicateNgModuleIdsForTest(true);
}
/**
* Reset the providers for the test injector.
*
* @publicApi
*/
resetTestEnvironment(): void {
this.resetTestingModule();
this._compiler = null;
this.platform = null!;
this.ngModule = null!;
TestBedImpl._environmentTeardownOptions = undefined;
setAllowDuplicateNgModuleIdsForTest(false);
}
resetTestingModule(): this {
this.checkGlobalCompilationFinished();
resetCompiledComponents();
if (this._compiler !== null) {
this.compiler.restoreOriginalState();
}
this._compiler = new TestBedCompiler(this.platform, this.ngModule);
// Restore the previous value of the "error on unknown elements" option
setUnknownElementStrictMode(
this._previousErrorOnUnknownElementsOption ?? THROW_ON_UNKNOWN_ELEMENTS_DEFAULT,
);
// Restore the previous value of the "error on unknown properties" option
setUnknownPropertyStrictMode(
this._previousErrorOnUnknownPropertiesOption ?? THROW_ON_UNKNOWN_PROPERTIES_DEFAULT,
);
// We have to chain a couple of try/finally blocks, because each step can
// throw errors and we don't want it to interrupt the next step and we also
// want an error to be thrown at the end.
try {
this.destroyActiveFixtures();
} finally {
try {
if (this.shouldTearDownTestingModule()) {
this.tearDownTestingModule();
}
} finally {
this._testModuleRef = null;
this._instanceTeardownOptions = undefined;
this._instanceErrorOnUnknownElementsOption = undefined;
this._instanceErrorOnUnknownPropertiesOption = undefined;
this._instanceDeferBlockBehavior = DEFER_BLOCK_DEFAULT_BEHAVIOR;
}
}
return this;
}
configureCompiler(config: {providers?: any[]; useJit?: boolean}): this {
if (config.useJit != null) {
throw new Error('JIT compiler is not configurable via TestBed APIs.');
}
if (config.providers !== undefined) {
this.compiler.setCompilerProviders(config.providers);
}
return this;
}
configureTestingModule(moduleDef: TestModuleMetadata): this {
this.assertNotInstantiated('TestBed.configureTestingModule', 'configure the test module');
// Trigger module scoping queue flush before executing other TestBed operations in a test.
// This is needed for the first test invocation to ensure that globally declared modules have
// their components scoped properly. See the `checkGlobalCompilationFinished` function
// description for additional info.
this.checkGlobalCompilationFinished();
// Always re-assign the options, even if they're undefined.
// This ensures that we don't carry them between tests.
this._instanceTeardownOptions = moduleDef.teardown;
this._instanceErrorOnUnknownElementsOption = moduleDef.errorOnUnknownElements;
this._instanceErrorOnUnknownPropertiesOption = moduleDef.errorOnUnknownProperties;
this._instanceDeferBlockBehavior = moduleDef.deferBlockBehavior ?? DEFER_BLOCK_DEFAULT_BEHAVIOR;
// Store the current value of the strict mode option,
// so we can restore it later
this._previousErrorOnUnknownElementsOption = getUnknownElementStrictMode();
setUnknownElementStrictMode(this.shouldThrowErrorOnUnknownElements());
this._previousErrorOnUnknownPropertiesOption = getUnknownPropertyStrictMode();
setUnknownPropertyStrictMode(this.shouldThrowErrorOnUnknownProperties());
this.compiler.configureTestingModule(moduleDef);
return this;
}
compileComponents(): Promise<any> {
return this.compiler.compileComponents();
}
inject<T>(
token: ProviderToken<T>,
notFoundValue: undefined,
options: InjectOptions & {
optional: true;
},
): T | null;
inject<T>(token: ProviderToken<T>, notFoundValue?: T, options?: InjectOptions): T;
inject<T>(token: ProviderToken<T>, notFoundValue: null, options?: InjectOptions): T | null;
/** @deprecated use object-based flags (`InjectOptions`) instead. */
inject<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): T;
/** @deprecated use object-based flags (`InjectOptions`) instead. */
inject<T>(token: ProviderToken<T>, notFoundValue: null, flags?: InjectFlags): T | null;
inject<T>(
token: ProviderToken<T>,
notFoundValue?: T | null,
flags?: InjectFlags | InjectOptions,
): T | null {
if ((token as unknown) === TestBed) {
return this as any;
}
const UNDEFINED = {} as unknown as T;
const result = this.testModuleRef.injector.get(token, UNDEFINED, convertToBitFlags(flags));
return result === UNDEFINED
? (this.compiler.injector.get(token, notFoundValue, flags) as any)
: result;
}
/** @deprecated from v9.0.0 use TestBed.inject */
get<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): any;
/** @deprecated from v9.0.0 use TestBed.inject */
get(token: any, notFoundValue?: any): any;
/** @deprecated from v9.0.0 use TestBed.inject */
get(
token: any,
notFoundValue: any = Injector.THROW_IF_NOT_FOUND,
flags: InjectFlags = InjectFlags.Default,
): any {
return this.inject(token, notFoundValue, flags);
}
runInInjectionContext<T>(fn: () => T): T {
return runInInjectionContext(this.inject(EnvironmentInjector), fn);
}
execute(tokens: any[], fn: Function, context?: any): any {
const params = tokens.map((t) => this.inject(t));
return fn.apply(context, params);
}
overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): this {
this.assertNotInstantiated('overrideModule', 'override module metadata');
this.compiler.overrideModule(ngModule, override);
return this;
}
overrideComponent(component: Type<any>, override: MetadataOverride<Component>): this {
this.assertNotInstantiated('overrideComponent', 'override component metadata');
this.compiler.overrideComponent(component, override);
return this;
}
overrideTemplateUsingTestingModule(component: Type<any>, template: string): this {
this.assertNotInstantiated(
'TestBed.overrideTemplateUsingTestingModule',
'Cannot override template when the test module has already been instantiated',
);
this.compiler.overrideTemplateUsingTestingModule(component, template);
return this;
}
overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): this {
this.assertNotInstantiated('overrideDirective', 'override directive metadata');
this.compiler.overrideDirective(directive, override);
return this;
}
overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): this {
this.assertNotInstantiated('overridePipe', 'override pipe metadata');
this.compiler.overridePipe(pipe, override);
return this;
}
/**
* Overwrites all providers for the given token with the given provider definition.
*/
overrideProvider(
token: any,
provider: {useFactory?: Function; useValue?: any; deps?: any[]},
): this {
this.assertNotInstantiated('overrideProvider', 'override provider');
this.compiler.overrideProvider(token, provider);
return this;
}
overrideTemplate(component: Type<any>, template: string): TestBed {
return this.overrideComponent(component, {set: {template, templateUrl: null!}});
}
createCompo | {
"end_byte": 23221,
"start_byte": 14358,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/test_bed.ts"
} |
angular/packages/core/testing/src/test_bed.ts_23225_31773 | <T>(type: Type<T>): ComponentFixture<T> {
const testComponentRenderer = this.inject(TestComponentRenderer);
const rootElId = `root${_nextRootElementId++}`;
testComponentRenderer.insertRootElement(rootElId);
if (getAsyncClassMetadataFn(type)) {
throw new Error(
`Component '${type.name}' has unresolved metadata. ` +
`Please call \`await TestBed.compileComponents()\` before running this test.`,
);
}
const componentDef = (type as any).ɵcmp;
if (!componentDef) {
throw new Error(`It looks like '${stringify(type)}' has not been compiled.`);
}
const componentFactory = new ComponentFactory(componentDef);
const initComponent = () => {
const componentRef = componentFactory.create(
Injector.NULL,
[],
`#${rootElId}`,
this.testModuleRef,
) as ComponentRef<T>;
return this.runInInjectionContext(() => new ComponentFixture(componentRef));
};
const noNgZone = this.inject(ComponentFixtureNoNgZone, false);
const ngZone = noNgZone ? null : this.inject(NgZone, null);
const fixture = ngZone ? ngZone.run(initComponent) : initComponent();
this._activeFixtures.push(fixture);
return fixture;
}
/**
* @internal strip this from published d.ts files due to
* https://github.com/microsoft/TypeScript/issues/36216
*/
private get compiler(): TestBedCompiler {
if (this._compiler === null) {
throw new Error(`Need to call TestBed.initTestEnvironment() first`);
}
return this._compiler;
}
/**
* @internal strip this from published d.ts files due to
* https://github.com/microsoft/TypeScript/issues/36216
*/
private get testModuleRef(): NgModuleRef<any> {
if (this._testModuleRef === null) {
this._testModuleRef = this.compiler.finalize();
}
return this._testModuleRef;
}
private assertNotInstantiated(methodName: string, methodDescription: string) {
if (this._testModuleRef !== null) {
throw new Error(
`Cannot ${methodDescription} when the test module has already been instantiated. ` +
`Make sure you are not using \`inject\` before \`${methodName}\`.`,
);
}
}
/**
* Check whether the module scoping queue should be flushed, and flush it if needed.
*
* When the TestBed is reset, it clears the JIT module compilation queue, cancelling any
* in-progress module compilation. This creates a potential hazard - the very first time the
* TestBed is initialized (or if it's reset without being initialized), there may be pending
* compilations of modules declared in global scope. These compilations should be finished.
*
* To ensure that globally declared modules have their components scoped properly, this function
* is called whenever TestBed is initialized or reset. The _first_ time that this happens, prior
* to any other operations, the scoping queue is flushed.
*/
private checkGlobalCompilationFinished(): void {
// Checking _testNgModuleRef is null should not be necessary, but is left in as an additional
// guard that compilations queued in tests (after instantiation) are never flushed accidentally.
if (!this.globalCompilationChecked && this._testModuleRef === null) {
flushModuleScopingQueueAsMuchAsPossible();
}
this.globalCompilationChecked = true;
}
private destroyActiveFixtures(): void {
let errorCount = 0;
this._activeFixtures.forEach((fixture) => {
try {
fixture.destroy();
} catch (e) {
errorCount++;
console.error('Error during cleanup of component', {
component: fixture.componentInstance,
stacktrace: e,
});
}
});
this._activeFixtures = [];
if (errorCount > 0 && this.shouldRethrowTeardownErrors()) {
throw Error(
`${errorCount} ${errorCount === 1 ? 'component' : 'components'} ` +
`threw errors during cleanup`,
);
}
}
shouldRethrowTeardownErrors(): boolean {
const instanceOptions = this._instanceTeardownOptions;
const environmentOptions = TestBedImpl._environmentTeardownOptions;
// If the new teardown behavior hasn't been configured, preserve the old behavior.
if (!instanceOptions && !environmentOptions) {
return TEARDOWN_TESTING_MODULE_ON_DESTROY_DEFAULT;
}
// Otherwise use the configured behavior or default to rethrowing.
return (
instanceOptions?.rethrowErrors ??
environmentOptions?.rethrowErrors ??
this.shouldTearDownTestingModule()
);
}
shouldThrowErrorOnUnknownElements(): boolean {
// Check if a configuration has been provided to throw when an unknown element is found
return (
this._instanceErrorOnUnknownElementsOption ??
TestBedImpl._environmentErrorOnUnknownElementsOption ??
THROW_ON_UNKNOWN_ELEMENTS_DEFAULT
);
}
shouldThrowErrorOnUnknownProperties(): boolean {
// Check if a configuration has been provided to throw when an unknown property is found
return (
this._instanceErrorOnUnknownPropertiesOption ??
TestBedImpl._environmentErrorOnUnknownPropertiesOption ??
THROW_ON_UNKNOWN_PROPERTIES_DEFAULT
);
}
shouldTearDownTestingModule(): boolean {
return (
this._instanceTeardownOptions?.destroyAfterEach ??
TestBedImpl._environmentTeardownOptions?.destroyAfterEach ??
TEARDOWN_TESTING_MODULE_ON_DESTROY_DEFAULT
);
}
getDeferBlockBehavior(): DeferBlockBehavior {
return this._instanceDeferBlockBehavior;
}
tearDownTestingModule() {
// If the module ref has already been destroyed, we won't be able to get a test renderer.
if (this._testModuleRef === null) {
return;
}
// Resolve the renderer ahead of time, because we want to remove the root elements as the very
// last step, but the injector will be destroyed as a part of the module ref destruction.
const testRenderer = this.inject(TestComponentRenderer);
try {
this._testModuleRef.destroy();
} catch (e) {
if (this.shouldRethrowTeardownErrors()) {
throw e;
} else {
console.error('Error during cleanup of a testing module', {
component: this._testModuleRef.instance,
stacktrace: e,
});
}
} finally {
testRenderer.removeAllRootElements?.();
}
}
/**
* Execute any pending effects.
*
* @developerPreview
*/
flushEffects(): void {
this.inject(MicrotaskEffectScheduler).flush();
this.inject(EffectScheduler).flush();
}
}
/**
* @description
* Configures and initializes environment for unit testing and provides methods for
* creating components and services in unit tests.
*
* `TestBed` is the primary api for writing unit tests for Angular applications and libraries.
*
* @publicApi
*/
export const TestBed: TestBedStatic = TestBedImpl;
/**
* Allows injecting dependencies in `beforeEach()` and `it()`. Note: this function
* (imported from the `@angular/core/testing` package) can **only** be used to inject dependencies
* in tests. To inject dependencies in your application code, use the [`inject`](api/core/inject)
* function from the `@angular/core` package instead.
*
* Example:
*
* ```
* beforeEach(inject([Dependency, AClass], (dep, object) => {
* // some code that uses `dep` and `object`
* // ...
* }));
*
* it('...', inject([AClass], (object) => {
* object.doSomething();
* expect(...);
* })
* ```
*
* @publicApi
*/
export function inject(tokens: any[], fn: Function): () => any {
const testBed = TestBedImpl.INSTANCE;
// Not using an arrow function to preserve context passed from call site
return function (this: unknown) {
return testBed.execute(tokens, fn, this);
};
}
/**
* @publicApi
*/
export class InjectSetupWrapper {
constructor(private _moduleDef: () => TestModuleMetadata) {}
private _addModule() {
const moduleDef = this._moduleDef();
if (moduleDef) {
TestBedImpl.configureTestingModule(moduleDef);
}
}
inject(tokens: any[], fn: Function): () => any {
const self = this;
// Not using an arrow function to preserve context passed from call site
return function (this: unknown) {
self._addModule();
return inject(tokens, fn).call(this);
};
}
}
/**
* @publicApi
*/
export function withModule(moduleDef: TestModuleMetadata): InjectSetupWrapper;
export function withModule(moduleDef: TestModuleMetadata, fn: Function): () => any;
export function | {
"end_byte": 31773,
"start_byte": 23225,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/test_bed.ts"
} |
angular/packages/core/testing/src/test_bed.ts_31774_32241 | withModule(
moduleDef: TestModuleMetadata,
fn?: Function | null,
): (() => any) | InjectSetupWrapper {
if (fn) {
// Not using an arrow function to preserve context passed from call site
return function (this: unknown) {
const testBed = TestBedImpl.INSTANCE;
if (moduleDef) {
testBed.configureTestingModule(moduleDef);
}
return fn.apply(this);
};
}
return new InjectSetupWrapper(() => moduleDef);
}
| {
"end_byte": 32241,
"start_byte": 31774,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/test_bed.ts"
} |
angular/packages/core/testing/src/logger.ts_0_609 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Injectable} from '@angular/core';
@Injectable()
export class Log<T = string> {
logItems: T[];
constructor() {
this.logItems = [];
}
add(value: T): void {
this.logItems.push(value);
}
fn(value: T) {
return () => {
this.logItems.push(value);
};
}
clear(): void {
this.logItems = [];
}
result(): string {
return this.logItems.join('; ');
}
}
| {
"end_byte": 609,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/logger.ts"
} |
angular/packages/core/testing/src/styling.ts_0_2437 | /**
* @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
*/
/**
* Returns element classes in form of a stable (sorted) string.
*
* @param element HTML Element.
* @returns Returns element classes in form of a stable (sorted) string.
*/
export function getSortedClassName(element: Element): string {
const names: string[] = Object.keys(getElementClasses(element));
names.sort();
return names.join(' ');
}
/**
* Returns element classes in form of a map.
*
* @param element HTML Element.
* @returns Map of class values.
*/
export function getElementClasses(element: Element): {[key: string]: true} {
const classes: {[key: string]: true} = {};
if (element.nodeType === Node.ELEMENT_NODE) {
const classList = element.classList;
for (let i = 0; i < classList.length; i++) {
const key = classList[i];
classes[key] = true;
}
}
return classes;
}
/**
* Returns element styles in form of a stable (sorted) string.
*
* @param element HTML Element.
* @returns Returns element styles in form of a stable (sorted) string.
*/
export function getSortedStyle(element: Element): string {
const styles = getElementStyles(element);
const names: string[] = Object.keys(styles);
names.sort();
let sorted = '';
names.forEach((key) => {
const value = styles[key];
if (value != null && value !== '') {
if (sorted !== '') sorted += ' ';
sorted += key + ': ' + value + ';';
}
});
return sorted;
}
/**
* Returns element styles in form of a map.
*
* @param element HTML Element.
* @returns Map of style values.
*/
export function getElementStyles(element: Element): {[key: string]: string} {
const styles: {[key: string]: string} = {};
if (element.nodeType === Node.ELEMENT_NODE) {
const style = (element as HTMLElement).style;
// reading `style.color` is a work around for a bug in Domino. The issue is that Domino has
// stale value for `style.length`. It seems that reading a property from the element causes the
// stale value to be updated. (As of Domino v 2.1.3)
style.color;
for (let i = 0; i < style.length; i++) {
const key = style.item(i);
const value = style.getPropertyValue(key);
if (value !== '') {
styles[key] = value;
}
}
}
return styles;
}
| {
"end_byte": 2437,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/styling.ts"
} |
angular/packages/core/testing/src/test_bed_common.ts_0_4123 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
InjectionToken,
SchemaMetadata,
ɵDeferBlockBehavior as DeferBlockBehavior,
} from '@angular/core';
/** Whether test modules should be torn down by default. */
export const TEARDOWN_TESTING_MODULE_ON_DESTROY_DEFAULT = true;
/** Whether unknown elements in templates should throw by default. */
export const THROW_ON_UNKNOWN_ELEMENTS_DEFAULT = false;
/** Whether unknown properties in templates should throw by default. */
export const THROW_ON_UNKNOWN_PROPERTIES_DEFAULT = false;
/** Whether defer blocks should use manual triggering or play through normally. */
export const DEFER_BLOCK_DEFAULT_BEHAVIOR = DeferBlockBehavior.Playthrough;
/**
* An abstract class for inserting the root test component element in a platform independent way.
*
* @publicApi
*/
export class TestComponentRenderer {
insertRootElement(rootElementId: string) {}
removeAllRootElements?() {}
}
/**
* @publicApi
*/
export const ComponentFixtureAutoDetect = new InjectionToken<boolean>('ComponentFixtureAutoDetect');
/**
* @publicApi
*/
export const ComponentFixtureNoNgZone = new InjectionToken<boolean>('ComponentFixtureNoNgZone');
/**
* @publicApi
*/
export interface TestModuleMetadata {
providers?: any[];
declarations?: any[];
imports?: any[];
schemas?: Array<SchemaMetadata | any[]>;
teardown?: ModuleTeardownOptions;
/**
* Whether NG0304 runtime errors should be thrown when unknown elements are present in component's
* template. Defaults to `false`, where the error is simply logged. If set to `true`, the error is
* thrown.
* @see [NG8001](/errors/NG8001) for the description of the problem and how to fix it
*/
errorOnUnknownElements?: boolean;
/**
* Whether errors should be thrown when unknown properties are present in component's template.
* Defaults to `false`, where the error is simply logged.
* If set to `true`, the error is thrown.
* @see [NG8002](/errors/NG8002) for the description of the error and how to fix it
*/
errorOnUnknownProperties?: boolean;
/**
* Whether errors that happen during application change detection should be rethrown.
*
* When `true`, errors that are caught during application change detection will
* be reported to the `ErrorHandler` and rethrown to prevent them from going
* unnoticed in tests.
*
* When `false`, errors are only forwarded to the `ErrorHandler`, which by default
* simply logs them to the console.
*
* Defaults to `true`.
*/
rethrowApplicationErrors?: boolean;
/**
* Whether defer blocks should behave with manual triggering or play through normally.
* Defaults to `manual`.
*/
deferBlockBehavior?: DeferBlockBehavior;
}
/**
* @publicApi
*/
export interface TestEnvironmentOptions {
/**
* Configures the test module teardown behavior in `TestBed`.
*/
teardown?: ModuleTeardownOptions;
/**
* Whether errors should be thrown when unknown elements are present in component's template.
* Defaults to `false`, where the error is simply logged.
* If set to `true`, the error is thrown.
* @see [NG8001](/errors/NG8001) for the description of the error and how to fix it
*/
errorOnUnknownElements?: boolean;
/**
* Whether errors should be thrown when unknown properties are present in component's template.
* Defaults to `false`, where the error is simply logged.
* If set to `true`, the error is thrown.
* @see [NG8002](/errors/NG8002) for the description of the error and how to fix it
*/
errorOnUnknownProperties?: boolean;
}
/**
* Configures the test module teardown behavior in `TestBed`.
* @publicApi
*/
export interface ModuleTeardownOptions {
/** Whether the test module should be destroyed after every test. Defaults to `true`. */
destroyAfterEach: boolean;
/** Whether errors during test module destruction should be re-thrown. Defaults to `true`. */
rethrowErrors?: boolean;
}
| {
"end_byte": 4123,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/test_bed_common.ts"
} |
angular/packages/core/testing/src/resolvers.ts_0_3504 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Component,
Directive,
NgModule,
Pipe,
Type,
ɵReflectionCapabilities as ReflectionCapabilities,
} from '@angular/core';
import {MetadataOverride} from './metadata_override';
import {MetadataOverrider} from './metadata_overrider';
const reflection = new ReflectionCapabilities();
/**
* Base interface to resolve `@Component`, `@Directive`, `@Pipe` and `@NgModule`.
*/
export interface Resolver<T> {
addOverride(type: Type<any>, override: MetadataOverride<T>): void;
setOverrides(overrides: Array<[Type<any>, MetadataOverride<T>]>): void;
resolve(type: Type<any>): T | null;
}
/**
* Allows to override ivy metadata for tests (via the `TestBed`).
*/
abstract class OverrideResolver<T> implements Resolver<T> {
private overrides = new Map<Type<any>, MetadataOverride<T>[]>();
private resolved = new Map<Type<any>, T | null>();
abstract get type(): any;
addOverride(type: Type<any>, override: MetadataOverride<T>) {
const overrides = this.overrides.get(type) || [];
overrides.push(override);
this.overrides.set(type, overrides);
this.resolved.delete(type);
}
setOverrides(overrides: Array<[Type<any>, MetadataOverride<T>]>) {
this.overrides.clear();
overrides.forEach(([type, override]) => {
this.addOverride(type, override);
});
}
getAnnotation(type: Type<any>): T | null {
const annotations = reflection.annotations(type);
// Try to find the nearest known Type annotation and make sure that this annotation is an
// instance of the type we are looking for, so we can use it for resolution. Note: there might
// be multiple known annotations found due to the fact that Components can extend Directives (so
// both Directive and Component annotations would be present), so we always check if the known
// annotation has the right type.
for (let i = annotations.length - 1; i >= 0; i--) {
const annotation = annotations[i];
const isKnownType =
annotation instanceof Directive ||
annotation instanceof Component ||
annotation instanceof Pipe ||
annotation instanceof NgModule;
if (isKnownType) {
return annotation instanceof this.type ? (annotation as unknown as T) : null;
}
}
return null;
}
resolve(type: Type<any>): T | null {
let resolved: T | null = this.resolved.get(type) || null;
if (!resolved) {
resolved = this.getAnnotation(type);
if (resolved) {
const overrides = this.overrides.get(type);
if (overrides) {
const overrider = new MetadataOverrider();
overrides.forEach((override) => {
resolved = overrider.overrideMetadata(this.type, resolved!, override);
});
}
}
this.resolved.set(type, resolved);
}
return resolved;
}
}
export class DirectiveResolver extends OverrideResolver<Directive> {
override get type() {
return Directive;
}
}
export class ComponentResolver extends OverrideResolver<Component> {
override get type() {
return Component;
}
}
export class PipeResolver extends OverrideResolver<Pipe> {
override get type() {
return Pipe;
}
}
export class NgModuleResolver extends OverrideResolver<NgModule> {
override get type() {
return NgModule;
}
}
| {
"end_byte": 3504,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/resolvers.ts"
} |
angular/packages/core/testing/src/component_fixture.ts_0_8762 | /**
* @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,
ChangeDetectorRef,
ComponentRef,
ɵChangeDetectionScheduler,
ɵNotificationSource,
DebugElement,
ElementRef,
getDebugNode,
inject,
NgZone,
RendererFactory2,
ViewRef,
ɵDeferBlockDetails as DeferBlockDetails,
ɵgetDeferBlocks as getDeferBlocks,
ɵNoopNgZone as NoopNgZone,
ɵZONELESS_ENABLED as ZONELESS_ENABLED,
ɵPendingTasks as PendingTasks,
ɵEffectScheduler as EffectScheduler,
ɵMicrotaskEffectScheduler as MicrotaskEffectScheduler,
} from '@angular/core';
import {Subscription} from 'rxjs';
import {DeferBlockFixture} from './defer';
import {ComponentFixtureAutoDetect, ComponentFixtureNoNgZone} from './test_bed_common';
import {TestBedApplicationErrorHandler} from './application_error_handler';
interface TestAppRef {
externalTestViews: Set<ViewRef>;
skipCheckNoChangesForExternalTestViews: Set<ViewRef>;
}
/**
* Fixture for debugging and testing a component.
*
* @publicApi
*/
export class ComponentFixture<T> {
/**
* The DebugElement associated with the root element of this component.
*/
debugElement: DebugElement;
/**
* The instance of the root component class.
*/
componentInstance: T;
/**
* The native element at the root of the component.
*/
nativeElement: any;
/**
* The ElementRef for the element at the root of the component.
*/
elementRef: ElementRef;
/**
* The ChangeDetectorRef for the component
*/
changeDetectorRef: ChangeDetectorRef;
private _renderer: RendererFactory2 | null | undefined;
private _isDestroyed: boolean = false;
/** @internal */
protected readonly _noZoneOptionIsSet = inject(ComponentFixtureNoNgZone, {optional: true});
/** @internal */
protected _ngZone: NgZone = this._noZoneOptionIsSet ? new NoopNgZone() : inject(NgZone);
// Inject ApplicationRef to ensure NgZone stableness causes after render hooks to run
// This will likely happen as a result of fixture.detectChanges because it calls ngZone.run
// This is a crazy way of doing things but hey, it's the world we live in.
// The zoneless scheduler should instead do this more imperatively by attaching
// the `ComponentRef` to `ApplicationRef` and calling `appRef.tick` as the `detectChanges`
// behavior.
/** @internal */
protected readonly _appRef = inject(ApplicationRef);
private readonly _testAppRef = this._appRef as unknown as TestAppRef;
private readonly pendingTasks = inject(PendingTasks);
private readonly appErrorHandler = inject(TestBedApplicationErrorHandler);
private readonly zonelessEnabled = inject(ZONELESS_ENABLED);
private readonly scheduler = inject(ɵChangeDetectionScheduler);
private readonly rootEffectScheduler = inject(EffectScheduler);
private readonly microtaskEffectScheduler = inject(MicrotaskEffectScheduler);
private readonly autoDetectDefault = this.zonelessEnabled ? true : false;
private autoDetect =
inject(ComponentFixtureAutoDetect, {optional: true}) ?? this.autoDetectDefault;
private subscriptions = new Subscription();
// TODO(atscott): Remove this from public API
ngZone = this._noZoneOptionIsSet ? null : this._ngZone;
/** @nodoc */
constructor(public componentRef: ComponentRef<T>) {
this.changeDetectorRef = componentRef.changeDetectorRef;
this.elementRef = componentRef.location;
this.debugElement = <DebugElement>getDebugNode(this.elementRef.nativeElement);
this.componentInstance = componentRef.instance;
this.nativeElement = this.elementRef.nativeElement;
this.componentRef = componentRef;
if (this.autoDetect) {
this._testAppRef.externalTestViews.add(this.componentRef.hostView);
this.scheduler?.notify(ɵNotificationSource.ViewAttached);
this.scheduler?.notify(ɵNotificationSource.MarkAncestorsForTraversal);
}
this.componentRef.hostView.onDestroy(() => {
this._testAppRef.externalTestViews.delete(this.componentRef.hostView);
});
// Create subscriptions outside the NgZone so that the callbacks run outside
// of NgZone.
this._ngZone.runOutsideAngular(() => {
this.subscriptions.add(
this._ngZone.onError.subscribe({
next: (error: any) => {
throw error;
},
}),
);
});
}
/**
* Trigger a change detection cycle for the component.
*/
detectChanges(checkNoChanges = true): void {
this.microtaskEffectScheduler.flush();
const originalCheckNoChanges = this.componentRef.changeDetectorRef.checkNoChanges;
try {
if (!checkNoChanges) {
this.componentRef.changeDetectorRef.checkNoChanges = () => {};
}
if (this.zonelessEnabled) {
try {
this._testAppRef.externalTestViews.add(this.componentRef.hostView);
this._appRef.tick();
} finally {
if (!this.autoDetect) {
this._testAppRef.externalTestViews.delete(this.componentRef.hostView);
}
}
} else {
// Run the change detection inside the NgZone so that any async tasks as part of the change
// detection are captured by the zone and can be waited for in isStable.
this._ngZone.run(() => {
// Flush root effects before `detectChanges()`, to emulate the sequencing of `tick()`.
this.rootEffectScheduler.flush();
this.changeDetectorRef.detectChanges();
this.checkNoChanges();
});
}
} finally {
this.componentRef.changeDetectorRef.checkNoChanges = originalCheckNoChanges;
}
this.microtaskEffectScheduler.flush();
}
/**
* Do a change detection run to make sure there were no changes.
*/
checkNoChanges(): void {
this.changeDetectorRef.checkNoChanges();
}
/**
* Set whether the fixture should autodetect changes.
*
* Also runs detectChanges once so that any existing change is detected.
*
* @param autoDetect Whether to autodetect changes. By default, `true`.
*/
autoDetectChanges(autoDetect = true): void {
if (this._noZoneOptionIsSet && !this.zonelessEnabled) {
throw new Error('Cannot call autoDetectChanges when ComponentFixtureNoNgZone is set.');
}
if (autoDetect !== this.autoDetect) {
if (autoDetect) {
this._testAppRef.externalTestViews.add(this.componentRef.hostView);
} else {
this._testAppRef.externalTestViews.delete(this.componentRef.hostView);
}
}
this.autoDetect = autoDetect;
this.detectChanges();
}
/**
* Return whether the fixture is currently stable or has async tasks that have not been completed
* yet.
*/
isStable(): boolean {
return !this.pendingTasks.hasPendingTasks.value;
}
/**
* Get a promise that resolves when the fixture is stable.
*
* This can be used to resume testing after events have triggered asynchronous activity or
* asynchronous change detection.
*/
whenStable(): Promise<any> {
if (this.isStable()) {
return Promise.resolve(false);
}
return new Promise((resolve, reject) => {
this.appErrorHandler.whenStableRejectFunctions.add(reject);
this._appRef.whenStable().then(() => {
this.appErrorHandler.whenStableRejectFunctions.delete(reject);
resolve(true);
});
});
}
/**
* Retrieves all defer block fixtures in the component fixture.
*/
getDeferBlocks(): Promise<DeferBlockFixture[]> {
const deferBlocks: DeferBlockDetails[] = [];
const lView = (this.componentRef.hostView as any)['_lView'];
getDeferBlocks(lView, deferBlocks);
const deferBlockFixtures = [];
for (const block of deferBlocks) {
deferBlockFixtures.push(new DeferBlockFixture(block, this));
}
return Promise.resolve(deferBlockFixtures);
}
private _getRenderer() {
if (this._renderer === undefined) {
this._renderer = this.componentRef.injector.get(RendererFactory2, null);
}
return this._renderer as RendererFactory2 | null;
}
/**
* Get a promise that resolves when the ui state is stable following animations.
*/
whenRenderingDone(): Promise<any> {
const renderer = this._getRenderer();
if (renderer && renderer.whenRenderingDone) {
return renderer.whenRenderingDone();
}
return this.whenStable();
}
/**
* Trigger component destruction.
*/
destroy(): void {
this.subscriptions.unsubscribe();
this._testAppRef.externalTestViews.delete(this.componentRef.hostView);
if (!this._isDestroyed) {
this.componentRef.destroy();
this._isDestroyed = true;
}
}
}
| {
"end_byte": 8762,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/src/component_fixture.ts"
} |
angular/packages/core/rxjs-interop/PACKAGE.md_0_114 | Includes utilities related to using the RxJS library in conjunction with Angular's signal-based reactivity system. | {
"end_byte": 114,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/PACKAGE.md"
} |
angular/packages/core/rxjs-interop/BUILD.bazel_0_887 | load("//tools:defaults.bzl", "generate_api_docs", "ng_module")
package(default_visibility = ["//visibility:public"])
exports_files(["package.json"])
ng_module(
name = "rxjs-interop",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
),
deps = [
"//packages:types",
"//packages/core",
"@npm//rxjs",
],
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
visibility = ["//visibility:public"],
)
generate_api_docs(
name = "core_rxjs-interop_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
"//packages/common:files_for_docgen",
"//packages/common/http:files_for_docgen",
],
entry_point = ":index.ts",
module_name = "@angular/core/rxjs-interop",
)
| {
"end_byte": 887,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/BUILD.bazel"
} |
angular/packages/core/rxjs-interop/index.ts_0_233 | /**
* @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 * from './src/index';
| {
"end_byte": 233,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/index.ts"
} |
angular/packages/core/rxjs-interop/public_api.ts_0_396 | /**
* @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/index';
// This file only reexports content of the `src` folder. Keep it that way.
| {
"end_byte": 396,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/public_api.ts"
} |
angular/packages/core/rxjs-interop/test/output_from_observable_spec.ts_0_5017 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {EventEmitter} from '@angular/core/public_api';
import {TestBed} from '@angular/core/testing';
import {BehaviorSubject, config, ReplaySubject, Subject} from 'rxjs';
import {outputFromObservable} from '../src';
describe('outputFromObservable()', () => {
// Safety clean-up as we are patching `onUnhandledError` in this test.
afterEach(() => (config.onUnhandledError = null));
it('should support emitting values via BehaviorSubject', () => {
const subject = new BehaviorSubject(0);
const output = TestBed.runInInjectionContext(() => outputFromObservable(subject));
const values: number[] = [];
output.subscribe((v) => values.push(v));
expect(values).toEqual([0]);
subject.next(1);
subject.next(2);
expect(values).toEqual([0, 1, 2]);
});
it('should support emitting values via ReplaySubject', () => {
const subject = new ReplaySubject<number>(1);
const output = TestBed.runInInjectionContext(() => outputFromObservable(subject));
// Emit before any subscribers!
subject.next(1);
const values: number[] = [];
output.subscribe((v) => values.push(v));
expect(values).toEqual([1]);
subject.next(2);
subject.next(3);
expect(values).toEqual([1, 2, 3]);
});
it('should support emitting values via Subject', () => {
const subject = new Subject<number>();
const output = TestBed.runInInjectionContext(() => outputFromObservable(subject));
// Emit before any subscribers! Ignored!
subject.next(1);
const values: number[] = [];
output.subscribe((v) => values.push(v));
expect(values).toEqual([]);
subject.next(2);
subject.next(3);
expect(values).toEqual([2, 3]);
});
it('should support emitting values via EventEmitter', () => {
const emitter = new EventEmitter<number>();
const output = TestBed.runInInjectionContext(() => outputFromObservable(emitter));
// Emit before any subscribers! Ignored!
emitter.next(1);
const values: number[] = [];
output.subscribe((v) => values.push(v));
expect(values).toEqual([]);
emitter.next(2);
emitter.next(3);
expect(values).toEqual([2, 3]);
});
it('should support explicit unsubscribing', () => {
const subject = new Subject<number>();
const output = TestBed.runInInjectionContext(() => outputFromObservable(subject));
const values: number[] = [];
expect(subject.observed).toBe(false);
const subscription = output.subscribe((v) => values.push(v));
expect(subject.observed).toBe(true);
expect(values).toEqual([]);
subject.next(2);
subject.next(3);
expect(values).toEqual([2, 3]);
subscription.unsubscribe();
expect(subject.observed).toBe(false);
});
it('should not yield more source values if directive is destroyed', () => {
const subject = new Subject<number>();
const output = TestBed.runInInjectionContext(() => outputFromObservable(subject));
const values: number[] = [];
expect(subject.observed).toBe(false);
output.subscribe((v) => values.push(v));
expect(subject.observed).toBe(true);
expect(values).toEqual([]);
// initiate destroy.
TestBed.resetTestingModule();
expect(subject.observed).toBe(false);
subject.next(2);
subject.next(3);
expect(values).toEqual([]);
});
it('should throw if subscriptions are added after directive destroy', () => {
const subject = new Subject<number>();
const output = TestBed.runInInjectionContext(() => outputFromObservable(subject));
// initiate destroy.
TestBed.resetTestingModule();
expect(() => output.subscribe(() => {})).toThrowError(
/Unexpected subscription to destroyed `OutputRef`/,
);
});
it('should be a noop when the source observable completes', () => {
const subject = new Subject<number>();
const outputRef = TestBed.runInInjectionContext(() => outputFromObservable(subject));
const values: number[] = [];
outputRef.subscribe((v) => values.push(v));
subject.next(1);
subject.next(2);
expect(values).toEqual([1, 2]);
subject.complete();
subject.next(3);
expect(values).toEqual([1, 2]);
});
it('should not handle errors from the source observable', (done) => {
const subject = new Subject<number>();
const outputRef = TestBed.runInInjectionContext(() => outputFromObservable(subject));
const values: number[] = [];
outputRef.subscribe((v) => values.push(v));
subject.next(1);
subject.next(2);
expect(values).toEqual([1, 2]);
config.onUnhandledError = (err) => {
config.onUnhandledError = null;
expect((err as Error).message).toEqual('test error message');
expect(values).toEqual([1, 2]);
done();
};
subject.error(new Error('test error message'));
});
});
| {
"end_byte": 5017,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/test/output_from_observable_spec.ts"
} |
angular/packages/core/rxjs-interop/test/pending_until_event_spec.ts_0_8143 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {EnvironmentInjector, ɵPendingTasks as PendingTasks, ApplicationRef} from '@angular/core';
import {
BehaviorSubject,
EMPTY,
Subject,
catchError,
delay,
config,
finalize,
firstValueFrom,
interval,
of,
} from 'rxjs';
import {pendingUntilEvent} from '@angular/core/rxjs-interop';
import {TestBed} from '@angular/core/testing';
describe('pendingUntilEvent', () => {
let taskService: PendingTasks;
let injector: EnvironmentInjector;
let appRef: ApplicationRef;
beforeEach(() => {
taskService = TestBed.inject(PendingTasks);
injector = TestBed.inject(EnvironmentInjector);
appRef = TestBed.inject(ApplicationRef);
});
it('should not block stability until subscription', async () => {
const originalSource = new BehaviorSubject(0);
const delayedSource = originalSource.pipe(delay(5), pendingUntilEvent(injector));
expect(taskService.hasPendingTasks.value).toEqual(false);
const emitPromise = firstValueFrom(delayedSource);
expect(taskService.hasPendingTasks.value).toEqual(true);
await expectAsync(emitPromise).toBeResolvedTo(0);
await expectAsync(appRef.whenStable()).toBeResolved();
});
it('runs the subscription body before stability', async () => {
const source = of(1).pipe(pendingUntilEvent(injector));
// stable before subscription
expect(taskService.hasPendingTasks.value).toEqual(false);
source.subscribe(() => {
// unstable within synchronous subscription body
expect(taskService.hasPendingTasks.value).toBe(true);
});
// stable after above synchronous subscription execution
await expectAsync(appRef.whenStable()).toBeResolved();
});
it('only blocks stability until first emit', async () => {
const intervalSource = interval(5).pipe(pendingUntilEvent(injector));
expect(taskService.hasPendingTasks.value).toEqual(false);
await new Promise<void>(async (resolve) => {
const subscription = intervalSource.subscribe(async (v) => {
if (v === 0) {
expect(taskService.hasPendingTasks.value).toBe(true);
} else {
await expectAsync(appRef.whenStable()).toBeResolved();
}
if (v === 3) {
subscription.unsubscribe();
resolve();
}
});
expect(taskService.hasPendingTasks.value).toBe(true);
});
});
it('should unblock stability on complete (but no emit)', async () => {
const sub = new Subject();
sub.asObservable().pipe(pendingUntilEvent(injector)).subscribe();
expect(taskService.hasPendingTasks.value).toBe(true);
sub.complete();
await expectAsync(appRef.whenStable()).toBeResolved();
});
it('should unblock stability on unsubscribe before emit', async () => {
const sub = new Subject();
const subscription = sub.asObservable().pipe(pendingUntilEvent(injector)).subscribe();
expect(taskService.hasPendingTasks.value).toBe(true);
subscription.unsubscribe();
await expectAsync(appRef.whenStable()).toBeResolved();
});
// Note that we cannot execute `finalize` operators that appear _after_ ours before
// removing the pending task. We need to register the finalize operation on the subscription
// as soon as the operator executes. A `finalize` operator later on in the stream will
// be appear later in the finalizers list. These finalizers are both registered and executed
// serially. We cannot execute our finalizer after other finalizers in the pipeline.
it('should execute user finalize body before stability (as long as it appears first)', async () => {
const sub = new Subject();
let finalizeExecuted = false;
const subscription = sub
.asObservable()
.pipe(
finalize(() => {
finalizeExecuted = true;
expect(taskService.hasPendingTasks.value).toBe(true);
}),
pendingUntilEvent(injector),
)
.subscribe();
expect(taskService.hasPendingTasks.value).toBe(true);
subscription.unsubscribe();
await expectAsync(appRef.whenStable()).toBeResolved();
expect(finalizeExecuted).toBe(true);
});
it('should not throw if application is destroyed before emit', async () => {
const sub = new Subject<void>();
sub.asObservable().pipe(pendingUntilEvent(injector)).subscribe();
expect(taskService.hasPendingTasks.value).toBe(true);
TestBed.resetTestingModule();
await expectAsync(appRef.whenStable()).toBeResolved();
sub.next();
await expectAsync(appRef.whenStable()).toBeResolved();
});
it('should unblock stability on error before emit', async () => {
const sub = new Subject<void>();
sub
.asObservable()
.pipe(
pendingUntilEvent(injector),
catchError(() => EMPTY),
)
.subscribe();
expect(taskService.hasPendingTasks.value).toBe(true);
sub.error(new Error('error in pipe'));
await expectAsync(appRef.whenStable()).toBeResolved();
sub.next();
await expectAsync(appRef.whenStable()).toBeResolved();
});
it('should unblock stability on error in subscription', async () => {
function nextUncaughtError() {
return new Promise((resolve) => {
config.onUnhandledError = (e) => {
config.onUnhandledError = null;
resolve(e);
};
});
}
const sub = new Subject<void>();
sub
.asObservable()
.pipe(pendingUntilEvent(injector))
.subscribe({
next: () => {
throw new Error('oh noes');
},
});
expect(taskService.hasPendingTasks.value).toBe(true);
const errorPromise = nextUncaughtError();
sub.next();
await expectAsync(errorPromise).toBeResolved();
await expectAsync(appRef.whenStable()).toBeResolved();
const errorPromise2 = nextUncaughtError();
sub.next();
await expectAsync(appRef.whenStable()).toBeResolved();
await expectAsync(errorPromise2).toBeResolved();
});
it('finalize and complete are delivered correctly', () => {
const sub = new Subject<void>();
let log: string[] = [];
const obs1 = sub.asObservable().pipe(
pendingUntilEvent(injector),
finalize(() => {
log.push('finalize');
}),
);
// complete after subscription
obs1.subscribe({
complete: () => {
log.push('complete');
},
});
sub.complete();
expect(log).toEqual(['complete', 'finalize']);
// already completed before subscription
log.length = 0;
obs1.subscribe({
complete: () => {
log.push('complete');
},
});
expect(log).toEqual(['complete', 'finalize']);
log.length = 0;
new Subject()
.asObservable()
.pipe(
pendingUntilEvent(injector),
finalize(() => {
log.push('finalize');
}),
)
.subscribe({
complete: () => {
log.push('complete');
},
})
.unsubscribe();
expect(log).toEqual(['finalize']);
});
it('should block stability for each new subscriber', async () => {
const sub = new Subject<void>();
const observable = sub.asObservable().pipe(delay(5), pendingUntilEvent(injector));
observable.subscribe();
expect(taskService.hasPendingTasks.value).toBe(true);
sub.next();
observable.subscribe();
// first subscription unblocks
await new Promise((r) => setTimeout(r, 5));
// still pending because the other subscribed after the emit
expect(taskService.hasPendingTasks.value).toBe(true);
sub.next();
await new Promise((r) => setTimeout(r, 3));
observable.subscribe();
sub.next();
// second subscription unblocks
await new Promise((r) => setTimeout(r, 2));
// still pending because third subscription delay not finished
expect(taskService.hasPendingTasks.value).toBe(true);
// finishes third subscription
await new Promise((r) => setTimeout(r, 3));
await expectAsync(appRef.whenStable()).toBeResolved();
});
});
| {
"end_byte": 8143,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/test/pending_until_event_spec.ts"
} |
angular/packages/core/rxjs-interop/test/to_signal_spec.ts_0_589 | /**
* @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 {
ChangeDetectionStrategy,
Component,
computed,
EnvironmentInjector,
Injector,
runInInjectionContext,
Signal,
} from '@angular/core';
import {toSignal} from '@angular/core/rxjs-interop';
import {TestBed} from '@angular/core/testing';
import {
BehaviorSubject,
Observable,
Observer,
ReplaySubject,
Subject,
Subscribable,
Unsubscribable,
} from 'rxjs'; | {
"end_byte": 589,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/test/to_signal_spec.ts"
} |
angular/packages/core/rxjs-interop/test/to_signal_spec.ts_591_9316 | describe('toSignal()', () => {
it(
'should reflect the last emitted value of an Observable',
test(() => {
const counter$ = new BehaviorSubject(0);
const counter = toSignal(counter$);
expect(counter()).toBe(0);
counter$.next(1);
expect(counter()).toBe(1);
counter$.next(3);
expect(counter()).toBe(3);
}),
);
it(
'should notify when the last emitted value of an Observable changes',
test(() => {
let seenValue: number = 0;
const counter$ = new BehaviorSubject(1);
const counter = toSignal(counter$);
expect(counter()).toBe(1);
counter$.next(2);
expect(counter()).toBe(2);
}),
);
it(
'should propagate an error returned by the Observable',
test(() => {
const counter$ = new BehaviorSubject(1);
const counter = toSignal(counter$);
expect(counter()).toBe(1);
counter$.error('fail');
expect(counter).toThrow('fail');
}),
);
it(
'should unsubscribe when the current context is destroyed',
test(() => {
const counter$ = new BehaviorSubject(0);
const injector = Injector.create({providers: []}) as EnvironmentInjector;
const counter = runInInjectionContext(injector, () => toSignal(counter$));
expect(counter()).toBe(0);
counter$.next(1);
expect(counter()).toBe(1);
// Destroying the injector should unsubscribe the Observable.
injector.destroy();
// The signal should have the last value observed.
expect(counter()).toBe(1);
// And this value should no longer be updating (unsubscribed).
counter$.next(2);
expect(counter()).toBe(1);
}),
);
it(
'should unsubscribe when an explicitly provided injector is destroyed',
test(() => {
const counter$ = new BehaviorSubject(0);
const injector = Injector.create({providers: []}) as EnvironmentInjector;
const counter = toSignal(counter$, {injector});
expect(counter()).toBe(0);
counter$.next(1);
expect(counter()).toBe(1);
// Destroying the injector should unsubscribe the Observable.
injector.destroy();
// The signal should have the last value observed.
expect(counter()).toBe(1);
// And this value should no longer be updating (unsubscribed).
counter$.next(2);
expect(counter()).toBe(1);
}),
);
it('should not require an injection context when manualCleanup is passed', () => {
const counter$ = new BehaviorSubject(0);
expect(() => toSignal(counter$, {manualCleanup: true})).not.toThrow();
counter$.complete();
});
it('should not unsubscribe when manualCleanup is passed', () => {
const counter$ = new BehaviorSubject(0);
const injector = Injector.create({providers: []}) as EnvironmentInjector;
const counter = runInInjectionContext(injector, () =>
toSignal(counter$, {manualCleanup: true}),
);
injector.destroy();
// Destroying the injector should not have unsubscribed the Observable.
counter$.next(1);
expect(counter()).toBe(1);
counter$.complete();
// The signal should have the last value observed before the observable completed.
expect(counter()).toBe(1);
});
it('should not allow toSignal creation in a reactive context', () => {
const counter$ = new BehaviorSubject(1);
const doubleCounter = computed(() => {
const counter = toSignal(counter$, {requireSync: true});
return counter() * 2;
});
expect(() => doubleCounter()).toThrowError(
/toSignal\(\) cannot be called from within a reactive context. Invoking `toSignal` causes new subscriptions every time./,
);
});
it('should throw the error back to RxJS if rejectErrors is set', () => {
let capturedObserver: Observer<number> = null!;
const fake$ = {
subscribe(observer: Observer<number>): Unsubscribable {
capturedObserver = observer;
return {unsubscribe(): void {}};
},
} as Subscribable<number>;
const s = toSignal(fake$, {initialValue: 0, rejectErrors: true, manualCleanup: true});
expect(s()).toBe(0);
if (capturedObserver === null) {
return fail('Observer not captured as expected.');
}
capturedObserver.next(1);
expect(s()).toBe(1);
expect(() => capturedObserver.error('test')).toThrow('test');
expect(s()).toBe(1);
});
describe('with no initial value', () => {
it(
'should return `undefined` if read before a value is emitted',
test(() => {
const counter$ = new Subject<number>();
const counter = toSignal(counter$);
expect(counter()).toBeUndefined();
counter$.next(1);
expect(counter()).toBe(1);
}),
);
it(
'should not throw if a value is emitted before called',
test(() => {
const counter$ = new Subject<number>();
const counter = toSignal(counter$);
counter$.next(1);
expect(() => counter()).not.toThrow();
}),
);
});
describe('with requireSync', () => {
it(
'should throw if created before a value is emitted',
test(() => {
const counter$ = new Subject<number>();
expect(() => toSignal(counter$, {requireSync: true})).toThrow();
}),
);
it(
'should not throw if a value emits synchronously on creation',
test(() => {
const counter$ = new ReplaySubject<number>(1);
counter$.next(1);
const counter = toSignal(counter$);
expect(counter()).toBe(1);
}),
);
});
describe('with an initial value', () => {
it(
'should return the initial value if called before a value is emitted',
test(() => {
const counter$ = new Subject<number>();
const counter = toSignal(counter$, {initialValue: null});
expect(counter()).toBeNull();
counter$.next(1);
expect(counter()).toBe(1);
}),
);
it(
'should not return the initial value if called after a value is emitted',
test(() => {
const counter$ = new Subject<number>();
const counter = toSignal(counter$, {initialValue: null});
counter$.next(1);
expect(counter()).not.toBeNull();
}),
);
});
describe('with an equality function', () => {
it(
'should not update for values considered equal',
test(() => {
const counter$ = new Subject<{value: number}>();
const counter = toSignal(counter$, {
initialValue: {value: 0},
equal: (a, b) => a.value === b.value,
});
let updates = 0;
const tracker = computed(() => {
updates++;
return counter();
});
expect(tracker()).toEqual({value: 0});
counter$.next({value: 1});
expect(tracker()).toEqual({value: 1});
expect(updates).toBe(2);
counter$.next({value: 1}); // same value as before
expect(tracker()).toEqual({value: 1});
expect(updates).toBe(2); // no downstream changes, since value was equal.
counter$.next({value: 2});
expect(tracker()).toEqual({value: 2});
expect(updates).toBe(3);
}),
);
it(
'should update when values are reference equal but equality function says otherwise',
test(() => {
const numsSet = new Set<number>();
const nums$ = new BehaviorSubject<Set<number>>(numsSet);
const nums = toSignal(nums$, {
requireSync: true,
equal: () => false,
});
let updates = 0;
const tracker = computed(() => {
updates++;
return Array.from(nums()!.values());
});
expect(tracker()).toEqual([]);
numsSet.add(1);
nums$.next(numsSet); // same value as before
expect(tracker()).toEqual([1]);
expect(updates).toBe(2);
}),
);
});
describe('in a @Component', () => {
it('should support `toSignal` as a class member initializer', () => {
@Component({
template: '{{counter()}}',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: false,
})
class TestCmp {
// Component creation should not run inside the template effect/consumer,
// hence using `toSignal` should be allowed/supported.
counter$ = new Subject<number>();
counter = toSignal(this.counter$);
}
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('');
fixture.componentInstance.counter$.next(2);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('2');
});
}); | {
"end_byte": 9316,
"start_byte": 591,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/test/to_signal_spec.ts"
} |
angular/packages/core/rxjs-interop/test/to_signal_spec.ts_9320_11276 | describe('type tests', () => {
const src = new Subject<any>();
it(
'should allow empty array initial values',
test(() => {
const res: Signal<string[]> = toSignal(src as Observable<string[]>, {initialValue: []});
expect(res).toBeDefined();
}),
);
it(
'should allow literal types',
test(() => {
type Animal = 'cat' | 'dog';
const res: Signal<Animal> = toSignal(src as Observable<Animal>, {initialValue: 'cat'});
expect(res).toBeDefined();
}),
);
it(
'should not allow initial values outside of the observable type',
test(() => {
type Animal = 'cat' | 'dog';
// @ts-expect-error
const res = toSignal(src as Observable<Animal>, {initialValue: 'cow'});
expect(res).toBeDefined();
}),
);
it(
'allows null as an initial value',
test(() => {
const res = toSignal(src as Observable<string>, {initialValue: null});
const res2: Signal<string | null> = res;
// @ts-expect-error
const res3: Signal<string | undefined> = res;
expect(res2).toBeDefined();
expect(res3).toBeDefined();
}),
);
it(
'allows undefined as an initial value',
test(() => {
const res = toSignal(src as Observable<string>, {initialValue: undefined});
const res2: Signal<string | undefined> = res;
// @ts-expect-error
const res3: Signal<string | null> = res;
expect(res2).toBeDefined();
expect(res3).toBeDefined();
}),
);
});
});
function test(fn: () => void | Promise<void>): () => Promise<void> {
return async () => {
const injector = Injector.create({
providers: [{provide: EnvironmentInjector, useFactory: () => injector}],
}) as EnvironmentInjector;
try {
return await runInInjectionContext(injector, fn);
} finally {
injector.destroy();
}
};
} | {
"end_byte": 11276,
"start_byte": 9320,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/test/to_signal_spec.ts"
} |
angular/packages/core/rxjs-interop/test/output_to_observable_spec.ts_0_4420 | /**
* @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, output} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {Subject} from 'rxjs';
import {outputFromObservable, outputToObservable} from '../src';
describe('outputToObservable()', () => {
it('should work with basic `output()`', () => {
const outputRef = TestBed.runInInjectionContext(() => output<number>());
const observable = outputToObservable(outputRef);
const values: number[] = [];
observable.subscribe({next: (v) => values.push(v)});
expect(values).toEqual([]);
outputRef.emit(1);
outputRef.emit(2);
expect(values).toEqual([1, 2]);
});
it('should complete observable upon directive destroy', () => {
const outputRef = TestBed.runInInjectionContext(() => output<number>());
const observable = outputToObservable(outputRef);
let completed = false;
const subscription = observable.subscribe({
complete: () => (completed = true),
});
outputRef.emit(1);
outputRef.emit(2);
expect(completed).toBe(false);
expect(subscription.closed).toBe(false);
// destroy `EnvironmentInjector`.
TestBed.resetTestingModule();
expect(completed).toBe(true);
expect(subscription.closed).toBe(true);
});
it('should complete EventEmitter upon directive destroy', () => {
const eventEmitter = TestBed.runInInjectionContext(() => new EventEmitter<number>());
const observable = outputToObservable(eventEmitter);
let completed = false;
const subscription = observable.subscribe({
complete: () => (completed = true),
});
eventEmitter.next(1);
eventEmitter.next(2);
expect(completed).toBe(false);
expect(subscription.closed).toBe(false);
expect(eventEmitter.observed).toBe(true);
// destroy `EnvironmentInjector`.
TestBed.resetTestingModule();
expect(completed).toBe(true);
expect(subscription.closed).toBe(true);
expect(eventEmitter.observed).toBe(false);
});
describe('with `outputFromObservable()` as source', () => {
it('should allow subscription', () => {
const subject = new Subject<number>();
const outputRef = TestBed.runInInjectionContext(() => outputFromObservable(subject));
const observable = outputToObservable(outputRef);
const values: number[] = [];
observable.subscribe({next: (v) => values.push(v)});
expect(values).toEqual([]);
subject.next(1);
subject.next(2);
expect(values).toEqual([1, 2]);
});
it('should complete observable upon directive destroy', () => {
const subject = new Subject<number>();
const outputRef = TestBed.runInInjectionContext(() => outputFromObservable(subject));
const observable = outputToObservable(outputRef);
let completed = false;
const subscription = observable.subscribe({
complete: () => (completed = true),
});
subject.next(1);
subject.next(2);
expect(completed).toBe(false);
expect(subscription.closed).toBe(false);
expect(subject.observed).toBe(true);
// destroy `EnvironmentInjector`.
TestBed.resetTestingModule();
expect(completed).toBe(true);
expect(subscription.closed).toBe(true);
expect(subject.observed).toBe(false);
});
it(
'may not complete the observable with an improperly ' +
'configured `OutputRef` without a destroy ref as source',
() => {
const outputRef = new EventEmitter<number>();
const observable = outputToObservable(outputRef);
let completed = false;
const subscription = observable.subscribe({
complete: () => (completed = true),
});
outputRef.next(1);
outputRef.next(2);
expect(completed).toBe(false);
expect(subscription.closed).toBe(false);
expect(outputRef.observed).toBe(true);
// destroy `EnvironmentInjector`.
TestBed.resetTestingModule();
expect(completed)
.withContext('Should not be completed as there is no known time when to destroy')
.toBe(false);
expect(subscription.closed).toBe(false);
expect(outputRef.observed).toBe(true);
},
);
});
});
| {
"end_byte": 4420,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/test/output_to_observable_spec.ts"
} |
angular/packages/core/rxjs-interop/test/to_observable_spec.ts_0_4621 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Component,
computed,
createEnvironmentInjector,
EnvironmentInjector,
Injector,
Signal,
signal,
} from '@angular/core';
import {toObservable} from '@angular/core/rxjs-interop';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {take, toArray} from 'rxjs/operators';
describe('toObservable()', () => {
let fixture!: ComponentFixture<unknown>;
let injector!: EnvironmentInjector;
@Component({
template: '',
standalone: true,
})
class Cmp {}
beforeEach(() => {
fixture = TestBed.createComponent(Cmp);
injector = TestBed.inject(EnvironmentInjector);
});
function flushEffects(): void {
fixture.detectChanges();
}
it('should produce an observable that tracks a signal', async () => {
const counter = signal(0);
const counterValues = toObservable(counter, {injector}).pipe(take(3), toArray()).toPromise();
// Initial effect execution, emits 0.
flushEffects();
counter.set(1);
// Emits 1.
flushEffects();
counter.set(2);
counter.set(3);
// Emits 3 (ignores 2 as it was batched by the effect).
flushEffects();
expect(await counterValues).toEqual([0, 1, 3]);
});
it('should propagate errors from the signal', () => {
const source = signal(1);
const counter = computed(() => {
const value = source();
if (value === 2) {
throw 'fail';
} else {
return value;
}
});
const counter$ = toObservable(counter, {injector});
let currentValue: number = 0;
let currentError: any = null;
const sub = counter$.subscribe({
next: (value) => (currentValue = value),
error: (err) => (currentError = err),
});
flushEffects();
expect(currentValue).toBe(1);
source.set(2);
flushEffects();
expect(currentError).toBe('fail');
sub.unsubscribe();
});
it('monitors the signal even if the Observable is never subscribed', () => {
let counterRead = false;
const counter = computed(() => {
counterRead = true;
return 0;
});
toObservable(counter, {injector});
// Simply creating the Observable shouldn't trigger a signal read.
expect(counterRead).toBeFalse();
// The signal is read after effects have run.
flushEffects();
expect(counterRead).toBeTrue();
});
it('should still monitor the signal if the Observable has no active subscribers', () => {
const counter = signal(0);
// Tracks how many reads of `counter()` there have been.
let readCount = 0;
const trackedCounter = computed(() => {
readCount++;
return counter();
});
const counter$ = toObservable(trackedCounter, {injector});
const sub = counter$.subscribe();
expect(readCount).toBe(0);
flushEffects();
expect(readCount).toBe(1);
// Sanity check of the read tracker - updating the counter should cause it to be read again
// by the active effect.
counter.set(1);
flushEffects();
expect(readCount).toBe(2);
// Tear down the only subscription.
sub.unsubscribe();
// Now, setting the signal still triggers additional reads
counter.set(2);
flushEffects();
expect(readCount).toBe(3);
});
it('stops monitoring the signal once injector is destroyed', () => {
const counter = signal(0);
// Tracks how many reads of `counter()` there have been.
let readCount = 0;
const trackedCounter = computed(() => {
readCount++;
return counter();
});
const childInjector = createEnvironmentInjector([], injector);
toObservable(trackedCounter, {injector: childInjector});
expect(readCount).toBe(0);
flushEffects();
expect(readCount).toBe(1);
// Now, setting the signal shouldn't trigger any additional reads, as the Injector was destroyed
childInjector.destroy();
counter.set(2);
flushEffects();
expect(readCount).toBe(1);
});
it('does not track downstream signal reads in the effect', () => {
const counter = signal(0);
const emits = signal(0);
toObservable(counter, {injector}).subscribe(() => {
// Read emits. If we are still tracked in the effect, this will cause an infinite loop by
// triggering the effect again.
emits();
emits.update((v) => v + 1);
});
flushEffects();
expect(emits()).toBe(1);
flushEffects();
expect(emits()).toBe(1);
});
});
| {
"end_byte": 4621,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/test/to_observable_spec.ts"
} |
angular/packages/core/rxjs-interop/test/rx_resource_spec.ts_0_1695 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {of, Observable} from 'rxjs';
import {TestBed} from '@angular/core/testing';
import {ApplicationRef, Injector, signal} from '@angular/core';
import {rxResource} from '@angular/core/rxjs-interop';
describe('rxResource()', () => {
it('should fetch data using an observable loader', async () => {
const injector = TestBed.inject(Injector);
const appRef = TestBed.inject(ApplicationRef);
const res = rxResource({
loader: () => of(1),
injector,
});
await appRef.whenStable();
expect(res.value()).toBe(1);
});
it('should cancel the fetch when a new request comes in', async () => {
const injector = TestBed.inject(Injector);
const appRef = TestBed.inject(ApplicationRef);
let unsub = false;
const request = signal(1);
const res = rxResource({
request,
loader: ({request}) =>
new Observable((sub) => {
if (request === 2) {
sub.next(true);
}
return () => {
if (request === 1) {
unsub = true;
}
};
}),
injector,
});
// Wait for the resource to reach loading state.
await waitFor(() => res.isLoading());
// Setting request = 2 should cancel request = 1
request.set(2);
await appRef.whenStable();
expect(unsub).toBe(true);
});
});
async function waitFor(fn: () => boolean): Promise<void> {
while (!fn()) {
await new Promise((resolve) => setTimeout(resolve, 1));
}
}
| {
"end_byte": 1695,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/test/rx_resource_spec.ts"
} |
angular/packages/core/rxjs-interop/test/BUILD.bazel_0_852 | load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library")
load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test")
circular_dependency_test(
name = "circular_deps_test",
entry_point = "angular/packages/core/rxjs-interop/index.mjs",
deps = ["//packages/core/rxjs-interop"],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["**/*.ts"]),
deps = [
"//packages:types",
"//packages/core",
"//packages/core/rxjs-interop",
"//packages/core/testing",
"//packages/private/testing",
"@npm//rxjs",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node"],
deps = [
":test_lib",
],
)
karma_web_test_suite(
name = "test_web",
deps = [
":test_lib",
],
)
| {
"end_byte": 852,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/test/BUILD.bazel"
} |
angular/packages/core/rxjs-interop/test/take_until_destroyed_spec.ts_0_2190 | /**
* @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 {DestroyRef, EnvironmentInjector, Injector, runInInjectionContext} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {takeUntilDestroyed} from '../src/take_until_destroyed';
describe('takeUntilDestroyed', () => {
it('should complete an observable when the current context is destroyed', () => {
const injector = Injector.create({providers: []}) as EnvironmentInjector;
const source$ = new BehaviorSubject(0);
const tied$ = runInInjectionContext(injector, () => source$.pipe(takeUntilDestroyed()));
let completed = false;
let last = 0;
tied$.subscribe({
next(value) {
last = value;
},
complete() {
completed = true;
},
});
source$.next(1);
expect(last).toBe(1);
injector.destroy();
expect(completed).toBeTrue();
source$.next(2);
expect(last).toBe(1);
});
it('should allow a manual DestroyRef to be passed', () => {
const injector = Injector.create({providers: []}) as EnvironmentInjector;
const source$ = new BehaviorSubject(0);
const tied$ = source$.pipe(takeUntilDestroyed(injector.get(DestroyRef)));
let completed = false;
let last = 0;
tied$.subscribe({
next(value) {
last = value;
},
complete() {
completed = true;
},
});
source$.next(1);
expect(last).toBe(1);
injector.destroy();
expect(completed).toBeTrue();
source$.next(2);
expect(last).toBe(1);
});
it('should unregister listener if observable is unsubscribed', () => {
const injector = Injector.create({providers: []}) as EnvironmentInjector;
const destroyRef = injector.get(DestroyRef);
const unregisterFn = jasmine.createSpy();
spyOn(destroyRef, 'onDestroy').and.returnValue(unregisterFn);
const subscription = new BehaviorSubject(0).pipe(takeUntilDestroyed(destroyRef)).subscribe();
subscription.unsubscribe();
expect(unregisterFn).toHaveBeenCalled();
});
});
| {
"end_byte": 2190,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/test/take_until_destroyed_spec.ts"
} |
angular/packages/core/rxjs-interop/src/rx_resource.ts_0_1716 | /**
* @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 {
assertInInjectionContext,
ResourceOptions,
resource,
ResourceLoaderParams,
ResourceRef,
} from '@angular/core';
import {Observable, Subject} from 'rxjs';
import {take, takeUntil} from 'rxjs/operators';
/**
* Like `ResourceOptions` but uses an RxJS-based `loader`.
*
* @experimental
*/
export interface RxResourceOptions<T, R> extends Omit<ResourceOptions<T, R>, 'loader'> {
loader: (params: ResourceLoaderParams<R>) => Observable<T>;
}
/**
* Like `resource` but uses an RxJS based `loader` which maps the request to an `Observable` of the
* resource's value. Like `firstValueFrom`, only the first emission of the Observable is considered.
*
* @experimental
*/
export function rxResource<T, R>(opts: RxResourceOptions<T, R>): ResourceRef<T> {
opts?.injector || assertInInjectionContext(rxResource);
return resource<T, R>({
...opts,
loader: (params) => {
const cancelled = new Subject<void>();
params.abortSignal.addEventListener('abort', () => cancelled.next());
// Note: this is identical to `firstValueFrom` which we can't use,
// because at the time of writing, `core` still supports rxjs 6.x.
return new Promise<T>((resolve, reject) => {
opts
.loader(params)
.pipe(take(1), takeUntil(cancelled))
.subscribe({
next: resolve,
error: reject,
complete: () => reject(new Error('Resource completed before producing a value')),
});
});
},
});
}
| {
"end_byte": 1716,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/src/rx_resource.ts"
} |
angular/packages/core/rxjs-interop/src/output_from_observable.ts_0_2542 | /**
* @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 {
assertInInjectionContext,
DestroyRef,
inject,
OutputOptions,
OutputRef,
OutputRefSubscription,
ɵRuntimeError,
ɵRuntimeErrorCode,
} from '@angular/core';
import {Observable} from 'rxjs';
import {takeUntilDestroyed} from './take_until_destroyed';
/**
* Implementation of `OutputRef` that emits values from
* an RxJS observable source.
*
* @internal
*/
class OutputFromObservableRef<T> implements OutputRef<T> {
private destroyed = false;
destroyRef = inject(DestroyRef);
constructor(private source: Observable<T>) {
this.destroyRef.onDestroy(() => {
this.destroyed = true;
});
}
subscribe(callbackFn: (value: T) => void): OutputRefSubscription {
if (this.destroyed) {
throw new ɵRuntimeError(
ɵRuntimeErrorCode.OUTPUT_REF_DESTROYED,
ngDevMode &&
'Unexpected subscription to destroyed `OutputRef`. ' +
'The owning directive/component is destroyed.',
);
}
// Stop yielding more values when the directive/component is already destroyed.
const subscription = this.source.pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
next: (value) => callbackFn(value),
});
return {
unsubscribe: () => subscription.unsubscribe(),
};
}
}
/**
* Declares an Angular output that is using an RxJS observable as a source
* for events dispatched to parent subscribers.
*
* The behavior for an observable as source is defined as followed:
* 1. New values are forwarded to the Angular output (next notifications).
* 2. Errors notifications are not handled by Angular. You need to handle these manually.
* For example by using `catchError`.
* 3. Completion notifications stop the output from emitting new values.
*
* @usageNotes
* Initialize an output in your directive by declaring a
* class field and initializing it with the `outputFromObservable()` function.
*
* ```ts
* @Directive({..})
* export class MyDir {
* nameChange$ = <some-observable>;
* nameChange = outputFromObservable(this.nameChange$);
* }
* ```
*
* @publicApi
*/
export function outputFromObservable<T>(
observable: Observable<T>,
opts?: OutputOptions,
): OutputRef<T> {
ngDevMode && assertInInjectionContext(outputFromObservable);
return new OutputFromObservableRef<T>(observable);
}
| {
"end_byte": 2542,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/src/output_from_observable.ts"
} |
angular/packages/core/rxjs-interop/src/take_until_destroyed.ts_0_1277 | /**
* @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 {assertInInjectionContext, DestroyRef, inject} from '@angular/core';
import {MonoTypeOperatorFunction, Observable} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
/**
* Operator which completes the Observable when the calling context (component, directive, service,
* etc) is destroyed.
*
* @param destroyRef optionally, the `DestroyRef` representing the current context. This can be
* passed explicitly to use `takeUntilDestroyed` outside of an [injection
* context](guide/di/dependency-injection-context). Otherwise, the current `DestroyRef` is injected.
*
* @publicApi
*/
export function takeUntilDestroyed<T>(destroyRef?: DestroyRef): MonoTypeOperatorFunction<T> {
if (!destroyRef) {
assertInInjectionContext(takeUntilDestroyed);
destroyRef = inject(DestroyRef);
}
const destroyed$ = new Observable<void>((observer) => {
const unregisterFn = destroyRef!.onDestroy(observer.next.bind(observer));
return unregisterFn;
});
return <T>(source: Observable<T>) => {
return source.pipe(takeUntil(destroyed$));
};
}
| {
"end_byte": 1277,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/src/take_until_destroyed.ts"
} |
angular/packages/core/rxjs-interop/src/output_to_observable.ts_0_1011 | /**
* @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 {OutputRef, ɵgetOutputDestroyRef} from '@angular/core';
import {Observable} from 'rxjs';
/**
* Converts an Angular output declared via `output()` or `outputFromObservable()`
* to an observable.
*
* You can subscribe to the output via `Observable.subscribe` then.
*
* @publicApi
*/
export function outputToObservable<T>(ref: OutputRef<T>): Observable<T> {
const destroyRef = ɵgetOutputDestroyRef(ref);
return new Observable<T>((observer) => {
// Complete the observable upon directive/component destroy.
// Note: May be `undefined` if an `EventEmitter` is declared outside
// of an injection context.
destroyRef?.onDestroy(() => observer.complete());
const subscription = ref.subscribe((v) => observer.next(v));
return () => subscription.unsubscribe();
});
}
| {
"end_byte": 1011,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/src/output_to_observable.ts"
} |
angular/packages/core/rxjs-interop/src/to_observable.ts_0_2469 | /**
* @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 {
assertInInjectionContext,
DestroyRef,
effect,
inject,
Injector,
Signal,
untracked,
ɵmicrotaskEffect as microtaskEffect,
} from '@angular/core';
import {Observable, ReplaySubject} from 'rxjs';
/**
* Options for `toObservable`.
*
* @developerPreview
*/
export interface ToObservableOptions {
/**
* The `Injector` to use when creating the underlying `effect` which watches the signal.
*
* If this isn't specified, the current [injection context](guide/di/dependency-injection-context)
* will be used.
*/
injector?: Injector;
}
/**
* Exposes the value of an Angular `Signal` as an RxJS `Observable`.
*
* The signal's value will be propagated into the `Observable`'s subscribers using an `effect`.
*
* `toObservable` must be called in an injection context unless an injector is provided via options.
*
* @developerPreview
*/
export function toObservable<T>(source: Signal<T>, options?: ToObservableOptions): Observable<T> {
!options?.injector && assertInInjectionContext(toObservable);
const injector = options?.injector ?? inject(Injector);
const subject = new ReplaySubject<T>(1);
const watcher = effect(
() => {
let value: T;
try {
value = source();
} catch (err) {
untracked(() => subject.error(err));
return;
}
untracked(() => subject.next(value));
},
{injector, manualCleanup: true},
);
injector.get(DestroyRef).onDestroy(() => {
watcher.destroy();
subject.complete();
});
return subject.asObservable();
}
export function toObservableMicrotask<T>(
source: Signal<T>,
options?: ToObservableOptions,
): Observable<T> {
!options?.injector && assertInInjectionContext(toObservable);
const injector = options?.injector ?? inject(Injector);
const subject = new ReplaySubject<T>(1);
const watcher = microtaskEffect(
() => {
let value: T;
try {
value = source();
} catch (err) {
untracked(() => subject.error(err));
return;
}
untracked(() => subject.next(value));
},
{injector, manualCleanup: true},
);
injector.get(DestroyRef).onDestroy(() => {
watcher.destroy();
subject.complete();
});
return subject.asObservable();
}
| {
"end_byte": 2469,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/src/to_observable.ts"
} |
angular/packages/core/rxjs-interop/src/to_signal.ts_0_5059 | /**
* @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 {
assertInInjectionContext,
assertNotInReactiveContext,
computed,
DestroyRef,
inject,
Injector,
signal,
Signal,
WritableSignal,
ɵRuntimeError,
ɵRuntimeErrorCode,
} from '@angular/core';
import {ValueEqualityFn} from '@angular/core/primitives/signals';
import {Observable, Subscribable} from 'rxjs';
/**
* Options for `toSignal`.
*
* @publicApi
*/
export interface ToSignalOptions<T> {
/**
* Initial value for the signal produced by `toSignal`.
*
* This will be the value of the signal until the observable emits its first value.
*/
initialValue?: unknown;
/**
* Whether to require that the observable emits synchronously when `toSignal` subscribes.
*
* If this is `true`, `toSignal` will assert that the observable produces a value immediately upon
* subscription. Setting this option removes the need to either deal with `undefined` in the
* signal type or provide an `initialValue`, at the cost of a runtime error if this requirement is
* not met.
*/
requireSync?: boolean;
/**
* `Injector` which will provide the `DestroyRef` used to clean up the Observable subscription.
*
* If this is not provided, a `DestroyRef` will be retrieved from the current [injection
* context](guide/di/dependency-injection-context), unless manual cleanup is requested.
*/
injector?: Injector;
/**
* Whether the subscription should be automatically cleaned up (via `DestroyRef`) when
* `toSignal`'s creation context is destroyed.
*
* If manual cleanup is enabled, then `DestroyRef` is not used, and the subscription will persist
* until the `Observable` itself completes.
*/
manualCleanup?: boolean;
/**
* Whether `toSignal` should throw errors from the Observable error channel back to RxJS, where
* they'll be processed as uncaught exceptions.
*
* In practice, this means that the signal returned by `toSignal` will keep returning the last
* good value forever, as Observables which error produce no further values. This option emulates
* the behavior of the `async` pipe.
*/
rejectErrors?: boolean;
/**
* A comparison function which defines equality for values emitted by the observable.
*
* Equality comparisons are executed against the initial value if one is provided.
*/
equal?: ValueEqualityFn<T>;
}
// Base case: no options -> `undefined` in the result type.
export function toSignal<T>(source: Observable<T> | Subscribable<T>): Signal<T | undefined>;
// Options with `undefined` initial value and no `requiredSync` -> `undefined`.
export function toSignal<T>(
source: Observable<T> | Subscribable<T>,
options: NoInfer<ToSignalOptions<T | undefined>> & {
initialValue?: undefined;
requireSync?: false;
},
): Signal<T | undefined>;
// Options with `null` initial value -> `null`.
export function toSignal<T>(
source: Observable<T> | Subscribable<T>,
options: NoInfer<ToSignalOptions<T | null>> & {initialValue?: null; requireSync?: false},
): Signal<T | null>;
// Options with `undefined` initial value and `requiredSync` -> strict result type.
export function toSignal<T>(
source: Observable<T> | Subscribable<T>,
options: NoInfer<ToSignalOptions<T>> & {initialValue?: undefined; requireSync: true},
): Signal<T>;
// Options with a more specific initial value type.
export function toSignal<T, const U extends T>(
source: Observable<T> | Subscribable<T>,
options: NoInfer<ToSignalOptions<T | U>> & {initialValue: U; requireSync?: false},
): Signal<T | U>;
/**
* Get the current value of an `Observable` as a reactive `Signal`.
*
* `toSignal` returns a `Signal` which provides synchronous reactive access to values produced
* by the given `Observable`, by subscribing to that `Observable`. The returned `Signal` will always
* have the most recent value emitted by the subscription, and will throw an error if the
* `Observable` errors.
*
* With `requireSync` set to `true`, `toSignal` will assert that the `Observable` produces a value
* immediately upon subscription. No `initialValue` is needed in this case, and the returned signal
* does not include an `undefined` type.
*
* By default, the subscription will be automatically cleaned up when the current [injection
* context](guide/di/dependency-injection-context) is destroyed. For example, when `toSignal` is
* called during the construction of a component, the subscription will be cleaned up when the
* component is destroyed. If an injection context is not available, an explicit `Injector` can be
* passed instead.
*
* If the subscription should persist until the `Observable` itself completes, the `manualCleanup`
* option can be specified instead, which disables the automatic subscription teardown. No injection
* context is needed in this configuration as well.
*
* @developerPreview
*/
e | {
"end_byte": 5059,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/src/to_signal.ts"
} |
angular/packages/core/rxjs-interop/src/to_signal.ts_5060_9130 | port function toSignal<T, U = undefined>(
source: Observable<T> | Subscribable<T>,
options?: ToSignalOptions<T | U> & {initialValue?: U},
): Signal<T | U> {
ngDevMode &&
assertNotInReactiveContext(
toSignal,
'Invoking `toSignal` causes new subscriptions every time. ' +
'Consider moving `toSignal` outside of the reactive context and read the signal value where needed.',
);
const requiresCleanup = !options?.manualCleanup;
requiresCleanup && !options?.injector && assertInInjectionContext(toSignal);
const cleanupRef = requiresCleanup
? (options?.injector?.get(DestroyRef) ?? inject(DestroyRef))
: null;
const equal = makeToSignalEqual(options?.equal);
// Note: T is the Observable value type, and U is the initial value type. They don't have to be
// the same - the returned signal gives values of type `T`.
let state: WritableSignal<State<T | U>>;
if (options?.requireSync) {
// Initially the signal is in a `NoValue` state.
state = signal({kind: StateKind.NoValue}, {equal});
} else {
// If an initial value was passed, use it. Otherwise, use `undefined` as the initial value.
state = signal<State<T | U>>(
{kind: StateKind.Value, value: options?.initialValue as U},
{equal},
);
}
// Note: This code cannot run inside a reactive context (see assertion above). If we'd support
// this, we would subscribe to the observable outside of the current reactive context, avoiding
// that side-effect signal reads/writes are attribute to the current consumer. The current
// consumer only needs to be notified when the `state` signal changes through the observable
// subscription. Additional context (related to async pipe):
// https://github.com/angular/angular/pull/50522.
const sub = source.subscribe({
next: (value) => state.set({kind: StateKind.Value, value}),
error: (error) => {
if (options?.rejectErrors) {
// Kick the error back to RxJS. It will be caught and rethrown in a macrotask, which causes
// the error to end up as an uncaught exception.
throw error;
}
state.set({kind: StateKind.Error, error});
},
// Completion of the Observable is meaningless to the signal. Signals don't have a concept of
// "complete".
});
if (options?.requireSync && state().kind === StateKind.NoValue) {
throw new ɵRuntimeError(
ɵRuntimeErrorCode.REQUIRE_SYNC_WITHOUT_SYNC_EMIT,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
'`toSignal()` called with `requireSync` but `Observable` did not emit synchronously.',
);
}
// Unsubscribe when the current context is destroyed, if requested.
cleanupRef?.onDestroy(sub.unsubscribe.bind(sub));
// The actual returned signal is a `computed` of the `State` signal, which maps the various states
// to either values or errors.
return computed(
() => {
const current = state();
switch (current.kind) {
case StateKind.Value:
return current.value;
case StateKind.Error:
throw current.error;
case StateKind.NoValue:
// This shouldn't really happen because the error is thrown on creation.
throw new ɵRuntimeError(
ɵRuntimeErrorCode.REQUIRE_SYNC_WITHOUT_SYNC_EMIT,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
'`toSignal()` called with `requireSync` but `Observable` did not emit synchronously.',
);
}
},
{equal: options?.equal},
);
}
function makeToSignalEqual<T>(
userEquality: ValueEqualityFn<T> = Object.is,
): ValueEqualityFn<State<T>> {
return (a, b) =>
a.kind === StateKind.Value && b.kind === StateKind.Value && userEquality(a.value, b.value);
}
const enum StateKind {
NoValue,
Value,
Error,
}
interface NoValueState {
kind: StateKind.NoValue;
}
interface ValueState<T> {
kind: StateKind.Value;
value: T;
}
interface ErrorState {
kind: StateKind.Error;
error: unknown;
}
type State<T> = NoValueState | ValueState<T> | ErrorState;
| {
"end_byte": 9130,
"start_byte": 5060,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/src/to_signal.ts"
} |
angular/packages/core/rxjs-interop/src/index.ts_0_684 | /**
* @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 {outputFromObservable} from './output_from_observable';
export {outputToObservable} from './output_to_observable';
export {takeUntilDestroyed} from './take_until_destroyed';
export {
toObservable,
ToObservableOptions,
toObservableMicrotask as ɵtoObservableMicrotask,
} from './to_observable';
export {toSignal, ToSignalOptions} from './to_signal';
export {pendingUntilEvent} from './pending_until_event';
export {RxResourceOptions, rxResource} from './rx_resource';
| {
"end_byte": 684,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/src/index.ts"
} |
angular/packages/core/rxjs-interop/src/pending_until_event.ts_0_1912 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {assertInInjectionContext, PendingTasks, inject, Injector} from '@angular/core';
import {MonoTypeOperatorFunction, Observable} from 'rxjs';
/**
* Operator which makes the application unstable until the observable emits, complets, errors, or is unsubscribed.
*
* Use this operator in observables whose subscriptions are important for rendering and should be included in SSR serialization.
*
* @param injector The `Injector` to use during creation. If this is not provided, the current injection context will be used instead (via `inject`).
*
* @experimental
*/
export function pendingUntilEvent<T>(injector?: Injector): MonoTypeOperatorFunction<T> {
if (injector === undefined) {
assertInInjectionContext(pendingUntilEvent);
injector = inject(Injector);
}
const taskService = injector.get(PendingTasks);
return (sourceObservable) => {
return new Observable<T>((originalSubscriber) => {
// create a new task on subscription
const removeTask = taskService.add();
let cleanedUp = false;
function cleanupTask() {
if (cleanedUp) {
return;
}
removeTask();
cleanedUp = true;
}
const innerSubscription = sourceObservable.subscribe({
next: (v) => {
originalSubscriber.next(v);
cleanupTask();
},
complete: () => {
originalSubscriber.complete();
cleanupTask();
},
error: (e) => {
originalSubscriber.error(e);
cleanupTask();
},
});
innerSubscription.add(() => {
originalSubscriber.unsubscribe();
cleanupTask();
});
return innerSubscription;
});
};
}
| {
"end_byte": 1912,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/src/pending_until_event.ts"
} |
angular/packages/core/schematics/rollup.config.js_0_1313 | /**
* @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
*/
const {nodeResolve} = require('@rollup/plugin-node-resolve');
const commonjs = require('@rollup/plugin-commonjs');
/** Removed license banners from input files. */
const stripBannerPlugin = {
name: 'strip-license-banner',
transform(code, _filePath) {
const banner = /(\/\**\s+\*\s@license.*?\*\/)/s.exec(code);
if (!banner) {
return;
}
const [bannerContent] = banner;
const pos = code.indexOf(bannerContent);
if (pos !== -1) {
const result = code.slice(0, pos) + code.slice(pos + bannerContent.length);
return {
code: result.trimStart(),
map: null,
};
}
return {
code: code,
map: null,
};
},
};
const banner = `'use strict';
/**
* @license Angular v0.0.0-PLACEHOLDER
* (c) 2010-2024 Google LLC. https://angular.io/
* License: MIT
*/`;
const plugins = [
nodeResolve({
jail: process.cwd(),
}),
stripBannerPlugin,
commonjs(),
];
const config = {
plugins,
external: ['typescript', 'tslib', /@angular-devkit\/.+/],
output: {
exports: 'auto',
banner,
},
};
module.exports = config;
| {
"end_byte": 1313,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/rollup.config.js"
} |
angular/packages/core/schematics/BUILD.bazel_0_3335 | load("//tools:defaults.bzl", "pkg_npm")
load("@npm//@bazel/rollup:index.bzl", "rollup_bundle")
exports_files([
"tsconfig.json",
"migrations.json",
"collection.json",
])
pkg_npm(
name = "npm_package",
srcs = [
"collection.json",
"migrations.json",
"package.json",
"//packages/core/schematics/ng-generate/control-flow-migration:static_files",
"//packages/core/schematics/ng-generate/inject-migration:static_files",
"//packages/core/schematics/ng-generate/output-migration:static_files",
"//packages/core/schematics/ng-generate/route-lazy-loading:static_files",
"//packages/core/schematics/ng-generate/signal-input-migration:static_files",
"//packages/core/schematics/ng-generate/signal-queries-migration:static_files",
"//packages/core/schematics/ng-generate/signals:static_files",
"//packages/core/schematics/ng-generate/standalone-migration:static_files",
],
validate = False,
visibility = ["//packages/core:__pkg__"],
deps = [
":bundles",
],
)
rollup_bundle(
name = "bundles",
config_file = ":rollup.config.js",
entry_points = {
"//packages/core/schematics/ng-generate/control-flow-migration:index.ts": "control-flow-migration",
"//packages/core/schematics/ng-generate/inject-migration:index.ts": "inject-migration",
"//packages/core/schematics/ng-generate/route-lazy-loading:index.ts": "route-lazy-loading",
"//packages/core/schematics/ng-generate/standalone-migration:index.ts": "standalone-migration",
"//packages/core/schematics/ng-generate/signals:index.ts": "signals",
"//packages/core/schematics/ng-generate/signal-input-migration:index.ts": "signal-input-migration",
"//packages/core/schematics/ng-generate/signal-queries-migration:index.ts": "signal-queries-migration",
"//packages/core/schematics/ng-generate/output-migration:index.ts": "output-migration",
"//packages/core/schematics/migrations/explicit-standalone-flag:index.ts": "explicit-standalone-flag",
"//packages/core/schematics/migrations/pending-tasks:index.ts": "pending-tasks",
"//packages/core/schematics/migrations/provide-initializer:index.ts": "provide-initializer",
},
format = "cjs",
link_workspace_root = True,
output_dir = True,
sourcemap = "false",
visibility = [
"//packages/core/schematics/test:__pkg__",
],
deps = [
"//packages/core/schematics/migrations/explicit-standalone-flag",
"//packages/core/schematics/migrations/pending-tasks",
"//packages/core/schematics/migrations/provide-initializer",
"//packages/core/schematics/ng-generate/control-flow-migration",
"//packages/core/schematics/ng-generate/inject-migration",
"//packages/core/schematics/ng-generate/output-migration",
"//packages/core/schematics/ng-generate/route-lazy-loading",
"//packages/core/schematics/ng-generate/signal-input-migration",
"//packages/core/schematics/ng-generate/signal-queries-migration",
"//packages/core/schematics/ng-generate/signals",
"//packages/core/schematics/ng-generate/standalone-migration",
"@npm//@rollup/plugin-commonjs",
"@npm//@rollup/plugin-node-resolve",
],
)
| {
"end_byte": 3335,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/BUILD.bazel"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden.txt_0_8602 | @@@@@@ any_test.ts @@@@@@
// tslint:disable
import {DebugElement, input} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
function it(msg: string, fn: () => void) {}
const harness = {
query<T>(v: T): DebugElement {
return null!;
},
};
class SubDir {
readonly name = input('John');
readonly name2 = input('');
}
class MyComp {
readonly hello = input('');
}
it('should work', () => {
const fixture = TestBed.createComponent(MyComp);
// `.componentInstance` is using `any` :O
const sub = fixture.debugElement.query(By.directive(SubDir)).componentInstance;
expect(sub.name()).toBe('John');
});
it('should work2', () => {
const fixture = TestBed.createComponent(MyComp);
// `.componentInstance` is using `any` :O
const sub = harness.query(SubDir).componentInstance;
expect(sub.name2()).toBe('John');
});
@@@@@@ base_class.ts @@@@@@
// tslint:disable
import {Directive, Input, input} from '@angular/core';
class BaseNonAngular {
disabled: string = '';
}
@Directive()
class Sub implements BaseNonAngular {
// should not be migrated because of the interface.
// TODO: Skipped for migration because:
// This input overrides a field from a superclass, while the superclass field
// is not migrated.
@Input() disabled = '';
}
class BaseWithAngular {
readonly disabled = input<string>('');
}
@Directive()
class Sub2 extends BaseWithAngular {
readonly disabled = input('');
}
interface BaseNonAngularInterface {
disabled: string;
}
@Directive()
class Sub3 implements BaseNonAngularInterface {
// should not be migrated because of the interface.
// TODO: Skipped for migration because:
// This input overrides a field from a superclass, while the superclass field
// is not migrated.
@Input() disabled = '';
}
@@@@@@ both_input_imports.ts @@@@@@
// tslint:disable
import {input, Input} from '@angular/core';
class BothInputImported {
// TODO: Skipped for migration because:
// Your application code writes to the input. This prevents migration.
@Input() decoratorInput = true;
signalInput = input<boolean>();
readonly thisCanBeMigrated = input(true);
__makeDecoratorInputNonMigratable() {
this.decoratorInput = false;
}
}
@@@@@@ catalyst_async_test.ts @@@@@@
import { UnwrapSignalInputs } from "google3/javascript/angular2/testing/catalyst/async";
// tslint:disable
import {input} from '@angular/core';
// google3/javascript/angular2/testing/catalyst/async
// ^^ this allows the advisor to even consider this file.
function it(msg: string, fn: () => void) {}
function bootstrapTemplate(tmpl: string, inputs: unknown) {}
class MyComp {
readonly hello = input('');
}
it('should work', () => {
const inputs = {
hello: 'test',
} as Partial<UnwrapSignalInputs<MyComp>>;
bootstrapTemplate('<my-comp [hello]="hello">', inputs);
});
@@@@@@ catalyst_test.ts @@@@@@
import { UnwrapSignalInputs } from "google3/javascript/angular2/testing/catalyst/fake_async";
// tslint:disable
import {input} from '@angular/core';
// google3/javascript/angular2/testing/catalyst/fake_async
// ^^ this allows the advisor to even consider this file.
function it(msg: string, fn: () => void) {}
function bootstrapTemplate(tmpl: string, inputs: unknown) {}
class MyComp {
readonly hello = input('');
}
it('should work', () => {
const inputs = {
hello: 'test',
} as Partial<UnwrapSignalInputs<MyComp>>;
bootstrapTemplate('<my-comp [hello]="hello">', inputs);
});
@@@@@@ catalyst_test_partial.ts @@@@@@
// tslint:disable
import {Component, Input, input} from '@angular/core';
// @ts-ignore
import {UnwrapSignalInputs} from 'google3/javascript/angular2/testing/catalyst/fake_async';
function renderComponent(inputs: Partial<UnwrapSignalInputs<TestableSecondaryRangePicker>> = {}) {}
@Component({
standalone: false,
jit: true,
template: '<bla [(ngModel)]="incompatible">',
})
class TestableSecondaryRangePicker {
readonly bla = input(true);
// TODO: Skipped for migration because:
// Your application code writes to the input. This prevents migration.
@Input() incompatible = true;
}
@@@@@@ constructor_initializations.ts @@@@@@
// tslint:disable
import {Input, Directive} from '@angular/core';
@Directive()
export class MyComp {
// TODO: Skipped for migration because:
// Your application code writes to the input. This prevents migration.
@Input() firstName: string;
constructor() {
// TODO: Consider initializations inside the constructor.
// Those are not migrated right now though, as they are writes.
this.firstName = 'Initial value';
}
}
@@@@@@ cross_references.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
@Component({
template: `
{{label()}}
`,
})
class Group {
readonly label = input.required<string>();
}
@Component({
template: `
@if (true) {
{{group.label()}}
}
{{group.label()}}
`,
})
class Option {
constructor(public group: Group) {}
}
@@@@@@ derived_class.ts @@@@@@
// tslint:disable
import {Input, Directive} from '@angular/core';
@Directive()
class Base {
// TODO: Skipped for migration because:
// The input cannot be migrated because the field is overridden by a subclass.
@Input() bla = true;
}
class Derived extends Base {
override bla = false;
}
// overridden in separate file
@Directive()
export class Base2 {
// TODO: Skipped for migration because:
// The input cannot be migrated because the field is overridden by a subclass.
@Input() bla = true;
}
// overridden in separate file
@Directive()
export class Base3 {
// TODO: Skipped for migration because:
// Your application code writes to the input. This prevents migration.
@Input() bla = true;
click() {
this.bla = false;
}
}
@@@@@@ derived_class_meta_input_alias.ts @@@@@@
// tslint:disable
import {Input, Directive} from '@angular/core';
@Directive()
class Base {
// should not be migrated.
// TODO: Skipped for migration because:
// The input cannot be migrated because the field is overridden by a subclass.
@Input() bla = true;
}
@Directive({
inputs: [{name: 'bla', alias: 'matDerivedBla'}],
})
class Derived extends Base {}
@@@@@@ derived_class_second_separate.ts @@@@@@
// tslint:disable
import {Input} from '@angular/core';
import {DerivedExternalWithInput} from './derived_class_separate_file';
class Derived extends DerivedExternalWithInput {
// this should be incompatible, because the final superclass
// within its own batch unit, detected a write that should
// propagate to this input.
// TODO: Skipped for migration because:
// This input is inherited from a superclass, but the parent cannot be migrated.
@Input() override bla = false;
}
@@@@@@ derived_class_separate_file.ts @@@@@@
// tslint:disable
import {Input} from '@angular/core';
import {Base2, Base3} from './derived_class';
class DerivedExternal extends Base2 {
override bla = false;
}
export class DerivedExternalWithInput extends Base3 {
// TODO: Skipped for migration because:
// This input is inherited from a superclass, but the parent cannot be migrated.
@Input() override bla = true;
}
@@@@@@ different_instantiations_of_reference.ts @@@@@@
// tslint:disable
import {Directive, Component, input} from '@angular/core';
// Material form field test case
let nextUniqueId = 0;
@Directive()
export class MatHint {
align: string = '';
readonly id = input(`mat-hint-${nextUniqueId++}`);
}
@Component({
template: ``,
})
export class MatFormFieldTest {
private declare _hintChildren: MatHint[];
private _control = true;
private _somethingElse = false;
private _syncDescribedByIds() {
if (this._control) {
let ids: string[] = [];
const startHint = this._hintChildren
? this._hintChildren.find((hint) => hint.align === 'start')
: null;
const endHint = this._hintChildren
? this._hintChildren.find((hint) => hint.align === 'end')
: null;
if (startHint) {
ids.push(startHint.id());
} else if (this._somethingElse) {
ids.push(`val:${this._somethingElse}`);
}
if (endHint) {
// Same input reference `MatHint#id`, but different instantiation!
// Should not be shared!.
ids.push(endHint.id());
}
}
}
}
@@@@@@ existing_signal_import.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
class ExistingSignalImport {
signalInput = input<boolean>();
readonly thisCanBeMigrated = input(true);
}
@@@@@@ external_templates.html @@@@@@ | {
"end_byte": 8602,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden.txt"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden.txt_8604_16860 | <span>{{test()}}</span>
@@@@@@ external_templates.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
@Component({
templateUrl: './external_templates.html',
selector: 'with-template',
})
export class WithTemplate {
readonly test = input(true);
}
@@@@@@ getters.ts @@@@@@
// tslint:disable
import {Directive, Input} from '@angular/core';
@Directive({})
export class WithGetters {
// TODO: Skipped for migration because:
// Accessor inputs cannot be migrated as they are too complex.
@Input()
get disabled() {
return this._disabled;
}
set disabled(value: boolean | string) {
this._disabled = typeof value === 'string' ? value === '' : !!value;
}
private _disabled: boolean = false;
bla() {
console.log(this._disabled);
}
}
@@@@@@ host_bindings.ts @@@@@@
// tslint:disable
import {Component, Input, HostBinding, input} from '@angular/core';
@Component({
template: '',
host: {
'[id]': 'id()',
'[nested]': 'nested.id()',
'[receiverNarrowing]': 'receiverNarrowing ? receiverNarrowing.id()',
// normal narrowing is irrelevant as we don't type check host bindings.
},
})
class HostBindingTestCmp {
readonly id = input('works');
// for testing nested expressions.
nested = this;
declare receiverNarrowing: this | undefined;
// TODO: Skipped for migration because:
// This input is used in combination with `@HostBinding` and migrating would
// break.
@HostBinding('[attr.bla]')
@Input()
myInput = 'initial';
}
const SHARED = {
'(click)': 'id()',
'(mousedown)': 'id2()',
};
@Component({
template: '',
host: SHARED,
})
class HostBindingsShared {
readonly id = input(false);
}
@Component({
template: '',
host: SHARED,
})
class HostBindingsShared2 {
readonly id = input(false);
readonly id2 = input(false);
}
@@@@@@ identifier_collisions.ts @@@@@@
/**
* @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
*/
// tslint:disable
import {Component, input} from '@angular/core';
const complex = 'some global variable';
@Component({template: ''})
class MyComp {
readonly name = input<string | null>(null);
readonly complex = input<string | null>(null);
valid() {
const name = this.name();
if (name) {
name.charAt(0);
}
}
// Input read cannot be stored in a variable: `name`.
simpleLocalCollision() {
const name = 'some other name';
const nameValue = this.name();
if (nameValue) {
nameValue.charAt(0);
}
}
// `this.complex` should conflict with the file-level `complex` variable,
// and result in a suffix variable.
complexParentCollision() {
const complexValue = this.complex();
if (complexValue) {
complexValue.charAt(0);
}
}
nestedShadowing() {
const nameValue = this.name();
if (nameValue) {
nameValue.charAt(0);
}
function nested() {
const name = '';
}
}
}
@@@@@@ imports.ts @@@@@@
// tslint:disable
// prettier-ignore
import {
Directive,
input
} from '@angular/core';
@Directive()
export class TestCmp {
readonly disabled = input(false);
}
@@@@@@ index.ts @@@@@@
// tslint:disable
import {Component, Input, input} from '@angular/core';
interface Vehicle {}
interface Car extends Vehicle {
__car: true;
}
interface Audi extends Car {
__audi: true;
}
@Component({
selector: 'app-component',
templateUrl: './template.html',
})
export class AppComponent {
readonly input = input<string | null>(null);
readonly bla = input.required<boolean, string | boolean>({ transform: disabledTransform });
readonly narrowableMultipleTimes = input<Vehicle | null>(null);
readonly withUndefinedInput = input<string>();
// TODO: Skipped for migration because:
// Your application code writes to the input. This prevents migration.
@Input() incompatible: string | null = null;
private _bla: any;
// TODO: Skipped for migration because:
// Accessor inputs cannot be migrated as they are too complex.
@Input()
set ngSwitch(newValue: any) {
this._bla = newValue;
if (newValue === 0) {
console.log('test');
}
}
someControlFlowCase() {
const input = this.input();
if (input) {
input.charAt(0);
}
}
moreComplexControlFlowCase() {
const input = this.input();
if (!input) {
return;
}
this.doSomething();
(() => {
// might be a different input value now?!
// No! it can't because we don't allow writes to "input"!!.
console.log(input.substring(0));
})();
}
doSomething() {
this.incompatible = 'some other value';
}
vsd() {
const input = this.input();
const narrowableMultipleTimes = this.narrowableMultipleTimes();
if (!input && narrowableMultipleTimes !== null) {
return narrowableMultipleTimes;
}
return input ? 'eager' : 'lazy';
}
allTheSameNoNarrowing() {
const input = this.input();
console.log(input);
console.log(input);
}
test() {
if (this.narrowableMultipleTimes()) {
console.log();
const x = () => {
// @ts-expect-error
if (isCar(this.narrowableMultipleTimes())) {
}
};
console.log();
console.log();
x();
x();
}
}
extremeNarrowingNested() {
const narrowableMultipleTimes = this.narrowableMultipleTimes();
if (narrowableMultipleTimes && isCar(narrowableMultipleTimes)) {
narrowableMultipleTimes.__car;
let car = narrowableMultipleTimes;
let ctx = this;
function nestedFn() {
if (isAudi(car)) {
console.log(car.__audi);
}
const narrowableMultipleTimesValue = ctx.narrowableMultipleTimes();
if (!isCar(narrowableMultipleTimesValue!) || !isAudi(narrowableMultipleTimesValue)) {
return;
}
narrowableMultipleTimesValue.__audi;
}
// iife
(() => {
if (isAudi(narrowableMultipleTimes)) {
narrowableMultipleTimes.__audi;
}
})();
}
}
}
function disabledTransform(bla: string | boolean): boolean {
return true;
}
function isCar(v: Vehicle): v is Car {
return true;
}
function isAudi(v: Car): v is Audi {
return true;
}
const x: AppComponent = null!;
x.incompatible = null;
@@@@@@ index_access_input.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
@Component({template: ''})
class IndexAccessInput {
readonly items = input<string[]>([]);
bla() {
const {items: itemsInput} = this;
const items = itemsInput();
items[0].charAt(0);
}
}
@@@@@@ index_spec.ts @@@@@@
// tslint:disable
import {NgIf} from '@angular/common';
import {Component, input} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {AppComponent} from '.';
describe('bla', () => {
it('should work', () => {
@Component({
template: `
<app-component #ref />
{{ref.input.ok}}
`,
})
class TestCmp {}
TestBed.configureTestingModule({
imports: [AppComponent],
});
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
});
it('', () => {
it('', () => {
// Define `Ng2Component`
@Component({
selector: 'ng2',
standalone: true,
template: '<div *ngIf="show()"><ng1A></ng1A> | <ng1B></ng1B></div>',
imports: [NgIf],
})
class Ng2Component {
show = input<boolean>(false);
}
});
});
});
@@@@@@ inline_template.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
@Component({
template: `
<div *someTemplateDir [style.ok]="justify()">
</div>
`,
})
export class InlineTmpl {
readonly justify = input<'start' | 'end'>('end');
}
@@@@@@ jit_true_component_external_tmpl.html @@@@@@
{{test()}}
@@@@@@ jit_true_components.ts @@@@@@
/**
* @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
*/
// tslint:disable
import {Component, input} from '@angular/core'; | {
"end_byte": 16860,
"start_byte": 8604,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden.txt"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden.txt_16862_25030 | @Component({
jit: true,
template: '{{test()}}',
})
class JitTrueComponent {
readonly test = input(true);
}
@Component({
jit: true,
templateUrl: './jit_true_component_external_tmpl.html',
})
class JitTrueComponentExternalTmpl {
readonly test = input(true);
}
@@@@@@ loop_labels.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
class MyTestCmp {
readonly someInput = input.required<boolean | string>();
tmpValue = false;
test() {
for (let i = 0, cell = null; i < Number.MIN_SAFE_INTEGER; i++) {
this.tmpValue = !!this.someInput();
this.tmpValue = !this.someInput();
}
}
test2() {
const someInput = this.someInput();
while (isBla(someInput)) {
this.tmpValue = someInput.includes('someText');
}
}
}
function isBla(value: any): value is string {
return true;
}
@@@@@@ manual_instantiations.ts @@@@@@
// tslint:disable
import {ManualInstantiation} from './manual_instantiations_external';
new ManualInstantiation();
@@@@@@ manual_instantiations_external.ts @@@@@@
// tslint:disable
import {Component, Input} from '@angular/core';
@Component({})
export class ManualInstantiation {
// TODO: Skipped for migration because:
// Class of this input is manually instantiated. This is discouraged and prevents
// migration
@Input() bla: string = '';
}
@@@@@@ modifier_tests.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
function CustomDecorator() {
return (a: any, b: any) => {};
}
@Component({template: ''})
class ModifierScenarios {
readonly alreadyReadonly = input(true);
protected readonly ImProtected = input(true);
protected readonly ImProtectedAndReadonly = input(true);
@CustomDecorator()
protected readonly usingCustomDecorator = input(true);
}
@@@@@@ mutate.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
export class TestCmp {
readonly shared = input<{
x: string;
}>({ x: '' });
bla() {
const shared = this.shared();
shared.x = this.doSmth(shared);
this.doSmth(shared);
}
doSmth(v: typeof this.shared()): string {
return v.x;
}
}
@@@@@@ narrowing.ts @@@@@@
// tslint:disable
import {Directive, input} from '@angular/core';
@Directive()
export class Narrowing {
readonly name = input<string>();
narrowingArrowFn() {
[this].map((x) => {
const name = x.name();
return name && name.charAt(0);
});
}
narrowingArrowFnMultiLineWrapped() {
[this].map(
(x) => {
const name = x.name();
return name &&
name.includes(
'A super long string to ensure this is wrapped and we can test formatting.',
);
},
);
}
narrowingObjectExpansion() {
[this].map(({name: nameInput}) => {
const name = nameInput();
return name && name.charAt(0);
});
}
narrowingNormalThenObjectExpansion() {
const name = this.name();
if (name) {
const {charAt} = name;
charAt(0);
}
}
}
@@@@@@ nested_template_prop_access.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
interface Config {
bla?: string;
}
@Component({
template: `
<span [id]="config().bla">
Test
</span>
`,
})
export class NestedTemplatePropAccess {
readonly config = input<Config>({});
}
@@@@@@ non_null_assertions.ts @@@@@@
// tslint:disable
import {Directive, input} from '@angular/core';
@Directive()
export class NonNullAssertions {
// We can't remove `undefined` from the type here. It's unclear
// whether it was just used as a workaround for required inputs, or
// it was actually meant to be part of the type.
readonly name = input.required<string | undefined>();
click() {
this.name()!.charAt(0);
}
}
@@@@@@ object_expansion.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
@Component({})
export class ObjectExpansion {
readonly bla = input<string>('');
expansion() {
const {bla: blaInput} = this;
const bla = blaInput();
bla.charAt(0);
}
deeperExpansion() {
const {
bla,
} = this;
const {charAt} = bla();
charAt(0);
}
expansionAsParameter({bla: blaInput} = this) {
const bla = blaInput();
bla.charAt(0);
}
}
@@@@@@ optimize_test.ts @@@@@@
// tslint:disable
import {AppComponent} from './index';
function assertValidLoadingInput(dir: AppComponent) {
const withUndefinedInput = dir.withUndefinedInput();
if (withUndefinedInput && dir.narrowableMultipleTimes()) {
throw new Error(``);
}
const validInputs = ['auto', 'eager', 'lazy'];
if (typeof withUndefinedInput === 'string' && !validInputs.includes(withUndefinedInput)) {
throw new Error();
}
}
@@@@@@ optional_inputs.ts @@@@@@
// tslint:disable
import {Directive, input} from '@angular/core';
@Directive()
class OptionalInput {
readonly bla = input<string>();
readonly isLegacyHttpOnly = input<boolean | undefined>(false);
}
@@@@@@ problematic_type_reference.ts @@@@@@
// tslint:disable
import {Component, Directive, QueryList, Input} from '@angular/core';
@Component({
template: `
{{label}}
`,
})
class Group {
// TODO: Skipped for migration because:
// Class of this input is referenced in the signature of another class.
@Input() label!: string;
}
@Directive()
class Base {
_items = new QueryList<{
label: string;
}>();
}
@Directive({})
class Option extends Base {
_items = new QueryList<Group>();
}
@@@@@@ required-no-explicit-type-extra.ts @@@@@@
// tslint:disable
import {ComponentMirror} from '@angular/core';
export const COMPLEX_VAR = {
x: null! as ComponentMirror<never>,
};
@@@@@@ required-no-explicit-type.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
import {COMPLEX_VAR} from './required-no-explicit-type-extra';
export const CONST = {field: true};
export class RequiredNoExplicitType {
readonly someInputNumber = input.required<number>();
readonly someInput = input.required<boolean>();
readonly withConstInitialVal = input.required<typeof CONST>();
// typing this explicitly now would require same imports as from the `-extra` file.
readonly complexVal = input.required<typeof COMPLEX_VAR>();
}
@@@@@@ required.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
class Required {
readonly simpleInput = input.required<string>();
}
@@@@@@ safe_property_reads.ts @@@@@@
/**
* @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
*/
// tslint:disable
import {Component, input} from '@angular/core';
@Component({
template: `
{{bla?.myInput()}}
`,
})
class WithSafePropertyReads {
readonly myInput = input(0);
bla: this | undefined = this;
}
@@@@@@ scope_sharing.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
export class TestCmp {
readonly shared = input(false);
bla() {
const shared = this.shared();
if (TestCmp.arguments) {
this.someFn(shared);
} else {
shared.valueOf();
}
this.someFn(shared);
}
someFn(bla: boolean): asserts bla is true {}
}
@@@@@@ shared_incompatible_scopes.ts @@@@@@
// tslint:disable
import {Directive, Component, input} from '@angular/core';
@Directive()
class SomeDir {
readonly bla = input.required<RegExp>();
}
@Component({
template: ``,
})
export class ScopeMismatchTest {
eachScopeRedeclared() {
const regexs: RegExp[] = [];
if (global.console) {
const dir: SomeDir = null!;
regexs.push(dir.bla());
}
const dir: SomeDir = null!;
regexs.push(dir.bla());
}
nestedButSharedLocal() {
const regexs: RegExp[] = [];
const dir: SomeDir = null!;
const bla = dir.bla();
if (global.console) {
regexs.push(bla);
}
regexs.push(bla);
}
dir: SomeDir = null!;
nestedButSharedInClassInstance() {
const regexs: RegExp[] = [];
const bla = this.dir.bla();
if (global.console) {
regexs.push(bla);
}
regexs.push(bla);
}
}
@@@@@@ spy_on.ts @@@@@@
// tslint:disable
import {Input} from '@angular/core'; | {
"end_byte": 25030,
"start_byte": 16862,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden.txt"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden.txt_25032_32997 | class MyComp {
// TODO: Skipped for migration because:
// A jasmine `spyOn` call spies on this field. This breaks with signals.
@Input() myInput = () => {};
}
spyOn<MyComp>(new MyComp(), 'myInput').and.returnValue();
@@@@@@ template.html @@@@@@
<span class="mat-mdc-optgroup-label" role="presentation">
<span class="mdc-list-item__primary-text">{{ input() }} <ng-content></ng-content></span>
</span>
<ng-content select="mat-option, ng-container"></ng-content>
@@@@@@ template_concat_string.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
@Component({
template: '<h3>' + '{{bla}}' + '</h3>',
})
export class WithConcatTemplate {
readonly bla = input(true);
}
@@@@@@ template_ng_if.ts @@@@@@
// tslint:disable
import {Component, Input, input} from '@angular/core';
@Component({
template: `
@if (first) {
{{first}}
}
<ng-template [ngIf]="second">
{{second}}
</ng-template>
<div *ngIf="third">
{{third}}
</div>
<div *ngIf="fourth()">
{{notTheInput}}
</div>
@if (fifth()) {
{{notTheInput}}
}
`,
})
export class MyComp {
// TODO: Skipped for migration because:
// This input is used in a control flow expression (e.g. `@if` or `*ngIf`)
// and migrating would break narrowing currently.
@Input() first = true;
// TODO: Skipped for migration because:
// This input is used in a control flow expression (e.g. `@if` or `*ngIf`)
// and migrating would break narrowing currently.
@Input() second = false;
// TODO: Skipped for migration because:
// This input is used in a control flow expression (e.g. `@if` or `*ngIf`)
// and migrating would break narrowing currently.
@Input() third = true;
readonly fourth = input(true);
readonly fifth = input(true);
}
@@@@@@ template_object_shorthand.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
@Component({
template: `
<div [bla]="{myInput: myInput()}">
</div>
`,
host: {
'[style]': '{myInput: myInput()}',
},
})
export class TemplateObjectShorthand {
readonly myInput = input(true);
}
@@@@@@ template_writes.ts @@@@@@
// tslint:disable
import {Component, Input, input} from '@angular/core';
@Component({
template: `
<input [(ngModel)]="inputA" />
<div (click)="inputB = false">
</div>
`,
host: {
'(click)': 'inputC = true',
},
})
class TwoWayBinding {
// TODO: Skipped for migration because:
// Your application code writes to the input. This prevents migration.
@Input() inputA = '';
// TODO: Skipped for migration because:
// Your application code writes to the input. This prevents migration.
@Input() inputB = true;
// TODO: Skipped for migration because:
// Your application code writes to the input. This prevents migration.
@Input() inputC = false;
readonly inputD = input(false);
}
@@@@@@ temporary_variables.ts @@@@@@
// tslint:disable
import {Directive, input} from '@angular/core';
export class OtherCmp {
readonly name = input(false);
}
@Directive()
export class MyComp {
readonly name = input('');
other: OtherCmp = null!;
click() {
const name = this.name();
if (name) {
console.error(name);
}
const nameValue = this.other.name();
if (nameValue) {
console.error(nameValue);
}
}
}
@@@@@@ ternary_narrowing.ts @@@@@@
// tslint:disable
import {Component, Input, input} from '@angular/core';
@Component({
template: `
{{ narrowed ? narrowed.substring(0, 1) : 'Empty' }}
{{ justChecked() ? 'true' : 'false' }}
{{ other?.safeRead ? other.safeRead : 'Empty' }}
{{ other?.safeRead2 ? other?.safeRead2 : 'Empty' }}
`,
})
export class TernaryNarrowing {
// TODO: Skipped for migration because:
// This input is used in a control flow expression (e.g. `@if` or `*ngIf`)
// and migrating would break narrowing currently.
@Input() narrowed: string | undefined = undefined;
readonly justChecked = input(true);
other?: OtherComponent;
}
@Component({template: ''})
export class OtherComponent {
// TODO: Skipped for migration because:
// This input is used in a control flow expression (e.g. `@if` or `*ngIf`)
// and migrating would break narrowing currently.
@Input() safeRead: string = '';
// TODO: Skipped for migration because:
// This input is used in a control flow expression (e.g. `@if` or `*ngIf`)
// and migrating would break narrowing currently.
@Input() safeRead2: string = '';
}
@@@@@@ transform_functions.ts @@@@@@
// tslint:disable
import {Input, input} from '@angular/core';
import {COMPLEX_VAR} from './required-no-explicit-type-extra';
function x(v: string | undefined): string | undefined {
return v;
}
export class TransformFunctions {
// We can check this, and expect `as any` due to transform incompatibility.
// TODO: Notes from signal input migration:
// Input type is incompatible with transform. The migration added an `any`
// cast. This worked previously because Angular was unable to check transforms.
readonly withExplicitTypeWorks = input.required<{
ok: true;
}, string | undefined>({ transform: ((v: string | undefined) => '') as any });
// This will be a synthetic type because we add `undefined` to `boolean`.
readonly synthetic1 = input.required<boolean | undefined, string | undefined>({ transform: x });
// Synthetic as we infer a full type from the initial value. Cannot be checked.
// TODO: Skipped for migration because:
// Input is required, but the migration cannot determine a good type for the
// input.
@Input({required: true, transform: (v: string | undefined) => ''}) synthetic2 = {
infer: COMPLEX_VAR,
};
}
@@@@@@ transform_incompatible_types.ts @@@@@@
// tslint:disable
import {Directive, input} from '@angular/core';
// see: button-base Material.
@Directive()
class TransformIncompatibleTypes {
// @ts-ignore Simulate `--strictPropertyInitialization=false`.
// TODO: Notes from signal input migration:
// Input type is incompatible with transform. The migration added an `any`
// cast. This worked previously because Angular was unable to check transforms.
readonly disabled = input<boolean, unknown>(undefined, { transform: ((v: unknown) => (v === null ? undefined : !!v)) as any });
}
@@@@@@ with_getters.ts @@@@@@
// tslint:disable
import {Input, input} from '@angular/core';
export class WithSettersAndGetters {
// TODO: Skipped for migration because:
// Accessor inputs cannot be migrated as they are too complex.
@Input()
set onlySetter(newValue: any) {
this._bla = newValue;
if (newValue === 0) {
console.log('test');
}
}
private _bla: any;
// TODO: Skipped for migration because:
// Accessor inputs cannot be migrated as they are too complex.
@Input()
get accessor(): string {
return '';
}
set accessor(newValue: string) {
this._accessor = newValue;
}
private _accessor: string = '';
readonly simpleInput = input.required<string>();
}
@@@@@@ with_getters_reference.ts @@@@@@
// tslint:disable
import {WithSettersAndGetters} from './with_getters';
class WithGettersExternalRef {
instance: WithSettersAndGetters = null!;
test() {
if (this.instance.accessor) {
console.log(this.instance.accessor);
}
}
}
@@@@@@ with_jsdoc.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
class WithJsdoc {
/**
* Works
*/
readonly simpleInput = input.required<string>();
readonly withCommentInside = input</* intended */ boolean>();
}
@@@@@@ writing_to_inputs.ts @@@@@@
// tslint:disable
import {Input, input} from '@angular/core';
export class TestCmp {
// TODO: Skipped for migration because:
// Your application code writes to the input. This prevents migration.
@Input() testParenthesisInput = false;
readonly notMutated = input(true);
testParenthesis() {
// prettier-ignore
((this.testParenthesisInput)) = true;
} | {
"end_byte": 32997,
"start_byte": 25032,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden.txt"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden.txt_32999_33085 | testNotMutated() {
let fixture: boolean;
fixture = this.notMutated();
}
}
| {
"end_byte": 33085,
"start_byte": 32999,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden.txt"
} |
angular/packages/core/schematics/migrations/signal-migration/test/migration_spec.ts_0_3270 | /**
* @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 {absoluteFrom} from '@angular/compiler-cli/src/ngtsc/file_system';
import {initMockFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {runTsurgeMigration} from '../../../utils/tsurge/testing';
import {SignalInputMigration} from '../src/migration';
import {setupTsurgeJasmineHelpers} from '../../../utils/tsurge/testing/jasmine';
describe('signal input migration', () => {
beforeEach(() => {
setupTsurgeJasmineHelpers();
initMockFileSystem('Native');
});
it(
'should properly handle declarations with loose property initialization ' +
'and strict null checks enabled',
async () => {
const {fs} = await runTsurgeMigration(
new SignalInputMigration(),
[
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: `
import {Component, Input} from '@angular/core';
@Component({template: ''})
class AppComponent {
@Input() name: string;
doSmth() {
this.name.charAt(0);
}
}
`,
},
],
{
strict: false,
strictNullChecks: true,
},
);
expect(fs.readFile(absoluteFrom('/app.component.ts'))).toMatchWithDiff(`
import {Component, input} from '@angular/core';
@Component({template: ''})
class AppComponent {
// TODO: Notes from signal input migration:
// Input is initialized to \`undefined\` but type does not allow this value.
// This worked with \`@Input\` because your project uses \`--strictPropertyInitialization=false\`.
readonly name = input<string>(undefined!);
doSmth() {
this.name().charAt(0);
}
}
`);
},
);
it(
'should properly handle declarations with loose property initialization ' +
'and strict null checks disabled',
async () => {
const {fs} = await runTsurgeMigration(
new SignalInputMigration(),
[
{
name: absoluteFrom('/app.component.ts'),
isProgramRootFile: true,
contents: `
import {Component, Input} from '@angular/core';
@Component({template: ''})
class AppComponent {
@Input() name: string;
doSmth() {
this.name.charAt(0);
}
}
`,
},
],
{
strict: false,
},
);
expect(fs.readFile(absoluteFrom('/app.component.ts'))).toContain(
// Shorthand not used here to keep behavior unchanged, and to not
// risk expanding the type. In practice `string|undefined` would be
// fine though as long as the consumers also have strict null checks disabled.
'readonly name = input<string>(undefined);',
);
expect(fs.readFile(absoluteFrom('/app.component.ts'))).toContain('this.name().charAt(0);');
},
);
});
| {
"end_byte": 3270,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/migration_spec.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden_best_effort.txt_0_8598 | @@@@@@ any_test.ts @@@@@@
// tslint:disable
import {DebugElement, input} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
function it(msg: string, fn: () => void) {}
const harness = {
query<T>(v: T): DebugElement {
return null!;
},
};
class SubDir {
readonly name = input('John');
readonly name2 = input('');
}
class MyComp {
readonly hello = input('');
}
it('should work', () => {
const fixture = TestBed.createComponent(MyComp);
// `.componentInstance` is using `any` :O
const sub = fixture.debugElement.query(By.directive(SubDir)).componentInstance;
expect(sub.name()).toBe('John');
});
it('should work2', () => {
const fixture = TestBed.createComponent(MyComp);
// `.componentInstance` is using `any` :O
const sub = harness.query(SubDir).componentInstance;
expect(sub.name2()).toBe('John');
});
@@@@@@ base_class.ts @@@@@@
// tslint:disable
import {Directive, input} from '@angular/core';
class BaseNonAngular {
disabled: string = '';
}
@Directive()
class Sub implements BaseNonAngular {
// should not be migrated because of the interface.
readonly disabled = input('');
}
class BaseWithAngular {
readonly disabled = input<string>('');
}
@Directive()
class Sub2 extends BaseWithAngular {
readonly disabled = input('');
}
interface BaseNonAngularInterface {
disabled: string;
}
@Directive()
class Sub3 implements BaseNonAngularInterface {
// should not be migrated because of the interface.
readonly disabled = input('');
}
@@@@@@ both_input_imports.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
class BothInputImported {
readonly decoratorInput = input(true);
signalInput = input<boolean>();
readonly thisCanBeMigrated = input(true);
__makeDecoratorInputNonMigratable() {
this.decoratorInput = false;
}
}
@@@@@@ catalyst_async_test.ts @@@@@@
import { UnwrapSignalInputs } from "google3/javascript/angular2/testing/catalyst/async";
// tslint:disable
import {input} from '@angular/core';
// google3/javascript/angular2/testing/catalyst/async
// ^^ this allows the advisor to even consider this file.
function it(msg: string, fn: () => void) {}
function bootstrapTemplate(tmpl: string, inputs: unknown) {}
class MyComp {
readonly hello = input('');
}
it('should work', () => {
const inputs = {
hello: 'test',
} as Partial<UnwrapSignalInputs<MyComp>>;
bootstrapTemplate('<my-comp [hello]="hello">', inputs);
});
@@@@@@ catalyst_test.ts @@@@@@
import { UnwrapSignalInputs } from "google3/javascript/angular2/testing/catalyst/fake_async";
// tslint:disable
import {input} from '@angular/core';
// google3/javascript/angular2/testing/catalyst/fake_async
// ^^ this allows the advisor to even consider this file.
function it(msg: string, fn: () => void) {}
function bootstrapTemplate(tmpl: string, inputs: unknown) {}
class MyComp {
readonly hello = input('');
}
it('should work', () => {
const inputs = {
hello: 'test',
} as Partial<UnwrapSignalInputs<MyComp>>;
bootstrapTemplate('<my-comp [hello]="hello">', inputs);
});
@@@@@@ catalyst_test_partial.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
// @ts-ignore
import {UnwrapSignalInputs} from 'google3/javascript/angular2/testing/catalyst/fake_async';
function renderComponent(inputs: Partial<UnwrapSignalInputs<TestableSecondaryRangePicker>> = {}) {}
@Component({
standalone: false,
jit: true,
template: '<bla [(ngModel)]="incompatible()">',
})
class TestableSecondaryRangePicker {
readonly bla = input(true);
readonly incompatible = input(true);
}
@@@@@@ constructor_initializations.ts @@@@@@
// tslint:disable
import {Directive, input} from '@angular/core';
@Directive()
export class MyComp {
readonly firstName = input<string>();
constructor() {
// TODO: Consider initializations inside the constructor.
// Those are not migrated right now though, as they are writes.
this.firstName = 'Initial value';
}
}
@@@@@@ cross_references.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
@Component({
template: `
{{label()}}
`,
})
class Group {
readonly label = input.required<string>();
}
@Component({
template: `
@if (true) {
{{group.label()}}
}
{{group.label()}}
`,
})
class Option {
constructor(public group: Group) {}
}
@@@@@@ derived_class.ts @@@@@@
// tslint:disable
import {Directive, input} from '@angular/core';
@Directive()
class Base {
readonly bla = input(true);
}
class Derived extends Base {
override bla = false;
}
// overridden in separate file
@Directive()
export class Base2 {
readonly bla = input(true);
}
// overridden in separate file
@Directive()
export class Base3 {
readonly bla = input(true);
click() {
this.bla = false;
}
}
@@@@@@ derived_class_meta_input_alias.ts @@@@@@
// tslint:disable
import {Directive, input} from '@angular/core';
@Directive()
class Base {
// should not be migrated.
readonly bla = input(true);
}
@Directive({
inputs: [{name: 'bla', alias: 'matDerivedBla'}],
})
class Derived extends Base {}
@@@@@@ derived_class_second_separate.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
import {DerivedExternalWithInput} from './derived_class_separate_file';
class Derived extends DerivedExternalWithInput {
// this should be incompatible, because the final superclass
// within its own batch unit, detected a write that should
// propagate to this input.
override readonly bla = input(false);
}
@@@@@@ derived_class_separate_file.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
import {Base2, Base3} from './derived_class';
class DerivedExternal extends Base2 {
override bla = false;
}
export class DerivedExternalWithInput extends Base3 {
override readonly bla = input(true);
}
@@@@@@ different_instantiations_of_reference.ts @@@@@@
// tslint:disable
import {Directive, Component, input} from '@angular/core';
// Material form field test case
let nextUniqueId = 0;
@Directive()
export class MatHint {
align: string = '';
readonly id = input(`mat-hint-${nextUniqueId++}`);
}
@Component({
template: ``,
})
export class MatFormFieldTest {
private declare _hintChildren: MatHint[];
private _control = true;
private _somethingElse = false;
private _syncDescribedByIds() {
if (this._control) {
let ids: string[] = [];
const startHint = this._hintChildren
? this._hintChildren.find((hint) => hint.align === 'start')
: null;
const endHint = this._hintChildren
? this._hintChildren.find((hint) => hint.align === 'end')
: null;
if (startHint) {
ids.push(startHint.id());
} else if (this._somethingElse) {
ids.push(`val:${this._somethingElse}`);
}
if (endHint) {
// Same input reference `MatHint#id`, but different instantiation!
// Should not be shared!.
ids.push(endHint.id());
}
}
}
}
@@@@@@ existing_signal_import.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
class ExistingSignalImport {
signalInput = input<boolean>();
readonly thisCanBeMigrated = input(true);
}
@@@@@@ external_templates.html @@@@@@
<span>{{test()}}</span>
@@@@@@ external_templates.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
@Component({
templateUrl: './external_templates.html',
selector: 'with-template',
})
export class WithTemplate {
readonly test = input(true);
}
@@@@@@ getters.ts @@@@@@
// tslint:disable
import {Directive, Input} from '@angular/core';
@Directive({})
export class WithGetters {
// TODO: Skipped for migration because:
// Accessor inputs cannot be migrated as they are too complex.
@Input()
get disabled() {
return this._disabled;
}
set disabled(value: boolean | string) {
this._disabled = typeof value === 'string' ? value === '' : !!value;
}
private _disabled: boolean = false;
bla() {
console.log(this._disabled);
}
}
@@@@@@ host_bindings.ts @@@@@@
// tslint:disable
import {Component, HostBinding, input} from '@angular/core';
@Component({
template: '',
host: {
'[id]': 'id()',
'[nested]': 'nested.id()',
'[receiverNarrowing]': 'receiverNarrowing ? receiverNarrowing.id()',
// normal narrowing is irrelevant as we don't type check host bindings.
},
})
class HostBindingTestCmp {
readonly id = input('works');
// for testing nested expressions.
nested = this;
declare receiverNarrowing: this | undefined; | {
"end_byte": 8598,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden_best_effort.txt"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden_best_effort.txt_8600_16665 | @HostBinding('[attr.bla]')
readonly myInput = input('initial');
}
const SHARED = {
'(click)': 'id()',
'(mousedown)': 'id2()',
};
@Component({
template: '',
host: SHARED,
})
class HostBindingsShared {
readonly id = input(false);
}
@Component({
template: '',
host: SHARED,
})
class HostBindingsShared2 {
readonly id = input(false);
readonly id2 = input(false);
}
@@@@@@ identifier_collisions.ts @@@@@@
/**
* @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
*/
// tslint:disable
import {Component, input} from '@angular/core';
const complex = 'some global variable';
@Component({template: ''})
class MyComp {
readonly name = input<string | null>(null);
readonly complex = input<string | null>(null);
valid() {
const name = this.name();
if (name) {
name.charAt(0);
}
}
// Input read cannot be stored in a variable: `name`.
simpleLocalCollision() {
const name = 'some other name';
const nameValue = this.name();
if (nameValue) {
nameValue.charAt(0);
}
}
// `this.complex` should conflict with the file-level `complex` variable,
// and result in a suffix variable.
complexParentCollision() {
const complexValue = this.complex();
if (complexValue) {
complexValue.charAt(0);
}
}
nestedShadowing() {
const nameValue = this.name();
if (nameValue) {
nameValue.charAt(0);
}
function nested() {
const name = '';
}
}
}
@@@@@@ imports.ts @@@@@@
// tslint:disable
// prettier-ignore
import {
Directive,
input
} from '@angular/core';
@Directive()
export class TestCmp {
readonly disabled = input(false);
}
@@@@@@ index.ts @@@@@@
// tslint:disable
import {Component, Input, input} from '@angular/core';
interface Vehicle {}
interface Car extends Vehicle {
__car: true;
}
interface Audi extends Car {
__audi: true;
}
@Component({
selector: 'app-component',
templateUrl: './template.html',
})
export class AppComponent {
readonly input = input<string | null>(null);
readonly bla = input.required<boolean, string | boolean>({ transform: disabledTransform });
readonly narrowableMultipleTimes = input<Vehicle | null>(null);
readonly withUndefinedInput = input<string>();
readonly incompatible = input<string | null>(null);
private _bla: any;
// TODO: Skipped for migration because:
// Accessor inputs cannot be migrated as they are too complex.
@Input()
set ngSwitch(newValue: any) {
this._bla = newValue;
if (newValue === 0) {
console.log('test');
}
}
someControlFlowCase() {
const input = this.input();
if (input) {
input.charAt(0);
}
}
moreComplexControlFlowCase() {
const input = this.input();
if (!input) {
return;
}
this.doSomething();
(() => {
// might be a different input value now?!
// No! it can't because we don't allow writes to "input"!!.
console.log(input.substring(0));
})();
}
doSomething() {
this.incompatible = 'some other value';
}
vsd() {
const input = this.input();
const narrowableMultipleTimes = this.narrowableMultipleTimes();
if (!input && narrowableMultipleTimes !== null) {
return narrowableMultipleTimes;
}
return input ? 'eager' : 'lazy';
}
allTheSameNoNarrowing() {
const input = this.input();
console.log(input);
console.log(input);
}
test() {
if (this.narrowableMultipleTimes()) {
console.log();
const x = () => {
// @ts-expect-error
if (isCar(this.narrowableMultipleTimes())) {
}
};
console.log();
console.log();
x();
x();
}
}
extremeNarrowingNested() {
const narrowableMultipleTimes = this.narrowableMultipleTimes();
if (narrowableMultipleTimes && isCar(narrowableMultipleTimes)) {
narrowableMultipleTimes.__car;
let car = narrowableMultipleTimes;
let ctx = this;
function nestedFn() {
if (isAudi(car)) {
console.log(car.__audi);
}
const narrowableMultipleTimesValue = ctx.narrowableMultipleTimes();
if (!isCar(narrowableMultipleTimesValue!) || !isAudi(narrowableMultipleTimesValue)) {
return;
}
narrowableMultipleTimesValue.__audi;
}
// iife
(() => {
if (isAudi(narrowableMultipleTimes)) {
narrowableMultipleTimes.__audi;
}
})();
}
}
}
function disabledTransform(bla: string | boolean): boolean {
return true;
}
function isCar(v: Vehicle): v is Car {
return true;
}
function isAudi(v: Car): v is Audi {
return true;
}
const x: AppComponent = null!;
x.incompatible = null;
@@@@@@ index_access_input.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
@Component({template: ''})
class IndexAccessInput {
readonly items = input<string[]>([]);
bla() {
const {items: itemsInput} = this;
const items = itemsInput();
items[0].charAt(0);
}
}
@@@@@@ index_spec.ts @@@@@@
// tslint:disable
import {NgIf} from '@angular/common';
import {Component, input} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {AppComponent} from '.';
describe('bla', () => {
it('should work', () => {
@Component({
template: `
<app-component #ref />
{{ref.input.ok}}
`,
})
class TestCmp {}
TestBed.configureTestingModule({
imports: [AppComponent],
});
const fixture = TestBed.createComponent(TestCmp);
fixture.detectChanges();
});
it('', () => {
it('', () => {
// Define `Ng2Component`
@Component({
selector: 'ng2',
standalone: true,
template: '<div *ngIf="show()"><ng1A></ng1A> | <ng1B></ng1B></div>',
imports: [NgIf],
})
class Ng2Component {
show = input<boolean>(false);
}
});
});
});
@@@@@@ inline_template.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
@Component({
template: `
<div *someTemplateDir [style.ok]="justify()">
</div>
`,
})
export class InlineTmpl {
readonly justify = input<'start' | 'end'>('end');
}
@@@@@@ jit_true_component_external_tmpl.html @@@@@@
{{test()}}
@@@@@@ jit_true_components.ts @@@@@@
/**
* @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
*/
// tslint:disable
import {Component, input} from '@angular/core';
@Component({
jit: true,
template: '{{test()}}',
})
class JitTrueComponent {
readonly test = input(true);
}
@Component({
jit: true,
templateUrl: './jit_true_component_external_tmpl.html',
})
class JitTrueComponentExternalTmpl {
readonly test = input(true);
}
@@@@@@ loop_labels.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
class MyTestCmp {
readonly someInput = input.required<boolean | string>();
tmpValue = false;
test() {
for (let i = 0, cell = null; i < Number.MIN_SAFE_INTEGER; i++) {
this.tmpValue = !!this.someInput();
this.tmpValue = !this.someInput();
}
}
test2() {
const someInput = this.someInput();
while (isBla(someInput)) {
this.tmpValue = someInput.includes('someText');
}
}
}
function isBla(value: any): value is string {
return true;
}
@@@@@@ manual_instantiations.ts @@@@@@
// tslint:disable
import {ManualInstantiation} from './manual_instantiations_external';
new ManualInstantiation();
@@@@@@ manual_instantiations_external.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
@Component({})
export class ManualInstantiation {
readonly bla = input<string>('');
}
@@@@@@ modifier_tests.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
function CustomDecorator() {
return (a: any, b: any) => {};
} | {
"end_byte": 16665,
"start_byte": 8600,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden_best_effort.txt"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden_best_effort.txt_16667_24861 | @Component({template: ''})
class ModifierScenarios {
readonly alreadyReadonly = input(true);
protected readonly ImProtected = input(true);
protected readonly ImProtectedAndReadonly = input(true);
@CustomDecorator()
protected readonly usingCustomDecorator = input(true);
}
@@@@@@ mutate.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
export class TestCmp {
readonly shared = input<{
x: string;
}>({ x: '' });
bla() {
const shared = this.shared();
shared.x = this.doSmth(shared);
this.doSmth(shared);
}
doSmth(v: typeof this.shared()): string {
return v.x;
}
}
@@@@@@ narrowing.ts @@@@@@
// tslint:disable
import {Directive, input} from '@angular/core';
@Directive()
export class Narrowing {
readonly name = input<string>();
narrowingArrowFn() {
[this].map((x) => {
const name = x.name();
return name && name.charAt(0);
});
}
narrowingArrowFnMultiLineWrapped() {
[this].map(
(x) => {
const name = x.name();
return name &&
name.includes(
'A super long string to ensure this is wrapped and we can test formatting.',
);
},
);
}
narrowingObjectExpansion() {
[this].map(({name: nameInput}) => {
const name = nameInput();
return name && name.charAt(0);
});
}
narrowingNormalThenObjectExpansion() {
const name = this.name();
if (name) {
const {charAt} = name;
charAt(0);
}
}
}
@@@@@@ nested_template_prop_access.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
interface Config {
bla?: string;
}
@Component({
template: `
<span [id]="config().bla">
Test
</span>
`,
})
export class NestedTemplatePropAccess {
readonly config = input<Config>({});
}
@@@@@@ non_null_assertions.ts @@@@@@
// tslint:disable
import {Directive, input} from '@angular/core';
@Directive()
export class NonNullAssertions {
// We can't remove `undefined` from the type here. It's unclear
// whether it was just used as a workaround for required inputs, or
// it was actually meant to be part of the type.
readonly name = input.required<string | undefined>();
click() {
this.name()!.charAt(0);
}
}
@@@@@@ object_expansion.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
@Component({})
export class ObjectExpansion {
readonly bla = input<string>('');
expansion() {
const {bla: blaInput} = this;
const bla = blaInput();
bla.charAt(0);
}
deeperExpansion() {
const {
bla,
} = this;
const {charAt} = bla();
charAt(0);
}
expansionAsParameter({bla: blaInput} = this) {
const bla = blaInput();
bla.charAt(0);
}
}
@@@@@@ optimize_test.ts @@@@@@
// tslint:disable
import {AppComponent} from './index';
function assertValidLoadingInput(dir: AppComponent) {
const withUndefinedInput = dir.withUndefinedInput();
if (withUndefinedInput && dir.narrowableMultipleTimes()) {
throw new Error(``);
}
const validInputs = ['auto', 'eager', 'lazy'];
if (typeof withUndefinedInput === 'string' && !validInputs.includes(withUndefinedInput)) {
throw new Error();
}
}
@@@@@@ optional_inputs.ts @@@@@@
// tslint:disable
import {Directive, input} from '@angular/core';
@Directive()
class OptionalInput {
readonly bla = input<string>();
readonly isLegacyHttpOnly = input<boolean | undefined>(false);
}
@@@@@@ problematic_type_reference.ts @@@@@@
// tslint:disable
import {Component, Directive, QueryList, input} from '@angular/core';
@Component({
template: `
{{label()}}
`,
})
class Group {
readonly label = input.required<string>();
}
@Directive()
class Base {
_items = new QueryList<{
label: string;
}>();
}
@Directive({})
class Option extends Base {
_items = new QueryList<Group>();
}
@@@@@@ required-no-explicit-type-extra.ts @@@@@@
// tslint:disable
import {ComponentMirror} from '@angular/core';
export const COMPLEX_VAR = {
x: null! as ComponentMirror<never>,
};
@@@@@@ required-no-explicit-type.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
import {COMPLEX_VAR} from './required-no-explicit-type-extra';
export const CONST = {field: true};
export class RequiredNoExplicitType {
readonly someInputNumber = input.required<number>();
readonly someInput = input.required<boolean>();
readonly withConstInitialVal = input.required<typeof CONST>();
// typing this explicitly now would require same imports as from the `-extra` file.
readonly complexVal = input.required<typeof COMPLEX_VAR>();
}
@@@@@@ required.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
class Required {
readonly simpleInput = input.required<string>();
}
@@@@@@ safe_property_reads.ts @@@@@@
/**
* @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
*/
// tslint:disable
import {Component, input} from '@angular/core';
@Component({
template: `
{{bla?.myInput()}}
`,
})
class WithSafePropertyReads {
readonly myInput = input(0);
bla: this | undefined = this;
}
@@@@@@ scope_sharing.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
export class TestCmp {
readonly shared = input(false);
bla() {
const shared = this.shared();
if (TestCmp.arguments) {
this.someFn(shared);
} else {
shared.valueOf();
}
this.someFn(shared);
}
someFn(bla: boolean): asserts bla is true {}
}
@@@@@@ shared_incompatible_scopes.ts @@@@@@
// tslint:disable
import {Directive, Component, input} from '@angular/core';
@Directive()
class SomeDir {
readonly bla = input.required<RegExp>();
}
@Component({
template: ``,
})
export class ScopeMismatchTest {
eachScopeRedeclared() {
const regexs: RegExp[] = [];
if (global.console) {
const dir: SomeDir = null!;
regexs.push(dir.bla());
}
const dir: SomeDir = null!;
regexs.push(dir.bla());
}
nestedButSharedLocal() {
const regexs: RegExp[] = [];
const dir: SomeDir = null!;
const bla = dir.bla();
if (global.console) {
regexs.push(bla);
}
regexs.push(bla);
}
dir: SomeDir = null!;
nestedButSharedInClassInstance() {
const regexs: RegExp[] = [];
const bla = this.dir.bla();
if (global.console) {
regexs.push(bla);
}
regexs.push(bla);
}
}
@@@@@@ spy_on.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
class MyComp {
readonly myInput = input(() => { });
}
spyOn<MyComp>(new MyComp(), 'myInput').and.returnValue();
@@@@@@ template.html @@@@@@
<span class="mat-mdc-optgroup-label" role="presentation">
<span class="mdc-list-item__primary-text">{{ input() }} <ng-content></ng-content></span>
</span>
<ng-content select="mat-option, ng-container"></ng-content>
@@@@@@ template_concat_string.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
@Component({
template: '<h3>' + '{{bla}}' + '</h3>',
})
export class WithConcatTemplate {
readonly bla = input(true);
}
@@@@@@ template_ng_if.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
@Component({
template: `
@if (first()) {
{{first()}}
}
<ng-template [ngIf]="second()">
{{second()}}
</ng-template>
<div *ngIf="third()">
{{third()}}
</div>
<div *ngIf="fourth()">
{{notTheInput}}
</div>
@if (fifth()) {
{{notTheInput}}
}
`,
})
export class MyComp {
readonly first = input(true);
readonly second = input(false);
readonly third = input(true);
readonly fourth = input(true);
readonly fifth = input(true);
}
@@@@@@ template_object_shorthand.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
@Component({
template: `
<div [bla]="{myInput: myInput()}">
</div>
`,
host: {
'[style]': '{myInput: myInput()}',
},
})
export class TemplateObjectShorthand {
readonly myInput = input(true);
}
@@@@@@ template_writes.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core'; | {
"end_byte": 24861,
"start_byte": 16667,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden_best_effort.txt"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden_best_effort.txt_24863_29724 | @Component({
template: `
<input [(ngModel)]="inputA()" />
<div (click)="inputB = false()">
</div>
`,
host: {
'(click)': 'inputC = true()',
},
})
class TwoWayBinding {
readonly inputA = input('');
readonly inputB = input(true);
readonly inputC = input(false);
readonly inputD = input(false);
}
@@@@@@ temporary_variables.ts @@@@@@
// tslint:disable
import {Directive, input} from '@angular/core';
export class OtherCmp {
readonly name = input(false);
}
@Directive()
export class MyComp {
readonly name = input('');
other: OtherCmp = null!;
click() {
const name = this.name();
if (name) {
console.error(name);
}
const nameValue = this.other.name();
if (nameValue) {
console.error(nameValue);
}
}
}
@@@@@@ ternary_narrowing.ts @@@@@@
// tslint:disable
import {Component, input} from '@angular/core';
@Component({
template: `
{{ narrowed() ? narrowed().substring(0, 1) : 'Empty' }}
{{ justChecked() ? 'true' : 'false' }}
{{ other?.safeRead() ? other.safeRead() : 'Empty' }}
{{ other?.safeRead2() ? other?.safeRead2() : 'Empty' }}
`,
})
export class TernaryNarrowing {
readonly narrowed = input<string>();
readonly justChecked = input(true);
other?: OtherComponent;
}
@Component({template: ''})
export class OtherComponent {
readonly safeRead = input<string>('');
readonly safeRead2 = input<string>('');
}
@@@@@@ transform_functions.ts @@@@@@
// tslint:disable
import {Input, input} from '@angular/core';
import {COMPLEX_VAR} from './required-no-explicit-type-extra';
function x(v: string | undefined): string | undefined {
return v;
}
export class TransformFunctions {
// We can check this, and expect `as any` due to transform incompatibility.
// TODO: Notes from signal input migration:
// Input type is incompatible with transform. The migration added an `any`
// cast. This worked previously because Angular was unable to check transforms.
readonly withExplicitTypeWorks = input.required<{
ok: true;
}, string | undefined>({ transform: ((v: string | undefined) => '') as any });
// This will be a synthetic type because we add `undefined` to `boolean`.
readonly synthetic1 = input.required<boolean | undefined, string | undefined>({ transform: x });
// Synthetic as we infer a full type from the initial value. Cannot be checked.
// TODO: Skipped for migration because:
// Input is required, but the migration cannot determine a good type for the
// input.
@Input({required: true, transform: (v: string | undefined) => ''}) synthetic2 = {
infer: COMPLEX_VAR,
};
}
@@@@@@ transform_incompatible_types.ts @@@@@@
// tslint:disable
import {Directive, input} from '@angular/core';
// see: button-base Material.
@Directive()
class TransformIncompatibleTypes {
// @ts-ignore Simulate `--strictPropertyInitialization=false`.
// TODO: Notes from signal input migration:
// Input type is incompatible with transform. The migration added an `any`
// cast. This worked previously because Angular was unable to check transforms.
readonly disabled = input<boolean, unknown>(undefined, { transform: ((v: unknown) => (v === null ? undefined : !!v)) as any });
}
@@@@@@ with_getters.ts @@@@@@
// tslint:disable
import {Input, input} from '@angular/core';
export class WithSettersAndGetters {
// TODO: Skipped for migration because:
// Accessor inputs cannot be migrated as they are too complex.
@Input()
set onlySetter(newValue: any) {
this._bla = newValue;
if (newValue === 0) {
console.log('test');
}
}
private _bla: any;
// TODO: Skipped for migration because:
// Accessor inputs cannot be migrated as they are too complex.
@Input()
get accessor(): string {
return '';
}
set accessor(newValue: string) {
this._accessor = newValue;
}
private _accessor: string = '';
readonly simpleInput = input.required<string>();
}
@@@@@@ with_getters_reference.ts @@@@@@
// tslint:disable
import {WithSettersAndGetters} from './with_getters';
class WithGettersExternalRef {
instance: WithSettersAndGetters = null!;
test() {
if (this.instance.accessor) {
console.log(this.instance.accessor);
}
}
}
@@@@@@ with_jsdoc.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
class WithJsdoc {
/**
* Works
*/
readonly simpleInput = input.required<string>();
readonly withCommentInside = input</* intended */ boolean>();
}
@@@@@@ writing_to_inputs.ts @@@@@@
// tslint:disable
import {input} from '@angular/core';
export class TestCmp {
readonly testParenthesisInput = input(false);
readonly notMutated = input(true);
testParenthesis() {
// prettier-ignore
((this.testParenthesisInput)) = true;
}
testNotMutated() {
let fixture: boolean;
fixture = this.notMutated();
}
}
| {
"end_byte": 29724,
"start_byte": 24863,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden_best_effort.txt"
} |
angular/packages/core/schematics/migrations/signal-migration/test/BUILD.bazel_0_4635 | load("@npm//@angular/build-tooling/bazel/integration:index.bzl", "integration_test")
load("//packages/core/schematics/migrations/signal-migration/test/ts-versions:index.bzl", "TS_VERSIONS")
load("//tools:defaults.bzl", "jasmine_node_test", "nodejs_binary", "ts_library")
ts_library(
name = "test_runners_lib",
testonly = True,
srcs = [
"batch_runner.ts",
"golden_test_runner.ts",
],
deps = [
"//packages/core/schematics/utils/tsurge",
"@npm//chalk",
"@npm//fast-glob",
],
)
nodejs_binary(
name = "golden_test_runner",
testonly = True,
data = [":test_runners_lib"],
entry_point = ":golden_test_runner.ts",
)
nodejs_binary(
name = "batch_runner",
testonly = True,
data = [":test_runners_lib"],
entry_point = ":batch_runner.ts",
)
integration_test(
name = "test",
srcs = [
"golden.txt",
"//packages/core/schematics/migrations/signal-migration/test/golden-test:test_files",
],
commands = [
"$(rootpath //packages/core/schematics/migrations/signal-migration/src:bin) ./golden-test/tsconfig.json --insert-todos",
"$(rootpath :golden_test_runner) ./golden-test ./golden.txt",
],
data = [
":golden_test_runner",
"//packages/core/schematics/migrations/signal-migration/src:bin",
],
environment = {
"FORCE_COLOR": "3",
},
)
[
integration_test(
name = "test_ts_%s" % version,
srcs = [
"golden.txt",
"//packages/core/schematics/migrations/signal-migration/test/golden-test:test_files",
"//packages/core/schematics/migrations/signal-migration/test/ts-versions:hooks.mjs",
"//packages/core/schematics/migrations/signal-migration/test/ts-versions:loader.mjs",
],
commands = [
"$(rootpath //packages/core/schematics/migrations/signal-migration/src:bin) --node_options=--import=./ts-versions/loader.js ./golden-test/tsconfig.json --insert-todos ",
"$(rootpath :golden_test_runner) ./golden-test ./golden.txt",
],
data = [
":golden_test_runner",
"//packages/core/schematics/migrations/signal-migration/src:bin",
"@npm_ts_versions//%s" % version,
],
environment = {
"FORCE_COLOR": "3",
"TS_VERSION_PACKAGE": version,
},
)
for version in TS_VERSIONS
]
integration_test(
name = "test_best_effort",
srcs = [
"golden_best_effort.txt",
"//packages/core/schematics/migrations/signal-migration/test/golden-test:test_files",
],
commands = [
"$(rootpath //packages/core/schematics/migrations/signal-migration/src:bin) ./golden-test/tsconfig.json --best-effort-mode --insert-todos",
"$(rootpath :golden_test_runner) ./golden-test ./golden_best_effort.txt",
],
data = [
":golden_test_runner",
"//packages/core/schematics/migrations/signal-migration/src:bin",
],
environment = {
"FORCE_COLOR": "3",
},
)
integration_test(
name = "test_batch",
size = "large",
srcs = [
"golden.txt",
"//packages/core/schematics/migrations/signal-migration/test/golden-test:test_files",
],
commands = [
"$(rootpath :batch_runner) analyze ./golden-test",
"$(rootpath :batch_runner) combine-all ./golden-test",
"$(rootpath :batch_runner) global-meta ./golden-test",
"$(rootpath :batch_runner) migrate ./golden-test",
"$(rootpath :golden_test_runner) ./golden-test ./golden.txt",
],
data = [
":batch_runner",
":golden_test_runner",
"//packages/core/schematics/migrations/signal-migration/src:batch_test_bin",
"//packages/core/schematics/migrations/signal-migration/src:bin",
],
environment = {
"FORCE_COLOR": "3",
},
tags = [
# Only used for manual verification at this point.
# The test is extremely expensive due to no caching between units.
"manual",
],
tool_mappings = {
"//packages/core/schematics/migrations/signal-migration/src:batch_test_bin": "migration",
},
)
ts_library(
name = "test_lib",
testonly = True,
srcs = ["migration_spec.ts"],
deps = [
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/file_system/testing",
"//packages/core/schematics/migrations/signal-migration/src",
"//packages/core/schematics/utils/tsurge",
],
)
jasmine_node_test(
name = "test_jasmine",
srcs = [":test_lib"],
)
| {
"end_byte": 4635,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/BUILD.bazel"
} |
angular/packages/core/schematics/migrations/signal-migration/test/batch_runner.ts_0_3858 | /**
* @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
*/
/**
* @fileoverview Executes the given migration phase in batch mode.
*
* I.e. The tsconfig of the project is updated to only consider a single
* file. Then the migration is invoked.
*/
import * as childProcess from 'child_process';
import glob from 'fast-glob';
import path from 'path';
import fs from 'fs';
import os from 'os';
const maxParallel = os.cpus().length;
main().catch((e) => {
console.error(e);
process.exitCode = 1;
});
async function main() {
const [mode, sourceDir] = process.argv.slice(2);
const files = glob.sync('**/*', {cwd: sourceDir}).filter((f) => f.endsWith('.ts'));
if (mode === 'analyze') {
const tsconfig = path.join(sourceDir, 'tsconfig.json');
const baseConfig = JSON.parse(fs.readFileSync(tsconfig, 'utf8')) as any;
schedule(files, maxParallel, async (fileName) => {
const tmpTsconfigName = path.join(sourceDir, `${fileName}.tsconfig.json`);
const extractResultFile = path.join(sourceDir, `${fileName}.extract.json`);
// update tsconfig.
await fs.promises.writeFile(
tmpTsconfigName,
JSON.stringify({...baseConfig, include: [fileName]}),
);
// execute command.
const extractResult = await promiseExec(
`migration extract ${path.resolve(tmpTsconfigName)}`,
{env: {...process.env, 'LIMIT_TO_ROOT_NAMES_ONLY': '1'}},
);
// write individual result.
await fs.promises.writeFile(extractResultFile, extractResult);
});
} else if (mode === 'combine-all') {
const metadataFiles = files.map((f) => path.resolve(path.join(sourceDir, `${f}.extract.json`)));
const mergeResult = await promiseExec(`migration combine-all ${metadataFiles.join(' ')}`);
// write merge result.
await fs.promises.writeFile(path.join(sourceDir, 'combined.json'), mergeResult);
} else if (mode === 'global-meta') {
const combinedUnitFile = path.join(sourceDir, 'combined.json');
const globalMeta = await promiseExec(`migration global-meta ${combinedUnitFile}`);
// write global meta result.
await fs.promises.writeFile(path.join(sourceDir, 'global_meta.json'), globalMeta);
} else if (mode === 'migrate') {
schedule(files, maxParallel, async (fileName) => {
const filePath = path.join(sourceDir, fileName);
// tsconfig should exist from analyze phase.
const tmpTsconfigName = path.join(sourceDir, `${fileName}.tsconfig.json`);
const mergeMetadataFile = path.join(sourceDir, 'global_meta.json');
// migrate in parallel.
await promiseExec(
`migration migrate ${path.resolve(tmpTsconfigName)} ${mergeMetadataFile} ${path.resolve(
filePath,
)}`,
{env: {...process.env, 'LIMIT_TO_ROOT_NAMES_ONLY': '1'}},
);
});
}
}
function promiseExec(command: string, opts?: childProcess.ExecOptions): Promise<string> {
return new Promise((resolve, reject) => {
const proc = childProcess.exec(command, opts);
let stdout = '';
proc.stdout?.on('data', (d) => (stdout += d.toString('utf8')));
proc.stderr?.on('data', (d) => process.stderr.write(d.toString('utf8')));
proc.on('close', (code, signal) => {
if (code === 0 && signal === null) {
resolve(stdout);
} else {
reject();
}
});
});
}
async function schedule<T>(
items: T[],
maxParallel: number,
doFn: (v: T) => Promise<void>,
): Promise<void> {
let idx = 0;
let tasks: Promise<void>[] = [];
while (idx < items.length) {
tasks = [];
while (idx < items.length && tasks.length < maxParallel) {
tasks.push(doFn(items[idx]));
idx++;
}
await Promise.all(tasks);
}
}
| {
"end_byte": 3858,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/batch_runner.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden_test_runner.ts_0_1441 | /**
* @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
*/
/**
* @fileoverview Verifies that the contents of the given migration
* directory match the given golden.
*/
import fs from 'fs';
import glob from 'fast-glob';
import chalk from 'chalk';
import path from 'path';
import {diffText} from '../../../utils/tsurge/testing/diff';
const [migratedDir, goldenPath] = process.argv.slice(2);
const files = glob.sync('**/*', {cwd: migratedDir});
let golden = '';
for (const filePath of files) {
if (!filePath.endsWith('.ts') && !filePath.endsWith('.html')) {
continue;
}
const migrateContent = fs.readFileSync(path.join(migratedDir, filePath), 'utf-8');
golden += `@@@@@@ ${filePath} @@@@@@\n\n${migrateContent}`;
}
const diskGolden = fs.readFileSync(goldenPath, 'utf8');
if (diskGolden !== golden) {
if (process.env['BUILD_WORKING_DIRECTORY']) {
fs.writeFileSync(
path.join(
process.env['BUILD_WORKING_DIRECTORY'],
`packages/core/schematics/migrations/signal-migration/test/${goldenPath}`,
),
golden,
);
console.info('Golden updated.');
process.exit(0);
}
process.stderr.write(diffText(diskGolden, golden));
console.error();
console.error();
console.error(chalk.red('Golden does not match.'));
process.exit(1);
}
| {
"end_byte": 1441,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden_test_runner.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/with_getters.ts_0_447 | // tslint:disable
import {Input} from '@angular/core';
export class WithSettersAndGetters {
@Input()
set onlySetter(newValue: any) {
this._bla = newValue;
if (newValue === 0) {
console.log('test');
}
}
private _bla: any;
@Input()
get accessor(): string {
return '';
}
set accessor(newValue: string) {
this._accessor = newValue;
}
private _accessor: string = '';
@Input() simpleInput!: string;
}
| {
"end_byte": 447,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/with_getters.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/index_access_input.ts_0_221 | // tslint:disable
import {Component, Input} from '@angular/core';
@Component({template: ''})
class IndexAccessInput {
@Input() items: string[] = [];
bla() {
const {items} = this;
items[0].charAt(0);
}
}
| {
"end_byte": 221,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/index_access_input.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/external_templates.html_0_22 | <span>{{test}}</span>
| {
"end_byte": 22,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/external_templates.html"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/shared_incompatible_scopes.ts_0_818 | // tslint:disable
import {Input, Directive, Component} from '@angular/core';
@Directive()
class SomeDir {
@Input({required: true}) bla!: RegExp;
}
@Component({
template: ``,
})
export class ScopeMismatchTest {
eachScopeRedeclared() {
const regexs: RegExp[] = [];
if (global.console) {
const dir: SomeDir = null!;
regexs.push(dir.bla);
}
const dir: SomeDir = null!;
regexs.push(dir.bla);
}
nestedButSharedLocal() {
const regexs: RegExp[] = [];
const dir: SomeDir = null!;
if (global.console) {
regexs.push(dir.bla);
}
regexs.push(dir.bla);
}
dir: SomeDir = null!;
nestedButSharedInClassInstance() {
const regexs: RegExp[] = [];
if (global.console) {
regexs.push(this.dir.bla);
}
regexs.push(this.dir.bla);
}
}
| {
"end_byte": 818,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/shared_incompatible_scopes.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/non_null_assertions.ts_0_388 | // tslint:disable
import {Input, Directive} from '@angular/core';
@Directive()
export class NonNullAssertions {
// We can't remove `undefined` from the type here. It's unclear
// whether it was just used as a workaround for required inputs, or
// it was actually meant to be part of the type.
@Input({required: true}) name?: string;
click() {
this.name!.charAt(0);
}
}
| {
"end_byte": 388,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/non_null_assertions.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/temporary_variables.ts_0_354 | // tslint:disable
import {Directive, Input} from '@angular/core';
export class OtherCmp {
@Input() name = false;
}
@Directive()
export class MyComp {
@Input() name = '';
other: OtherCmp = null!;
click() {
if (this.name) {
console.error(this.name);
}
if (this.other.name) {
console.error(this.other.name);
}
}
}
| {
"end_byte": 354,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/temporary_variables.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/modifier_tests.ts_0_412 | // tslint:disable
import {Component, Input} from '@angular/core';
function CustomDecorator() {
return (a: any, b: any) => {};
}
@Component({template: ''})
class ModifierScenarios {
@Input() readonly alreadyReadonly = true;
@Input() protected ImProtected = true;
@Input() protected readonly ImProtectedAndReadonly = true;
@Input() @CustomDecorator() protected readonly usingCustomDecorator = true;
}
| {
"end_byte": 412,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/modifier_tests.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/required-no-explicit-type.ts_0_486 | // tslint:disable
import {Input} from '@angular/core';
import {COMPLEX_VAR} from './required-no-explicit-type-extra';
export const CONST = {field: true};
export class RequiredNoExplicitType {
@Input({required: true}) someInputNumber = 0;
@Input({required: true}) someInput = true;
@Input({required: true}) withConstInitialVal = CONST;
// typing this explicitly now would require same imports as from the `-extra` file.
@Input({required: true}) complexVal = COMPLEX_VAR;
}
| {
"end_byte": 486,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/required-no-explicit-type.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/template_ng_if.ts_0_524 | // tslint:disable
import {Component, Input} from '@angular/core';
@Component({
template: `
@if (first) {
{{first}}
}
<ng-template [ngIf]="second">
{{second}}
</ng-template>
<div *ngIf="third">
{{third}}
</div>
<div *ngIf="fourth">
{{notTheInput}}
</div>
@if (fifth) {
{{notTheInput}}
}
`,
})
export class MyComp {
@Input() first = true;
@Input() second = false;
@Input() third = true;
@Input() fourth = true;
@Input() fifth = true;
}
| {
"end_byte": 524,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/template_ng_if.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/template_concat_string.ts_0_185 | // tslint:disable
import {Component, Input} from '@angular/core';
@Component({
template: '<h3>' + '{{bla}}' + '</h3>',
})
export class WithConcatTemplate {
@Input() bla = true;
}
| {
"end_byte": 185,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/template_concat_string.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/mutate.ts_0_279 | // tslint:disable
import {Input} from '@angular/core';
export class TestCmp {
@Input() shared: {x: string} = {x: ''};
bla() {
this.shared.x = this.doSmth(this.shared);
this.doSmth(this.shared);
}
doSmth(v: typeof this.shared): string {
return v.x;
}
}
| {
"end_byte": 279,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/mutate.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/existing_signal_import.ts_0_166 | // tslint:disable
import {input, Input} from '@angular/core';
class ExistingSignalImport {
signalInput = input<boolean>();
@Input() thisCanBeMigrated = true;
}
| {
"end_byte": 166,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/existing_signal_import.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/constructor_initializations.ts_0_326 | // tslint:disable
import {Input, Directive} from '@angular/core';
@Directive()
export class MyComp {
@Input() firstName: string;
constructor() {
// TODO: Consider initializations inside the constructor.
// Those are not migrated right now though, as they are writes.
this.firstName = 'Initial value';
}
}
| {
"end_byte": 326,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/constructor_initializations.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/manual_instantiations_external.ts_0_149 | // tslint:disable
import {Component, Input} from '@angular/core';
@Component({})
export class ManualInstantiation {
@Input() bla: string = '';
}
| {
"end_byte": 149,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/manual_instantiations_external.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/derived_class_meta_input_alias.ts_0_246 | // tslint:disable
import {Input, Directive} from '@angular/core';
@Directive()
class Base {
// should not be migrated.
@Input() bla = true;
}
@Directive({
inputs: [{name: 'bla', alias: 'matDerivedBla'}],
})
class Derived extends Base {}
| {
"end_byte": 246,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/derived_class_meta_input_alias.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/inline_template.ts_0_235 | // tslint:disable
import {Component, Input} from '@angular/core';
@Component({
template: `
<div *someTemplateDir [style.ok]="justify">
</div>
`,
})
export class InlineTmpl {
@Input() justify: 'start' | 'end' = 'end';
}
| {
"end_byte": 235,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/inline_template.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/spy_on.ts_0_164 | // tslint:disable
import {Input} from '@angular/core';
class MyComp {
@Input() myInput = () => {};
}
spyOn<MyComp>(new MyComp(), 'myInput').and.returnValue();
| {
"end_byte": 164,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/spy_on.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/both_input_imports.ts_0_276 | // tslint:disable
import {input, Input} from '@angular/core';
class BothInputImported {
@Input() decoratorInput = true;
signalInput = input<boolean>();
@Input() thisCanBeMigrated = true;
__makeDecoratorInputNonMigratable() {
this.decoratorInput = false;
}
}
| {
"end_byte": 276,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/both_input_imports.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/transform_functions.ts_0_761 | // tslint:disable
import {Input} from '@angular/core';
import {COMPLEX_VAR} from './required-no-explicit-type-extra';
function x(v: string | undefined): string | undefined {
return v;
}
export class TransformFunctions {
// We can check this, and expect `as any` due to transform incompatibility.
@Input({required: true, transform: (v: string | undefined) => ''}) withExplicitTypeWorks: {
ok: true;
} = null!;
// This will be a synthetic type because we add `undefined` to `boolean`.
@Input({required: true, transform: x}) synthetic1?: boolean;
// Synthetic as we infer a full type from the initial value. Cannot be checked.
@Input({required: true, transform: (v: string | undefined) => ''}) synthetic2 = {
infer: COMPLEX_VAR,
};
}
| {
"end_byte": 761,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/transform_functions.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/jit_true_components.ts_0_527 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// tslint:disable
import {Component, Input} from '@angular/core';
@Component({
jit: true,
template: '{{test}}',
})
class JitTrueComponent {
@Input() test = true;
}
@Component({
jit: true,
templateUrl: './jit_true_component_external_tmpl.html',
})
class JitTrueComponentExternalTmpl {
@Input() test = true;
}
| {
"end_byte": 527,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/jit_true_components.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/catalyst_test.ts_0_472 | // tslint:disable
import {Input} from '@angular/core';
// google3/javascript/angular2/testing/catalyst/fake_async
// ^^ this allows the advisor to even consider this file.
function it(msg: string, fn: () => void) {}
function bootstrapTemplate(tmpl: string, inputs: unknown) {}
class MyComp {
@Input() hello = '';
}
it('should work', () => {
const inputs = {
hello: 'test',
} as Partial<MyComp>;
bootstrapTemplate('<my-comp [hello]="hello">', inputs);
});
| {
"end_byte": 472,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/catalyst_test.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/optional_inputs.ts_0_168 | // tslint:disable
import {Directive, Input} from '@angular/core';
@Directive()
class OptionalInput {
@Input() bla?: string;
@Input() isLegacyHttpOnly? = false;
}
| {
"end_byte": 168,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/optional_inputs.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/ternary_narrowing.ts_0_584 | // tslint:disable
import {Component, Input} from '@angular/core';
@Component({
template: `
{{ narrowed ? narrowed.substring(0, 1) : 'Empty' }}
{{ justChecked ? 'true' : 'false' }}
{{ other?.safeRead ? other.safeRead : 'Empty' }}
{{ other?.safeRead2 ? other?.safeRead2 : 'Empty' }}
`,
})
export class TernaryNarrowing {
@Input() narrowed: string | undefined = undefined;
@Input() justChecked = true;
other?: OtherComponent;
}
@Component({template: ''})
export class OtherComponent {
@Input() safeRead: string = '';
@Input() safeRead2: string = '';
}
| {
"end_byte": 584,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/ternary_narrowing.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/host_bindings.ts_0_834 | // tslint:disable
import {Component, Input, HostBinding} from '@angular/core';
@Component({
template: '',
host: {
'[id]': 'id',
'[nested]': 'nested.id',
'[receiverNarrowing]': 'receiverNarrowing ? receiverNarrowing.id',
// normal narrowing is irrelevant as we don't type check host bindings.
},
})
class HostBindingTestCmp {
@Input() id = 'works';
// for testing nested expressions.
nested = this;
declare receiverNarrowing: this | undefined;
@HostBinding('[attr.bla]')
@Input()
myInput = 'initial';
}
const SHARED = {
'(click)': 'id',
'(mousedown)': 'id2',
};
@Component({
template: '',
host: SHARED,
})
class HostBindingsShared {
@Input() id = false;
}
@Component({
template: '',
host: SHARED,
})
class HostBindingsShared2 {
@Input() id = false;
@Input() id2 = false;
}
| {
"end_byte": 834,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/host_bindings.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/catalyst_async_test.ts_0_467 | // tslint:disable
import {Input} from '@angular/core';
// google3/javascript/angular2/testing/catalyst/async
// ^^ this allows the advisor to even consider this file.
function it(msg: string, fn: () => void) {}
function bootstrapTemplate(tmpl: string, inputs: unknown) {}
class MyComp {
@Input() hello = '';
}
it('should work', () => {
const inputs = {
hello: 'test',
} as Partial<MyComp>;
bootstrapTemplate('<my-comp [hello]="hello">', inputs);
});
| {
"end_byte": 467,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/catalyst_async_test.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/template_writes.ts_0_359 | // tslint:disable
import {Component, Input} from '@angular/core';
@Component({
template: `
<input [(ngModel)]="inputA" />
<div (click)="inputB = false">
</div>
`,
host: {
'(click)': 'inputC = true',
},
})
class TwoWayBinding {
@Input() inputA = '';
@Input() inputB = true;
@Input() inputC = false;
@Input() inputD = false;
}
| {
"end_byte": 359,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/template_writes.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/imports.ts_0_160 | // tslint:disable
// prettier-ignore
import {
Directive,
Input
} from '@angular/core';
@Directive()
export class TestCmp {
@Input() disabled = false;
}
| {
"end_byte": 160,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/imports.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/derived_class_second_separate.ts_0_367 | // tslint:disable
import {Input} from '@angular/core';
import {DerivedExternalWithInput} from './derived_class_separate_file';
class Derived extends DerivedExternalWithInput {
// this should be incompatible, because the final superclass
// within its own batch unit, detected a write that should
// propagate to this input.
@Input() override bla = false;
}
| {
"end_byte": 367,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/derived_class_second_separate.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/catalyst_test_partial.ts_0_430 | // tslint:disable
import {Component, Input} from '@angular/core';
// @ts-ignore
import {} from 'google3/javascript/angular2/testing/catalyst/fake_async';
function renderComponent(inputs: Partial<TestableSecondaryRangePicker> = {}) {}
@Component({
standalone: false,
jit: true,
template: '<bla [(ngModel)]="incompatible">',
})
class TestableSecondaryRangePicker {
@Input() bla = true;
@Input() incompatible = true;
}
| {
"end_byte": 430,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/catalyst_test_partial.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/manual_instantiations.ts_0_117 | // tslint:disable
import {ManualInstantiation} from './manual_instantiations_external';
new ManualInstantiation();
| {
"end_byte": 117,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/manual_instantiations.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/safe_property_reads.ts_0_417 | /**
* @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
*/
// tslint:disable
import {Component, Input} from '@angular/core';
@Component({
template: `
{{bla?.myInput}}
`,
})
class WithSafePropertyReads {
@Input() myInput = 0;
bla: this | undefined = this;
}
| {
"end_byte": 417,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/safe_property_reads.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/required.ts_0_109 | // tslint:disable
import {Input} from '@angular/core';
class Required {
@Input() simpleInput!: string;
}
| {
"end_byte": 109,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/required.ts"
} |
angular/packages/core/schematics/migrations/signal-migration/test/golden-test/external_templates.ts_0_211 | // tslint:disable
import {Component, Input} from '@angular/core';
@Component({
templateUrl: './external_templates.html',
selector: 'with-template',
})
export class WithTemplate {
@Input() test = true;
}
| {
"end_byte": 211,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/schematics/migrations/signal-migration/test/golden-test/external_templates.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.