Best JavaScript code snippet using ts-auto-mock
ng_declaration_collector.ts
Source:ng_declaration_collector.ts
1/**2 * @license3 * Copyright Google Inc. All Rights Reserved.4 *5 * Use of this source code is governed by an MIT-style license that can be6 * found in the LICENSE file at https://angular.io/license7 */8import {Reference} from '@angular/compiler-cli/src/ngtsc/imports';9import {PartialEvaluator, ResolvedValue} from '@angular/compiler-cli/src/ngtsc/partial_evaluator';10import * as ts from 'typescript';11import {NgDecorator, getAngularDecorators} from '../../utils/ng_decorators';12import {getPropertyNameText} from '../../utils/typescript/property_name';13/**14 * Visitor that walks through specified TypeScript nodes and collects all defined15 * directives and provider classes. Directives are separated by decorated and16 * undecorated directives.17 */18export class NgDeclarationCollector {19 /** List of resolved directives which are decorated. */20 decoratedDirectives: ts.ClassDeclaration[] = [];21 /** List of resolved providers which are decorated. */22 decoratedProviders: ts.ClassDeclaration[] = [];23 /** Set of resolved Angular declarations which are not decorated. */24 undecoratedDeclarations = new Set<ts.ClassDeclaration>();25 constructor(public typeChecker: ts.TypeChecker, private evaluator: PartialEvaluator) {}26 visitNode(node: ts.Node) {27 if (ts.isClassDeclaration(node)) {28 this._visitClassDeclaration(node);29 }30 ts.forEachChild(node, n => this.visitNode(n));31 }32 private _visitClassDeclaration(node: ts.ClassDeclaration) {33 if (!node.decorators || !node.decorators.length) {34 return;35 }36 const ngDecorators = getAngularDecorators(this.typeChecker, node.decorators);37 const ngModuleDecorator = ngDecorators.find(({name}) => name === 'NgModule');38 if (hasDirectiveDecorator(node, this.typeChecker, ngDecorators)) {39 this.decoratedDirectives.push(node);40 } else if (hasInjectableDecorator(node, this.typeChecker, ngDecorators)) {41 this.decoratedProviders.push(node);42 } else if (ngModuleDecorator) {43 this._visitNgModuleDecorator(ngModuleDecorator);44 }45 }46 private _visitNgModuleDecorator(decorator: NgDecorator) {47 const decoratorCall = decorator.node.expression;48 const metadata = decoratorCall.arguments[0];49 if (!metadata || !ts.isObjectLiteralExpression(metadata)) {50 return;51 }52 let entryComponentsNode: ts.Expression|null = null;53 let declarationsNode: ts.Expression|null = null;54 metadata.properties.forEach(p => {55 if (!ts.isPropertyAssignment(p)) {56 return;57 }58 const name = getPropertyNameText(p.name);59 if (name === 'entryComponents') {60 entryComponentsNode = p.initializer;61 } else if (name === 'declarations') {62 declarationsNode = p.initializer;63 }64 });65 // In case the module specifies the "entryComponents" field, walk through all66 // resolved entry components and collect the referenced directives.67 if (entryComponentsNode) {68 flattenTypeList(this.evaluator.evaluate(entryComponentsNode)).forEach(ref => {69 if (ts.isClassDeclaration(ref.node) &&70 !hasNgDeclarationDecorator(ref.node, this.typeChecker)) {71 this.undecoratedDeclarations.add(ref.node);72 }73 });74 }75 // In case the module specifies the "declarations" field, walk through all76 // resolved declarations and collect the referenced directives.77 if (declarationsNode) {78 flattenTypeList(this.evaluator.evaluate(declarationsNode)).forEach(ref => {79 if (ts.isClassDeclaration(ref.node) &&80 !hasNgDeclarationDecorator(ref.node, this.typeChecker)) {81 this.undecoratedDeclarations.add(ref.node);82 }83 });84 }85 }86}87/** Flattens a list of type references. */88function flattenTypeList(value: ResolvedValue): Reference[] {89 if (Array.isArray(value)) {90 return <Reference[]>value.reduce(91 (res: Reference[], v: ResolvedValue) => res.concat(flattenTypeList(v)), []);92 } else if (value instanceof Reference) {93 return [value];94 }95 return [];96}97/** Checks whether the given node has the "@Directive" or "@Component" decorator set. */98export function hasDirectiveDecorator(99 node: ts.ClassDeclaration, typeChecker: ts.TypeChecker, ngDecorators?: NgDecorator[]): boolean {100 return (ngDecorators || getNgClassDecorators(node, typeChecker))101 .some(({name}) => name === 'Directive' || name === 'Component');102}103/** Checks whether the given node has the "@Injectable" decorator set. */104export function hasInjectableDecorator(105 node: ts.ClassDeclaration, typeChecker: ts.TypeChecker, ngDecorators?: NgDecorator[]): boolean {106 return (ngDecorators || getNgClassDecorators(node, typeChecker))107 .some(({name}) => name === 'Injectable');108}109/** Whether the given node has an explicit decorator that describes an Angular declaration. */110export function hasNgDeclarationDecorator(node: ts.ClassDeclaration, typeChecker: ts.TypeChecker) {111 return getNgClassDecorators(node, typeChecker)112 .some(({name}) => name === 'Component' || name === 'Directive' || name === 'Pipe');113}114/** Gets all Angular decorators of a given class declaration. */115export function getNgClassDecorators(116 node: ts.ClassDeclaration, typeChecker: ts.TypeChecker): NgDecorator[] {117 if (!node.decorators) {118 return [];119 }120 return getAngularDecorators(typeChecker, node.decorators);...
util.ts
Source:util.ts
1/**2 * @license3 * Copyright Google LLC All Rights Reserved.4 *5 * Use of this source code is governed by an MIT-style license that can be6 * found in the LICENSE file at https://angular.io/license7 */8import ts from 'typescript';9import {getImportSpecifier} from '../../utils/typescript/imports';10export const classes = new Set(['FormArray', 'FormBuilder', 'FormControl', 'FormGroup']);11export const formControl = 'FormControl';12export const untypedPrefix = 'Untyped';13export const forms = '@angular/forms';14export interface MigratableNode {15 node: ts.Node;16 importName: string;17}18export type rewriteFn = (startPos: number, origLength: number, text: string) => void;19export function migrateFile(20 sourceFile: ts.SourceFile, typeChecker: ts.TypeChecker, rewrite: rewriteFn) {21 const imports = getImports(sourceFile);22 // If no relevant classes are imported, we can exit early.23 if (imports.length === 0) return;24 // For each control class, migrate all of its uses.25 for (let i = imports.length; i >= 0; i--) {26 const imp = imports[i];27 const usages = getUsages(sourceFile, typeChecker, imp);28 if (usages.length === 0) {29 // Since there are no usages of this class we need to migrate it, we should completely30 // skip it for the subsequent migration steps.31 imports.splice(i, 1);32 }33 for (const usage of usages) {34 const newName = getUntypedVersionOfImportOrName(usage.importName);35 if (newName === null) {36 // This should never happen.37 console.error(38 `Typed forms migration error: unknown replacement for usage ${usage.node.getText()}`);39 continue;40 }41 rewrite(usage.node.getStart(), usage.node.getWidth(), newName);42 }43 }44 // For each imported control class, migrate to the corresponding uptyped import.45 for (const imp of imports) {46 const untypedClass = getUntypedVersionOfImportOrName(imp.getText());47 if (untypedClass === null) {48 // This should never happen.49 console.error(50 `Typed forms migration error: unknown untyped version of import ${imp.getText()}`);51 continue;52 }53 if (getImportSpecifier(sourceFile, forms, untypedClass)) {54 // In order to make the migration idempotent, we must check whether the untyped version of the55 // class is already present. If present, immediately continue.56 continue;57 }58 rewrite(imp.getStart(), imp.getWidth(), untypedClass);59 }60}61function getImports(sourceFile: ts.SourceFile): ts.ImportSpecifier[] {62 let imports: ts.ImportSpecifier[] = [];63 for (const cc of classes) {64 const specifier = getImportSpecifier(sourceFile, forms, cc);65 if (!specifier) continue;66 imports.push(specifier);67 }68 return imports;69}70function getUntypedVersionOfImportOrName(name: string): string|null {71 for (const cc of classes) {72 if (name.includes(cc)) {73 return `${untypedPrefix}${cc}`;74 }75 }76 return null;77}78function getUsages(79 sourceFile: ts.SourceFile, typeChecker: ts.TypeChecker,80 importSpecifier: ts.ImportSpecifier): MigratableNode[] {81 const usages: MigratableNode[] = [];82 const visitNode = (node: ts.Node) => {83 if (ts.isImportSpecifier(node)) {84 // Skip this node and all of its children; imports are a special case.85 return;86 }87 if (ts.isIdentifier(node) && isUsageOfFormsImport(typeChecker, node, importSpecifier)) {88 usages.push({node, importName: importSpecifier.getText()});89 }90 ts.forEachChild(node, visitNode);91 };92 ts.forEachChild(sourceFile, visitNode);93 return usages;94}95function isUsageOfFormsImport(96 typeChecker: ts.TypeChecker, node: ts.Identifier,97 importSpecifier: ts.ImportSpecifier): boolean {98 const symbol = typeChecker.getSymbolAtLocation(node);99 // We check symbol.declarations because we actually care about the name at the declaration site,100 // not the usage site. These could be different in the case of overriden constructors.101 if (!symbol || symbol.declarations === undefined || !symbol.declarations.length) return false;102 const decl = symbol.declarations[0];103 if (!ts.isImportSpecifier(decl)) return false;104 // As per `typescript/imports.ts`, we must walk up the tree to find the enclosing import105 // declaration. For reasons specific to the TS AST, this is always 3 levels up from an import106 // specifier node.107 const importDecl = decl.parent.parent.parent;108 if (!ts.isStringLiteral(importDecl.moduleSpecifier)) return false;109 const importName = typeChecker.getTypeAtLocation(importSpecifier)?.getSymbol()?.getName();110 if (!importName) return false;111 // Handles aliased imports: e.g. "import {Component as myComp} from ...";112 const declName = decl.propertyName ? decl.propertyName.text : decl.name.text;113 if (importName === declName) return true;114 // In the case of FormControl's overridden exported constructor, the value name and declaration115 // name are not exactly the same. For our purposes, it's enough to check whether the latter is a116 // substring of the former.117 if (declName === formControl && importName.includes(declName)) return true;118 return false;...
symbol.ts
Source:symbol.ts
1/**2 * @license3 * Copyright Google LLC All Rights Reserved.4 *5 * Use of this source code is governed by an MIT-style license that can be6 * found in the LICENSE file at https://angular.io/license7 */8import ts from 'typescript';9export function getValueSymbolOfDeclaration(node: ts.Node, typeChecker: ts.TypeChecker): ts.Symbol|10 undefined {11 let symbol = typeChecker.getSymbolAtLocation(node);12 while (symbol && symbol.flags & ts.SymbolFlags.Alias) {13 symbol = typeChecker.getAliasedSymbol(symbol);14 }15 return symbol;16}17/** Checks whether a node is referring to a specific import specifier. */18export function isReferenceToImport(19 typeChecker: ts.TypeChecker, node: ts.Node, importSpecifier: ts.ImportSpecifier): boolean {20 const nodeSymbol = typeChecker.getTypeAtLocation(node).getSymbol();21 const importSymbol = typeChecker.getTypeAtLocation(importSpecifier).getSymbol();22 return !!(nodeSymbol?.declarations?.[0] && importSymbol?.declarations?.[0]) &&23 nodeSymbol.declarations[0] === importSymbol.declarations[0];24}25/** Checks whether a node's type is nullable (`null`, `undefined` or `void`). */26export function isNullableType(typeChecker: ts.TypeChecker, node: ts.Node) {27 // Skip expressions in the form of `foo.bar!.baz` since the `TypeChecker` seems28 // to identify them as null, even though the user indicated that it won't be.29 if (node.parent && ts.isNonNullExpression(node.parent)) {30 return false;31 }32 const type = typeChecker.getTypeAtLocation(node);33 const typeNode = typeChecker.typeToTypeNode(type, undefined, ts.NodeBuilderFlags.None);34 let hasSeenNullableType = false;35 // Trace the type of the node back to a type node, walk36 // through all of its sub-nodes and look for nullable tyes.37 if (typeNode) {38 (function walk(current: ts.Node) {39 if (current.kind === ts.SyntaxKind.NullKeyword ||40 current.kind === ts.SyntaxKind.UndefinedKeyword ||41 current.kind === ts.SyntaxKind.VoidKeyword) {42 hasSeenNullableType = true;43 // Note that we don't descend into type literals, because it may cause44 // us to mis-identify the root type as nullable, because it has a nullable45 // property (e.g. `{ foo: string | null }`).46 } else if (!hasSeenNullableType && !ts.isTypeLiteralNode(current)) {47 current.forEachChild(walk);48 }49 })(typeNode);50 }51 return hasSeenNullableType;52}53/**54 * Walks through the types and sub-types of a node, looking for a55 * type that has the same name as one of the passed-in ones.56 */57export function hasOneOfTypes(58 typeChecker: ts.TypeChecker, node: ts.Node, types: string[]): boolean {59 const type = typeChecker.getTypeAtLocation(node);60 const typeNode =61 type ? typeChecker.typeToTypeNode(type, undefined, ts.NodeBuilderFlags.None) : undefined;62 let hasMatch = false;63 if (typeNode) {64 (function walk(current: ts.Node) {65 if (ts.isIdentifier(current) && types.includes(current.text)) {66 hasMatch = true;67 } else if (!hasMatch && !ts.isTypeLiteralNode(current)) {68 current.forEachChild(walk);69 }70 })(typeNode);71 }72 return hasMatch;...
wrapped-symbol.ts
Source:wrapped-symbol.ts
1import ts from "typescript";2export class WrappedSymbol {3 typeChecker: ts.TypeChecker;4 symbol: ts.Symbol;5 constructor(typeChecker: ts.TypeChecker, symbol: ts.Symbol) {6 this.typeChecker = typeChecker;7 this.symbol = symbol;8 }9 public get isFunctionDeclaration(): boolean {10 if (this.symbol.valueDeclaration) {11 return ts.isFunctionDeclaration(this.symbol.valueDeclaration);12 }13 return false;14 }15 public get isModuleDeclaration(): boolean {16 if (this.symbol.valueDeclaration) {17 return ts.isModuleDeclaration(this.symbol.valueDeclaration);18 }19 return false;20 }21 public get exports(): WrappedSymbol[] {22 const exports: WrappedSymbol[] = [];23 if (this.symbol.exports) {24 this.symbol.exports.forEach((sym, _) => {25 exports.push(26 new WrappedSymbol(this.typeChecker, sym).aliasedSymbolIfNecessary27 );28 });29 }30 return exports;31 }32 public get aliasedSymbolIfNecessary(): WrappedSymbol {33 if ((this.symbol.flags & ts.SymbolFlags.Alias) !== 0) {34 const newSymbol: ts.Symbol = this.typeChecker.getAliasedSymbol(35 this.symbol36 );37 return new WrappedSymbol(this.typeChecker, newSymbol);38 }39 return this;40 }41 public get comment(): string {42 return ts.displayPartsToString(43 this.symbol.getDocumentationComment(this.typeChecker)44 );45 }46 public get name(): string {47 return this.symbol.getName();48 }49}50// interface DocEntry {51// name?: string;52// fileName?: string;53// documentation?: string;54// type?: string;55// constructors?: DocEntry[];56// parameters?: DocEntry[];57// returnType?: string;...
Using AI Code Generation
1import { typeChecker } from 'ts-auto-mock';2import { typeChecker } from 'ts-auto-mock';3import { typeChecker } from 'ts-auto-mock';4import { typeChecker } from 'ts-auto-mock';5import { typeChecker } from 'ts-auto-mock';6import { typeChecker } from 'ts-auto-mock';7import { typeChecker } from 'ts-auto-mock';8import { typeChecker } from 'ts-auto-mock';9import { typeChecker } from 'ts-auto-mock';10import { typeChecker } from 'ts-auto-mock';11import { typeChecker } from 'ts-auto-mock';12import { typeChecker } from 'ts-auto-mock';13import { typeChecker } from 'ts-auto-mock';14import { typeChecker } from 'ts-auto-mock';15import { typeChecker } from 'ts-auto-mock';16import { typeChecker } from 'ts-auto
Using AI Code Generation
1import { typeChecker } from 'ts-auto-mock';2import { mock } from 'ts-mock-imports';3import * as jest from 'jest';4const testMock = mock('./test');5jest.mock('./test');6const testMock = typeChecker('./test');7testMock.mock('testFunction', () => {8 return 'test';9});10jest.mock('./test', () => {11 return {12 testFunction: () => {13 return 'test';14 }15 };16});17const testMock = typeChecker('./test');18testMock.mock('testFunction', () => {19 return 'test';20});21testMock.restoreAll();22jest.restoreAllMocks();23const testMock = typeChecker('./test');24testMock.restoreAll();25testMock.restore('testFunction');26jest.restoreAllMocks();27const testMock = typeChecker('./test');28testMock.restore('testFunction');29const testFunction = testMock.imported.testFunction;30const testFunction = require('./test').testFunction;31const testFunction = typeChecker('./test').imported.testFunction;32const testFunction = testMock.mocked.testFunction;33const testFunction = jest.fn();34const testFunction = jest.fn();35const testFunction = testMock.mocked.testFunction;36const testFunction = jest.fn();37const testFunction = jest.fn();38const testFunction = testMock.imported.testFunction;39const testFunction = require('./test').testFunction;
Using AI Code Generation
1import {typeChecker} from 'ts-auto-mock';2const type = typeChecker('name of the type');3import {typeChecker} from 'ts-auto-mock';4const type = typeChecker('name of the type');5import {typeChecker} from 'ts-auto-mock';6const type = typeChecker('name of the type');7import {typeChecker} from 'ts-auto-mock';8const type = typeChecker('name of the type');9import {typeChecker} from 'ts-auto-mock';10const type = typeChecker('name of the type');11import {typeChecker} from 'ts-auto-mock';12const type = typeChecker('name of the type');13import {typeChecker} from 'ts-auto-mock';14const type = typeChecker('name of the type');15import {typeChecker} from 'ts-auto-mock';16const type = typeChecker('name of the type');17import {typeChecker} from 'ts-auto-mock';18const type = typeChecker('name of the type');19import {typeChecker} from 'ts-auto-mock';20const type = typeChecker('name of the type');
Using AI Code Generation
1import { typeChecker } from 'ts-auto-mock';2import { createMock } from 'ts-auto-mock/extension';3const mock = createMock<SomeInterface>();4import { typeChecker } from 'ts-auto-mock';5import { createMock } from 'ts-auto-mock/extension';6const mock = createMock<SomeInterface>();7import { typeChecker } from 'ts-auto-mock';8import { createMock } from 'ts-auto-mock/extension';9const mock = createMock<SomeInterface>();10import { typeChecker } from 'ts-auto-mock';11import { createMock } from 'ts-auto-mock/extension';12const mock = createMock<SomeInterface>();13import { typeChecker } from 'ts-auto-mock';14import { createMock } from 'ts-auto-mock/extension';15const mock = createMock<SomeInterface>();16import { typeChecker } from 'ts-auto-mock';17import { createMock } from 'ts-auto-mock/extension';18const mock = createMock<SomeInterface>();19import { typeChecker } from 'ts-auto-mock';20import { createMock } from 'ts-auto-mock/extension';21const mock = createMock<SomeInterface>();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!